8c52d53ffa921839d491a76ed137c0aeccfef971
[spider.git] / src / client.c
1 /*
2  * C Client for the DX Spider cluster program
3  *
4  * Eventually this program will be a complete replacement
5  * for the perl version.
6  *
7  * This program provides the glue necessary to talk between
8  * an input (eg from telnet or ax25) and the perl DXSpider
9  * node.
10  *
11  * Currently, this program connects STDIN/STDOUT to the
12  * message system used by cluster.pl
13  *
14  * Copyright (c) 2000 Dirk Koopman G1TLH
15  *
16  * $Id$
17  */
18
19 #include <stdio.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <netdb.h>
27 #include <sys/socket.h>
28 #include <netinet/in.h>
29 #include <errno.h>
30 #include <signal.h>
31 #include <string.h>
32 #include <termios.h>
33 #include <regex.h>
34
35 #include "sel.h"
36 #include "cmsg.h"
37 #include "debug.h"
38
39 #define TEXT 1
40 #define MSG 2
41 #define MAXBUFL 1024
42
43 #ifndef MAXPATHLEN 
44 #define MAXPATHLEN 256
45 #endif
46
47 #define DEFPACLEN 128
48 #define MAXPACLEN 236
49 #define MAXCALLSIGN 9
50
51 #define DBUF 1
52 #define DMSG 2
53
54 typedef struct 
55 {
56         int cnum;                                       /* the connection number */
57         int sort;                                       /* the type of connection either text or msg */
58         cmsg_t *in;                                     /* current input message being built up */
59         cmsg_t *out;                            /* current output message being sent */
60         cmsg_t *obuf;                           /* current output being buffered */
61         reft *inq;                                      /* input queue */
62         reft *outq;                                     /* output queue */
63         sel_t *sp;                                      /* my select fcb address */
64         struct termios t;                       /* any termios associated with this cnum */
65         char echo;                                      /* echo characters back to this cnum */
66         char t_set;                                     /* the termios structure is valid */
67         char buffer_it;                         /* buffer outgoing packets for paclen */
68 } fcb_t;
69
70 typedef struct 
71 {
72         char *in;
73         regex_t *regex;
74 } myregex_t;
75
76
77 char *node_addr = "localhost";  /* the node tcp address, can be overridden by DXSPIDER_HOST */
78 int node_port = 27754;                  /* the tcp port of the node at the above address can be overidden by DXSPIDER_PORT*/
79 char *call;                                             /* the caller's callsign */
80 char *connsort;                                 /* the type of connection */
81 fcb_t *in;                                              /* the fcb of 'stdin' that I shall use */
82 fcb_t *node;                                    /* the fcb of the msg system */
83 char nl = '\n';                                 /* line end character */
84 char ending = 0;                                /* set this to end the program */
85 char send_Z = 1;                                /* set a Z record to the node on termination */
86 char echo = 1;                                  /* echo characters on stdout from stdin */
87 char int_tabs = 0;                              /* interpret tabs -> spaces */
88 char *root = "/spider";         /* root of data tree, can be overridden by DXSPIDER_ROOT  */
89 int timeout = 60;                               /* default timeout for logins and things */
90 int paclen = DEFPACLEN;                 /* default buffer size for outgoing packets */
91 int tabsize = 8;                                /* default tabsize for text messages */
92
93 myregex_t iscallreg[] = {               /* regexes to determine whether this is a reasonable callsign */
94         {
95                 "^[A-Z]+[0-9]+[A-Z]+[1-9]?$", 0                /* G1TLH G1TLH1 */
96         },
97         {
98                 "^[0-9]+[A-Z]+[0-9]+[A-Z]+[1-9]?$", 0          /* 2E0AAA 2E0AAA1 */
99         },
100         {
101                 "^[A-Z]+[0-9]+[A-Z]+-[1-9]$", 0                /* G1TLH-2 */
102         },
103         {
104                 "^[0-9]+[A-Z]+[0-9]+[A-Z]+-[1-9]$", 0          /* 2E0AAA-2 */
105         },
106         {
107                 "^[A-Z]+[0-9]+[A-Z]+-1[0-5]$", 0               /* G1TLH-11 */
108         },
109         {
110                 "^[0-9]+[A-Z]+[0-9]+[A-Z]+-1[0-5]$", 0         /* 2E0AAA-11 */
111         },
112         {
113                 0, 0
114         }
115 };
116
117 void terminate(int);
118
119 /*
120  * utility routines - various
121  */
122
123 void die(char *s, ...)
124 {
125         char buf[2000];
126         
127         va_list ap;
128         va_start(ap, s);
129         vsnprintf(buf, sizeof(buf)-1, s, ap);
130         va_end(ap);
131         fprintf(stderr,"%s\n", buf);
132         terminate(-1);
133 }
134
135 char *strupper(char *s)
136 {
137         char *d = malloc(strlen(s)+1);
138         char *p = d;
139         
140         if (!d)
141                 die("out of room in strupper");
142         while (*p++ = toupper(*s++)) ;
143         return d;
144 }
145
146 char *strlower(char *s)
147 {
148         char *d = malloc(strlen(s)+1);
149         char *p = d;
150         
151         if (!d)
152                 die("out of room in strlower");
153         while (*p++ = tolower(*s++)) ;
154         return d;
155 }
156
157 int eq(char *a, char *b)
158 {
159         return (strcmp(a, b) == 0);
160 }
161
162 int xopen(char *dir, char *name, int mode)
163 {
164         char fn[MAXPATHLEN+1];
165         snprintf(fn, MAXPATHLEN, "%s/%s/%s", root, dir, name);
166         return open(fn, mode);
167 }
168
169 int iscallsign(char *s)
170 {
171         myregex_t *rp;
172
173         if (strlen(s) > MAXCALLSIGN)
174                 return 0;
175         
176         for (rp = iscallreg; rp->in; ++rp) {
177                 if (regexec(rp->regex, s, 0, 0, 0) == 0)
178                         return 1;
179         }
180         return 0;
181 }
182
183 /*
184  * higher level send and receive routines
185  */
186
187 fcb_t *fcb_new(int cnum, int sort)
188 {
189         fcb_t *f = malloc(sizeof(fcb_t));
190         if (!f)
191                 die("no room in fcb_new");
192         memset (f, 0, sizeof(fcb_t));
193         f->cnum = cnum;
194         f->sort = sort;
195         f->inq = chain_new();
196         f->outq = chain_new();
197         return f;
198 }
199
200 void flush_text(fcb_t *f)
201 {
202         if (f->obuf) {
203                 cmsg_send(f->outq, f->obuf, 0);
204                 f->sp->flags |= SEL_OUTPUT;
205                 f->obuf = 0;
206         }
207 }
208
209 void send_text(fcb_t *f, char *s, int l)
210 {
211         cmsg_t *mp;
212         char *p;
213         
214         if (f->buffer_it && f->obuf) {
215                 mp = f->obuf;
216         } else {
217                 f->obuf = mp = cmsg_new(paclen+1, f->sort, f);
218         }
219
220         /* remove trailing spaces  */
221         while (l > 0 &&isspace(s[l-1]))
222                 --l;
223
224         for (p = s; p < s+l; ) {
225                 if (mp->inp >= mp->data + paclen) {
226                         flush_text(f);
227                         f->obuf = mp = cmsg_new(paclen+1, f->sort, f);
228                 }
229                 *mp->inp++ = *p++;
230         }
231         if (mp->inp >= mp->data + paclen) {
232                 flush_text(f);
233                 f->obuf = mp = cmsg_new(paclen+1, f->sort, f);
234         }
235         *mp->inp++ = nl;
236         if (!f->buffer_it)
237                 flush_text(f);
238 }
239
240 void send_msg(fcb_t *f, char let, char *s, int l)
241 {
242         cmsg_t *mp;
243         int ln;
244         int myl = strlen(call)+2+l;
245
246         mp = cmsg_new(myl+4+1, f->sort, f);
247         ln = htonl(myl);
248         memcpy(mp->inp, &ln, 4);
249         mp->inp += 4;
250         *mp->inp++ = let;
251         strcpy(mp->inp, call);
252         mp->inp += strlen(call);
253         *mp->inp++ = '|';
254         if (l > 0) {
255                 memcpy(mp->inp, s, l);
256                 mp->inp += l;
257         }
258         *mp->inp = 0;
259         cmsg_send(f->outq, mp, 0);
260         f->sp->flags |= SEL_OUTPUT;
261 }
262
263 /*
264  * the callback (called by sel_run) that handles all the inputs and outputs
265  */
266
267 int fcb_handler(sel_t *sp, int in, int out, int err)
268 {
269         fcb_t *f = sp->fcb;
270         cmsg_t *mp, *omp;
271         
272         /* input modes */
273         if (in) {
274                 char *p, buf[MAXBUFL];
275                 int r;
276
277                 /* read what we have into a buffer */
278                 r = read(f->cnum, buf, MAXBUFL);
279                 if (r < 0) {
280                         switch (errno) {
281                         case EINTR:
282                         case EINPROGRESS:
283                         case EAGAIN:
284                                 goto lout;
285                         default:
286                                 if (f->sort == MSG)
287                                         send_Z = 0;
288                                 ending++;
289                                 return 0;
290                         }
291                 } else if (r == 0) {
292                         if (f->sort == MSG)
293                                 send_Z = 0;
294                         ending++;
295                         return 0;
296                 }
297
298                 dbgdump(DBUF, "in ->", buf, r);
299                 
300                 /* create a new message buffer if required */
301                 if (!f->in)
302                         f->in = cmsg_new(MAXBUFL+1, f->sort, f);
303                 mp = f->in;
304
305                 switch (f->sort) {
306                 case TEXT:
307                         p = buf;
308                         if (f->echo)
309                                 omp = cmsg_new(3*r+1, f->sort, f);
310                         while (r > 0 && p < &buf[r]) {
311
312                                 /* echo processing */
313                                 if (f->echo) {
314                                         switch (*p) {
315                                         case '\b':
316                                         case 0x7f:
317                                                 strcpy(omp->inp, "\b \b");
318                                                 omp->inp += strlen(omp->inp);
319                                                 break;
320                                         default:
321                                                 *omp->inp++ = *p;
322                                         }
323                                 }
324                                 
325                                 /* character processing */
326                                 switch (*p) {
327                                 case '\t':
328                                         if (int_tabs) {
329                                                 memset(mp->inp, ' ', tabsize);
330                                                 mp->inp += tabsize;
331                                                 ++p;
332                                         } else {
333                                                 *mp->inp++ = *p++;
334                                         }
335                                         break;
336                                 case '\b':
337                                 case 0x7f:
338                                         if (mp->inp > mp->data)
339                                                 mp->inp--;
340                                         ++p;
341                                         break;
342                                 default:
343                                         if (nl == '\n' && *p == '\r') {   /* ignore \r in telnet mode (ugh) */
344                                                 p++;
345                                         } else if (*p == nl) {
346                                                 if (mp->inp == mp->data)
347                                                         *mp->inp++ = ' ';
348                                                 *mp->inp = 0;              /* zero terminate it, but don't include it in the length */
349                                                 dbgdump(DMSG, "QUEUE TEXT", mp->data, mp->inp-mp->data);
350                                                 cmsg_send(f->inq, mp, 0);
351                                                 f->in = mp = cmsg_new(MAXBUFL+1, f->sort, f);
352                                                 ++p;
353                                         } else {
354                                                 if (mp->inp < &mp->data[MAXBUFL-8])
355                                                         *mp->inp++ = *p++;
356                                                 else {
357                                                         mp->inp = mp->data;
358                                                 }
359                                         }
360                                 }
361                         }
362                         
363                         /* queue any echo text */
364                         if (f->echo) {
365                                 dbgdump(DMSG, "QUEUE ECHO TEXT", omp->data, omp->inp - omp->data);
366                                 cmsg_send(f->outq, omp, 0);
367                                 f->sp->flags |= SEL_OUTPUT;
368                         }
369                         
370                         break;
371
372                 case MSG:
373                         p = buf;
374                         while (r > 0 && p < &buf[r]) {
375
376                                 /* build up the size into the likely message length (yes I know it's a short) */
377                                 switch (mp->state) {
378                                 case 0:
379                                 case 1:
380                                         mp->state++;
381                                         break;
382                                 case 2:
383                                 case 3:
384                                         mp->size = (mp->size << 8) | (*p++ & 0xff);
385                                         if (mp->size > MAXBUFL)
386                                                 die("Message size too big from node (%d > %d)", mp->size, MAXBUFL);
387                                         mp->state++;
388                                         break;
389                                 default:
390                                         if (mp->inp - mp->data < mp->size) {
391                                                 *mp->inp++ = *p++;
392                                         } 
393                                         if (mp->inp - mp->data >= mp->size) {
394                                                 /* kick it upstairs */
395                                                 dbgdump(DMSG, "QUEUE MSG", mp->data, mp->inp - mp->data);
396                                                 cmsg_send(f->inq, mp, 0);
397                                                 mp = f->in = cmsg_new(MAXBUFL+1, f->sort, f);
398                                         }
399                                 }
400                         }
401                         break;
402                         
403                 default:
404                         die("invalid sort (%d) in input handler", f->sort);
405                 }
406         }
407         
408         /* output modes */
409 lout:;
410         if (out) {
411                 int l, r;
412                 
413                 if (!f->out) {
414                         mp = f->out = cmsg_next(f->outq);
415                         if (!mp) {
416                                 sp->flags &= ~SEL_OUTPUT;
417                                 return 0;
418                         }
419                         mp->inp = mp->data;
420                 }
421                 l = mp->size - (mp->inp - mp->data);
422                 if (l > 0) {
423                         
424                         dbgdump(DBUF, "<-out", mp->inp, l);
425                         
426                         r = write(f->cnum, mp->inp, l);
427                         if (r < 0) {
428                                 switch (errno) {
429                                 case EINTR:
430                                 case EINPROGRESS:
431                                 case EAGAIN:
432                                         goto lend;
433                                 default:
434                                         if (f->sort == MSG)
435                                                 send_Z = 0;
436                                         ending++;
437                                         return;
438                                 }
439                         } else if (r > 0) {
440                                 mp->inp += r;
441                         }
442                 } else if (l < 0) 
443                         die("got negative length in handler on node");
444                 if (mp->inp - mp->data >= mp->size) {
445                         cmsg_callback(mp, 0);
446                         f->out = 0;
447                 }
448         }
449 lend:;
450         return 0;
451 }
452
453 /*
454  * things to do with initialisation
455  */
456
457 void initargs(int argc, char *argv[])
458 {
459         int i, c, err = 0;
460
461         while ((c = getopt(argc, argv, "h:p:x:")) > 0) {
462                 switch (c) {
463                 case 'h':
464                         node_addr = optarg;
465                         break;
466                 case 'l':
467                         paclen = atoi(optarg);
468                         if (paclen < 80)
469                                 paclen = 80;
470                         if (paclen > MAXPACLEN)
471                                 paclen = MAXPACLEN;
472                         break;
473                 case 'p':
474                         node_port = atoi(optarg);
475                         break;
476                 case 'x':
477                         dbginit("client");
478                         dbgset(atoi(optarg));
479                         break;
480                 default:
481                         ++err;
482                         goto lerr;
483                 }
484         }
485
486 lerr:
487         if (err) {
488                 die("usage: client [-x n|-h<host>|-p<port>|-l<paclen>] <call>|login [local|telnet|ax25]");
489         }
490         
491         if (optind < argc) {
492                 call = strupper(argv[optind]);
493                 ++optind;
494         }
495         if (!call)
496                 die("Must have at least a callsign (for now)");
497
498         if (optind < argc) {
499                 connsort = strlower(argv[optind]);
500                 if (eq(connsort, "telnet") || eq(connsort, "local")) {
501                         nl = '\n';
502                         echo = 1;
503                 } else if (eq(connsort, "ax25")) {
504                         nl = '\r';
505                         echo = 0;
506                 } else {
507                         die("2nd argument must be \"telnet\" or \"ax25\" or \"local\"");
508                 }
509         } else {
510                 connsort = "local";
511                 nl = '\n';
512                 echo = 1;
513         }
514
515         /* this is kludgy, but hey so is the rest of this! */
516         if (!eq(connsort, "ax25") && paclen == DEFPACLEN) {
517                 paclen = MAXPACLEN;
518         }
519 }
520
521 void connect_to_node()
522 {
523         struct hostent *hp, *gethostbyname();
524         struct sockaddr_in server;
525         int nodef;
526         sel_t *sp;
527                                 
528         if ((hp = gethostbyname(node_addr)) == 0) 
529                 die("Unknown host tcp host %s for printer", node_addr);
530
531         memset(&server, 0, sizeof server);
532         server.sin_family = AF_INET;
533         memcpy(&server.sin_addr, hp->h_addr, hp->h_length);
534         server.sin_port = htons(node_port);
535                                                 
536         nodef = socket(AF_INET, SOCK_STREAM, 0);
537         if (nodef < 0) 
538                 die("Can't open socket to %s port %d (%d)", node_addr, node_port, errno);
539
540         if (connect(nodef, (struct sockaddr *) &server, sizeof server) < 0) {
541                 die("Error on connect to %s port %d (%d)", node_addr, node_port, errno);
542         }
543         node = fcb_new(nodef, MSG);
544         node->sp = sel_open(nodef, node, "Msg System", fcb_handler, MSG, SEL_INPUT);
545         
546 }
547
548 /*
549  * things to do with going away
550  */
551
552 void term_timeout(int i)
553 {
554         /* none of this is going to be reused so don't bother cleaning up properly */
555         if (in && in->t_set)
556                 tcsetattr(0, TCSANOW, &in->t);
557         if (node) {
558                 close(node->cnum);
559         }
560         exit(i);
561 }
562
563 void terminate(int i)
564 {
565         if (node && send_Z && call) {
566                 send_msg(node, 'Z', "", 0);
567         }
568         
569         signal(SIGALRM, term_timeout);
570         alarm(10);
571         
572         while ((in && !is_chain_empty(in->outq)) ||
573                    (node && !is_chain_empty(node->outq))) {
574                 sel_run();
575         }
576         if (in && in->t_set)
577                 tcsetattr(0, TCSADRAIN, &in->t);
578         if (node) 
579                 close(node->cnum);
580         exit(i);
581 }
582
583 void login_timeout(int i)
584 {
585         write(0, "Timed Out", 10);
586         write(0, &nl, 1);
587         sel_run();                                      /* force a coordination */
588         if (in && in->t_set)
589                 tcsetattr(0, TCSANOW, &in->t);
590         exit(i);
591 }
592
593 /*
594  * things to do with ongoing processing of inputs
595  */
596
597 void process_stdin()
598 {
599         cmsg_t *mp = cmsg_next(in->inq);
600         if (mp) {
601                 dbg(DMSG, "MSG size: %d", mp->size);
602         
603                 if (mp->size > 0 && mp->inp > mp->data) {
604                         send_msg(node, 'I', mp->data, mp->size);
605                 }
606                 cmsg_callback(mp, 0);
607         }
608 }
609
610 void process_node()
611 {
612         cmsg_t *mp = cmsg_next(node->inq);
613         if (mp) {
614                 dbg(DMSG, "MSG size: %d", mp->size);
615         
616                 if (mp->size > 0 && mp->inp > mp->data) {
617                         char *p = strchr(mp->data, '|');
618                         if (p)
619                                 p++;
620                         switch (mp->data[0]) {
621                         case 'Z':
622                                 send_Z = 0;
623                                 ending++;
624                                 return;
625                         case 'E':
626                                 if (isdigit(*p))
627                                         in->echo = *p - '0';
628                                 break;
629                         case 'B':
630                                 if (isdigit(*p))
631                                         in->buffer_it = *p - '0';
632                                 break;
633                         case 'D':
634                                 if (p) {
635                                         int l = mp->inp - (unsigned char *) p;
636                                         send_text(in, p, l);
637                                 }
638                                 break;
639                         default:
640                                 break;
641                         }
642                 }
643                 cmsg_callback(mp, 0);
644         } else {
645                 flush_text(in);
646         }
647 }
648
649 /*
650  * the program itself....
651  */
652
653 main(int argc, char *argv[])
654 {
655         /* set up environment */
656         {
657                 char *p = getenv("DXSPIDER_ROOT");
658                 if (p)
659                         root = p;
660                 p = getenv("DXSPIDER_HOST");
661                 if (p)
662                         node_addr = p;
663                 p = getenv("DXSPIDER_PORT");
664                 if (p)
665                         node_port = atoi(p);
666                 p = getenv("DXSPIDER_PACLEN");
667                 if (p) {
668                         paclen = atoi(p);
669                         if (paclen < 80)
670                                 paclen = 80;
671                         if (paclen > MAXPACLEN)
672                                 paclen = MAXPACLEN;
673                 }
674         }
675         
676         /* get program arguments, initialise stuff */
677         initargs(argc, argv);
678         sel_init(10, 0, 10000);
679
680         /* trap signals */
681         signal(SIGHUP, SIG_IGN);
682         signal(SIGINT, terminate);
683         signal(SIGQUIT, terminate);
684         signal(SIGTERM, terminate);
685 #ifdef SIGPWR
686         signal(SIGPWR, terminate);
687 #endif
688
689         /* compile regexes for iscallsign */
690         {
691                 myregex_t *rp;
692                 for (rp = iscallreg; rp->in; ++rp) {
693                         regex_t reg;
694                         int r = regcomp(&reg, rp->in, REG_EXTENDED|REG_ICASE|REG_NOSUB);
695                         if (r)
696                                 die("regcomp returned %d for '%s'", r, rp->in);
697                         rp->regex = malloc(sizeof(regex_t));
698                         if (!rp->regex)
699                                 die("out of room - compiling regexes");
700                         *rp->regex = reg;
701                 }
702         }
703         
704         /* is this a login? */
705         if (eq(call, "LOGIN")) {
706                 char buf[MAXPACLEN+1];
707                 int r;
708                 int f = xopen("data", "issue", 0);
709                 if (f > 0) {
710                         while ((r = read(f, buf, paclen)) > 0) {
711                                 if (nl != '\n') {
712                                         char *p;
713                                         for (p = buf; p < &buf[r]; ++p) {
714                                                 if (*p == '\n')
715                                                         *p = nl;
716                                         }
717                                 }
718                                 write(0, buf, r);
719                         }
720                         close(f);
721                 }
722                 signal(SIGALRM, login_timeout);
723                 alarm(timeout);
724                 write(0, "login: ", 7);
725                 r = read(0, buf, 20);
726                 if (r <= 0)
727                         die("No login or error (%d)", errno);
728                 signal(SIGALRM, SIG_IGN);
729                 alarm(0);
730                 while (r > 0) {
731                         if (buf[r-1] == ' ' || buf[r-1] == '\r' || buf[r-1] == '\n')
732                                 --r;
733                         else
734                                 break;
735                 }
736                 buf[r] = 0;
737                 call = strupper(buf);
738         }
739
740         /* check the callsign */
741         if (!iscallsign(call)) {
742                 die("Sorry, %s isn't a valid callsign", call);
743         }
744         
745         /* connect up stdin */
746         in = fcb_new(0, TEXT);
747         in->sp = sel_open(0, in, "STDIN", fcb_handler, TEXT, SEL_INPUT);
748         if (tcgetattr(0, &in->t) < 0) {
749                 echo = 0;
750                 in->t_set = 0;
751         } else {
752                 struct termios t = in->t;
753                 t.c_lflag &= ~(ECHO|ECHONL|ICANON);
754                 if (tcsetattr(0, TCSANOW, &t) < 0) 
755                         die("tcsetattr (%d)", errno);
756                 in->echo = echo;
757                 in->t_set = 1;
758         }
759         in->buffer_it = 1;
760
761         /* connect up node */
762         connect_to_node();
763
764         /* tell the cluster who I am */
765         send_msg(node, 'A', connsort, strlen(connsort));
766         
767         /* main processing loop */
768         while (!ending) {
769                 sel_run();
770                 if (!ending) {
771                         process_stdin();
772                         process_node();
773                 }
774         }
775         terminate(0);
776 }
777
778
779
780
781
782