]> git.ozlabs.org Git - ppp.git/blob - chat/chat.c
Makefile.am: Add explicit openssl directory to pppd include path
[ppp.git] / chat / chat.c
1 /*
2  *      Chat -- a program for automatic session establishment (i.e. dial
3  *              the phone and log in).
4  *
5  * Standard termination codes:
6  *  0 - successful completion of the script
7  *  1 - invalid argument, expect string too large, etc.
8  *  2 - error on an I/O operation or fatal error condition.
9  *  3 - timeout waiting for a simple string.
10  *  4 - the first string declared as "ABORT"
11  *  5 - the second string declared as "ABORT"
12  *  6 - ... and so on for successive ABORT strings.
13  *
14  *      This software is in the public domain.
15  *
16  * -----------------
17  *      22-May-99 added environment substitutuion, enabled with -E switch.
18  *      Andreas Arens <andras@cityweb.de>.
19  *
20  *      12-May-99 added a feature to read data to be sent from a file,
21  *      if the send string starts with @.  Idea from gpk <gpk@onramp.net>.
22  *
23  *      added -T and -U option and \T and \U substitution to pass a phone
24  *      number into chat script. Two are needed for some ISDN TA applications.
25  *      Keith Dart <kdart@cisco.com>
26  *      
27  *
28  *      Added SAY keyword to send output to stderr.
29  *      This allows to turn ECHO OFF and to output specific, user selected,
30  *      text to give progress messages. This best works when stderr
31  *      exists (i.e.: pppd in nodetach mode).
32  *
33  *      Added HANGUP directives to allow for us to be called
34  *      back. When HANGUP is set to NO, chat will not hangup at HUP signal.
35  *      We rely on timeouts in that case.
36  *
37  *      Added CLR_ABORT to clear previously set ABORT string. This has been
38  *      dictated by the HANGUP above as "NO CARRIER" (for example) must be
39  *      an ABORT condition until we know the other host is going to close
40  *      the connection for call back. As soon as we have completed the
41  *      first stage of the call back sequence, "NO CARRIER" is a valid, non
42  *      fatal string. As soon as we got called back (probably get "CONNECT"),
43  *      we should re-arm the ABORT "NO CARRIER". Hence the CLR_ABORT command.
44  *      Note that CLR_ABORT packs the abort_strings[] array so that we do not
45  *      have unused entries not being reclaimed.
46  *
47  *      In the same vein as above, added CLR_REPORT keyword.
48  *
49  *      Allow for comments. Line starting with '#' are comments and are
50  *      ignored. If a '#' is to be expected as the first character, the 
51  *      expect string must be quoted.
52  *
53  *
54  *              Francis Demierre <Francis@SwissMail.Com>
55  *              Thu May 15 17:15:40 MET DST 1997
56  *
57  *
58  *      Added -r "report file" switch & REPORT keyword.
59  *              Robert Geer <bgeer@xmission.com>
60  *
61  *      Added -s "use stderr" and -S "don't use syslog" switches.
62  *              June 18, 1997
63  *              Karl O. Pinc <kop@meme.com>
64  *
65  *
66  *      Added -e "echo" switch & ECHO keyword
67  *              Dick Streefland <dicks@tasking.nl>
68  *
69  *
70  *      Considerable updates and modifications by
71  *              Al Longyear <longyear@pobox.com>
72  *              Paul Mackerras <paulus@cs.anu.edu.au>
73  *
74  *
75  *      The original author is:
76  *
77  *              Karl Fox <karl@MorningStar.Com>
78  *              Morning Star Technologies, Inc.
79  *              1760 Zollinger Road
80  *              Columbus, OH  43221
81  *              (614)451-1883
82  *
83  */
84
85 #include <stdio.h>
86 #include <ctype.h>
87 #include <time.h>
88 #include <fcntl.h>
89 #include <signal.h>
90 #include <errno.h>
91 #include <string.h>
92 #include <stdlib.h>
93 #include <unistd.h>
94 #include <sys/types.h>
95 #include <sys/stat.h>
96 #include <syslog.h>
97 #include <stdarg.h>
98
99 #ifndef TERMIO
100 #undef  TERMIOS
101 #define TERMIOS
102 #endif
103
104 #ifdef TERMIO
105 #include <termio.h>
106 #endif
107 #ifdef TERMIOS
108 #include <termios.h>
109 #endif
110
111 #define STR_LEN 1024
112
113 #ifndef SIGTYPE
114 #define SIGTYPE void
115 #endif
116
117 #ifndef O_NONBLOCK
118 #define O_NONBLOCK      O_NDELAY
119 #endif
120
121 #ifdef SUNOS
122 extern int sys_nerr;
123 extern char *sys_errlist[];
124 #define memmove(to, from, n)    bcopy(from, to, n)
125 #define strerror(n)             ((unsigned)(n) < sys_nerr? sys_errlist[(n)] :\
126                                  "unknown error")
127 #endif
128
129 /*************** Micro getopt() *********************************************/
130 #define OPTION(c,v)     (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
131                                 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
132                                 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
133 #define OPTARG(c,v)     (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
134                                 (_O=4,(char*)0):(char*)0)
135 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
136 #define ARG(c,v)        (c?(--c,*v++):(char*)0)
137
138 static int _O = 0;              /* Internal state */
139 /*************** Micro getopt() *********************************************/
140
141 char *program_name;
142
143 #define MAX_ABORTS              50
144 #define MAX_REPORTS             50
145 #define DEFAULT_CHAT_TIMEOUT    45
146
147 int echo          = 0;
148 int verbose       = 0;
149 int to_log        = 1;
150 int to_stderr     = 0;
151 int Verbose       = 0;
152 int quiet         = 0;
153 int report        = 0;
154 int use_env       = 0;
155 int exit_code     = 0;
156 FILE* report_fp   = (FILE *) 0;
157 char *report_file = (char *) 0;
158 char *chat_file   = (char *) 0;
159 char *phone_num   = (char *) 0;
160 char *phone_num2  = (char *) 0;
161 int timeout       = DEFAULT_CHAT_TIMEOUT;
162
163 int have_tty_parameters = 0;
164
165 #ifdef TERMIO
166 #define term_parms struct termio
167 #define get_term_param(param) ioctl(0, TCGETA, param)
168 #define set_term_param(param) ioctl(0, TCSETA, param)
169 struct termio saved_tty_parameters;
170 #endif
171
172 #ifdef TERMIOS
173 #define term_parms struct termios
174 #define get_term_param(param) tcgetattr(0, param)
175 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
176 struct termios saved_tty_parameters;
177 #endif
178
179 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
180         fail_buffer[50];
181 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
182 int clear_abort_next = 0;
183
184 char *report_string[MAX_REPORTS] ;
185 char  report_buffer[256] ;
186 int n_reports = 0, report_next = 0, report_gathering = 0 ; 
187 int clear_report_next = 0;
188
189 int say_next = 0, hup_next = 0;
190
191 void *dup_mem (void *b, size_t c);
192 void *copy_of (char *s);
193 char *grow (char *s, char **p, size_t len);
194 void usage (void);
195 void msgf (const char *fmt, ...);
196 void fatal (int code, const char *fmt, ...);
197 SIGTYPE sigalrm (int signo);
198 SIGTYPE sigint (int signo);
199 SIGTYPE sigterm (int signo);
200 SIGTYPE sighup (int signo);
201 void unalarm (void);
202 void init (void);
203 void set_tty_parameters (void);
204 int  echo_stderr (int);
205 void break_sequence (void);
206 void terminate (int status);
207 void do_file (char *chat_file);
208 int  get_string (register char *string);
209 int  put_string (register char *s);
210 int  write_char (int c);
211 int  put_char (int c);
212 int  get_char (void);
213 int  chat_send (register char *s);
214 char *character (int c);
215 void chat_expect (register char *s);
216 char *clean (register char *s, int sending);
217 void break_sequence (void);
218 void terminate (int status);
219 void pack_array (char **array, int end);
220 char *expect_strtok (char *, char *);
221 int vfmtmsg (char *, int, const char *, va_list);       /* vsprintf++ */
222
223 int main (int, char *[]);
224
225 void *dup_mem(void *b, size_t c)
226 {
227     void *ans = malloc (c);
228     if (!ans)
229         fatal(2, "memory error!");
230
231     memcpy (ans, b, c);
232     return ans;
233 }
234
235 void *copy_of (char *s)
236 {
237     return dup_mem (s, strlen (s) + 1);
238 }
239
240 /* grow a char buffer and keep a pointer offset */
241 char *grow(char *s, char **p, size_t len)
242 {
243     size_t l = *p - s;          /* save p as distance into s */
244
245     s = realloc(s, len);
246     if (!s)
247         fatal(2, "memory error!");
248     *p = s + l;                 /* restore p */
249     return s;
250 }
251
252 /*
253  * chat [ -v ] [ -E ] [ -T number ] [ -U number ] [ -t timeout ] [ -f chat-file ] \
254  * [ -r report-file ] \
255  *              [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
256  *
257  *      Perform a UUCP-dialer-like chat script on stdin and stdout.
258  */
259 int
260 main(int argc, char **argv)
261 {
262     int option;
263     char *arg;
264
265     program_name = *argv;
266     tzset();
267
268     while ((option = OPTION(argc, argv)) != 0) {
269         switch (option) {
270         case 'e':
271             ++echo;
272             break;
273
274         case 'E':
275             ++use_env;
276             break;
277
278         case 'v':
279             ++verbose;
280             break;
281
282         case 'V':
283             ++Verbose;
284             break;
285
286         case 's':
287             ++to_stderr;
288             break;
289
290         case 'S':
291             to_log = 0;
292             break;
293
294         case 'f':
295             if ((arg = OPTARG(argc, argv)) != NULL)
296                     chat_file = copy_of(arg);
297             else
298                 usage();
299             break;
300
301         case 't':
302             if ((arg = OPTARG(argc, argv)) != NULL)
303                 timeout = atoi(arg);
304             else
305                 usage();
306             break;
307
308         case 'r':
309             arg = OPTARG (argc, argv);
310             if (arg) {
311                 if (report_fp != NULL)
312                     fclose (report_fp);
313                 report_file = copy_of (arg);
314                 report_fp   = fopen (report_file, "a");
315                 if (report_fp != NULL) {
316                     if (verbose)
317                         fprintf (report_fp, "Opening \"%s\"...\n",
318                                  report_file);
319                     report = 1;
320                 }
321             }
322             break;
323
324         case 'T':
325             if ((arg = OPTARG(argc, argv)) != NULL)
326                 phone_num = copy_of(arg);
327             else
328                 usage();
329             break;
330
331         case 'U':
332             if ((arg = OPTARG(argc, argv)) != NULL)
333                 phone_num2 = copy_of(arg);
334             else
335                 usage();
336             break;
337
338         default:
339             usage();
340             break;
341         }
342     }
343 /*
344  * Default the report file to the stderr location
345  */
346     if (report_fp == NULL)
347         report_fp = stderr;
348
349     if (to_log) {
350 #ifdef ultrix
351         openlog("chat", LOG_PID);
352 #else
353         openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
354
355         if (verbose)
356             setlogmask(LOG_UPTO(LOG_INFO));
357         else
358             setlogmask(LOG_UPTO(LOG_WARNING));
359 #endif
360     }
361
362     init();
363     
364     if (chat_file != NULL) {
365         arg = ARG(argc, argv);
366         if (arg != NULL)
367             usage();
368         else
369             do_file (chat_file);
370     } else {
371         while ((arg = ARG(argc, argv)) != NULL) {
372             chat_expect(arg);
373
374             if ((arg = ARG(argc, argv)) != NULL)
375                 chat_send(arg);
376         }
377     }
378
379     terminate(0);
380     return 0;
381 }
382
383 /*
384  *  Process a chat script when read from a file.
385  */
386
387 void do_file (char *chat_file)
388 {
389     int linect, sendflg;
390     char *sp, *arg, quote;
391     char buf [STR_LEN];
392     FILE *cfp;
393
394     cfp = fopen (chat_file, "r");
395     if (cfp == NULL)
396         fatal(1, "%s -- open failed: %m", chat_file);
397
398     linect = 0;
399     sendflg = 0;
400
401     while (fgets(buf, STR_LEN, cfp) != NULL) {
402         sp = strchr (buf, '\n');
403         if (sp)
404             *sp = '\0';
405
406         linect++;
407         sp = buf;
408
409         /* lines starting with '#' are comments. If a real '#'
410            is to be expected, it should be quoted .... */
411         if ( *sp == '#' )
412             continue;
413
414         while (*sp != '\0') {
415             if (*sp == ' ' || *sp == '\t') {
416                 ++sp;
417                 continue;
418             }
419
420             if (*sp == '"' || *sp == '\'') {
421                 quote = *sp++;
422                 arg = sp;
423                 while (*sp != quote) {
424                     if (*sp == '\0')
425                         fatal(1, "unterminated quote (line %d)", linect);
426
427                     if (*sp++ == '\\') {
428                         if (*sp != '\0')
429                             ++sp;
430                     }
431                 }
432             }
433             else {
434                 arg = sp;
435                 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
436                     ++sp;
437             }
438
439             if (*sp != '\0')
440                 *sp++ = '\0';
441
442             if (sendflg)
443                 chat_send (arg);
444             else
445                 chat_expect (arg);
446             sendflg = !sendflg;
447         }
448     }
449     fclose (cfp);
450 }
451
452 /*
453  *      We got an error parsing the command line.
454  */
455 void usage(void)
456 {
457     fprintf(stderr, "\
458 Usage: %s [-e] [-E] [-v] [-V] [-t timeout] [-r report-file]\n\
459      [-T phone-number] [-U phone-number2] {-f chat-file | chat-script}\n", program_name);
460     exit(1);
461 }
462
463 char line[1024];
464
465 /*
466  * Send a message to syslog and/or stderr.
467  */
468 void msgf(const char *fmt, ...)
469 {
470     va_list args;
471
472     va_start(args, fmt);
473
474     vfmtmsg(line, sizeof(line), fmt, args);
475     if (to_log)
476         syslog(LOG_INFO, "%s", line);
477     if (to_stderr)
478         fprintf(stderr, "%s\n", line);
479     va_end(args);
480 }
481
482 /*
483  *      Print an error message and terminate.
484  */
485
486 void fatal(int code, const char *fmt, ...)
487 {
488     va_list args;
489
490     va_start(args, fmt);
491
492     vfmtmsg(line, sizeof(line), fmt, args);
493     if (to_log)
494         syslog(LOG_ERR, "%s", line);
495     if (to_stderr)
496         fprintf(stderr, "%s\n", line);
497     va_end(args);
498     terminate(code);
499 }
500
501 int alarmed = 0;
502
503 SIGTYPE sigalrm(int signo)
504 {
505     int flags;
506
507     alarm(1);
508     alarmed = 1;                /* Reset alarm to avoid race window */
509     signal(SIGALRM, sigalrm);   /* that can cause hanging in read() */
510
511     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
512         fatal(2, "Can't get file mode flags on stdin: %m");
513
514     if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
515         fatal(2, "Can't set file mode flags on stdin: %m");
516
517     if (verbose)
518         msgf("alarm");
519 }
520
521 void unalarm(void)
522 {
523     int flags;
524
525     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
526         fatal(2, "Can't get file mode flags on stdin: %m");
527
528     if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
529         fatal(2, "Can't set file mode flags on stdin: %m");
530 }
531
532 SIGTYPE sigint(int signo)
533 {
534     fatal(2, "SIGINT");
535 }
536
537 SIGTYPE sigterm(int signo)
538 {
539     fatal(2, "SIGTERM");
540 }
541
542 SIGTYPE sighup(int signo)
543 {
544     fatal(2, "SIGHUP");
545 }
546
547 void init(void)
548 {
549     signal(SIGINT, sigint);
550     signal(SIGTERM, sigterm);
551     signal(SIGHUP, sighup);
552
553     set_tty_parameters();
554     signal(SIGALRM, sigalrm);
555     alarm(0);
556     alarmed = 0;
557 }
558
559 void set_tty_parameters(void)
560 {
561 #if defined(get_term_param)
562     term_parms t;
563
564     if (get_term_param (&t) < 0)
565         fatal(2, "Can't get terminal parameters: %m");
566
567     saved_tty_parameters = t;
568     have_tty_parameters  = 1;
569
570     t.c_iflag     |= IGNBRK | ISTRIP | IGNPAR;
571     t.c_oflag      = 0;
572     t.c_lflag      = 0;
573     t.c_cc[VERASE] =
574     t.c_cc[VKILL]  = 0;
575     t.c_cc[VMIN]   = 1;
576     t.c_cc[VTIME]  = 0;
577
578     if (set_term_param (&t) < 0)
579         fatal(2, "Can't set terminal parameters: %m");
580 #endif
581 }
582
583 void break_sequence(void)
584 {
585 #ifdef TERMIOS
586     tcsendbreak (0, 0);
587 #endif
588 }
589
590 void terminate(int status)
591 {
592     static int terminating = 0;
593
594     if (terminating)
595         exit(status);
596     terminating = 1;
597     echo_stderr(-1);
598 /*
599  * Allow the last of the report string to be gathered before we terminate.
600  */
601     if (report_gathering) {
602         int c, rep_len;
603
604         rep_len = strlen(report_buffer);
605         while (rep_len + 1 <= sizeof(report_buffer)) {
606             alarm(1);
607             c = get_char();
608             alarm(0);
609             if (c < 0 || iscntrl(c))
610                 break;
611             report_buffer[rep_len] = c;
612             ++rep_len;
613         }
614         report_buffer[rep_len] = 0;
615         fprintf (report_fp, "chat:  %s\n", report_buffer);
616     }
617     if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
618         if (verbose)
619             fprintf (report_fp, "Closing \"%s\".\n", report_file);
620         fclose (report_fp);
621         report_fp = (FILE *) NULL;
622     }
623
624 #if defined(get_term_param)
625     if (have_tty_parameters) {
626         if (set_term_param (&saved_tty_parameters) < 0)
627             fatal(2, "Can't restore terminal parameters: %m");
628     }
629 #endif
630
631     exit(status);
632 }
633
634 /*
635  *      'Clean up' this string.
636  */
637 char *clean(register char *s,
638             int sending)  /* set to 1 when sending (putting) this string. */
639 {
640     char cur_chr;
641     char *s1, *p, *phchar;
642     int add_return = sending;
643     size_t len = strlen(s) + 3;         /* see len comments below */
644
645 #define isoctal(chr)    (((chr) >= '0') && ((chr) <= '7'))
646 #define isalnumx(chr)   ((((chr) >= '0') && ((chr) <= '9')) \
647                          || (((chr) >= 'a') && ((chr) <= 'z')) \
648                          || (((chr) >= 'A') && ((chr) <= 'Z')) \
649                          || (chr) == '_')
650
651     p = s1 = malloc(len);
652     if (!p)
653         fatal(2, "memory error!");
654     while (*s) {
655         cur_chr = *s++;
656         if (cur_chr == '^') {
657             cur_chr = *s++;
658             if (cur_chr == '\0') {
659                 *p++ = '^';
660                 break;
661             }
662             cur_chr &= 0x1F;
663             if (cur_chr != 0) {
664                 *p++ = cur_chr;
665             }
666             continue;
667         }
668
669         if (use_env && cur_chr == '$') {                /* ARI */
670             char c;
671
672             phchar = s;
673             while (isalnumx(*s))
674                 s++;
675             c = *s;             /* save */
676             *s = '\0';
677             phchar = getenv(phchar);
678             *s = c;             /* restore */
679             if (phchar) {
680                 len += strlen(phchar);
681                 s1 = grow(s1, &p, len);
682                 while (*phchar)
683                     *p++ = *phchar++;
684             }
685             continue;
686         }
687
688         if (cur_chr != '\\') {
689             *p++ = cur_chr;
690             continue;
691         }
692
693         cur_chr = *s++;
694         if (cur_chr == '\0') {
695             if (sending) {
696                 *p++ = '\\';
697                 *p++ = '\\';    /* +1 for len */
698             }
699             break;
700         }
701
702         switch (cur_chr) {
703         case 'b':
704             *p++ = '\b';
705             break;
706
707         case 'c':
708             if (sending && *s == '\0')
709                 add_return = 0;
710             else
711                 *p++ = cur_chr;
712             break;
713
714         case '\\':
715         case 'K':
716         case 'p':
717         case 'd':
718             if (sending)
719                 *p++ = '\\';
720             *p++ = cur_chr;
721             break;
722
723         case 'T':
724             if (sending && phone_num) {
725                 len += strlen(phone_num);
726                 s1 = grow(s1, &p, len);
727                 for (phchar = phone_num; *phchar != '\0'; phchar++) 
728                     *p++ = *phchar;
729             }
730             else {
731                 *p++ = '\\';
732                 *p++ = 'T';
733             }
734             break;
735
736         case 'U':
737             if (sending && phone_num2) {
738                 len += strlen(phone_num2);
739                 s1 = grow(s1, &p, len);
740                 for (phchar = phone_num2; *phchar != '\0'; phchar++) 
741                     *p++ = *phchar;
742             }
743             else {
744                 *p++ = '\\';
745                 *p++ = 'U';
746             }
747             break;
748
749         case 'q':
750             quiet = 1;
751             break;
752
753         case 'r':
754             *p++ = '\r';
755             break;
756
757         case 'n':
758             *p++ = '\n';
759             break;
760
761         case 's':
762             *p++ = ' ';
763             break;
764
765         case 't':
766             *p++ = '\t';
767             break;
768
769         case 'N':
770             if (sending) {
771                 *p++ = '\\';
772                 *p++ = '\0';
773             }
774             else
775                 *p++ = 'N';
776             break;
777
778         case '$':                       /* ARI */
779             if (use_env) {
780                 *p++ = cur_chr;
781                 break;
782             }
783             /* FALL THROUGH */
784
785         default:
786             if (isoctal (cur_chr)) {
787                 cur_chr &= 0x07;
788                 if (isoctal (*s)) {
789                     cur_chr <<= 3;
790                     cur_chr |= *s++ - '0';
791                     if (isoctal (*s)) {
792                         cur_chr <<= 3;
793                         cur_chr |= *s++ - '0';
794                     }
795                 }
796
797                 if (cur_chr != 0 || sending) {
798                     if (sending && (cur_chr == '\\' || cur_chr == 0))
799                         *p++ = '\\';
800                     *p++ = cur_chr;
801                 }
802                 break;
803             }
804
805             if (sending)
806                 *p++ = '\\';
807             *p++ = cur_chr;
808             break;
809         }
810     }
811
812     if (add_return)
813         *p++ = '\r';    /* +2 for len */
814
815     *p = '\0';          /* +3 for len */
816     return s1;
817 }
818
819 /*
820  * A modified version of 'strtok'. This version skips \ sequences.
821  */
822
823 char *expect_strtok (char *s, char *term)
824 {
825     static  char *str   = "";
826     int     escape_flag = 0;
827     char   *result;
828
829 /*
830  * If a string was specified then do initial processing.
831  */
832     if (s)
833         str = s;
834
835 /*
836  * If this is the escape flag then reset it and ignore the character.
837  */
838     if (*str)
839         result = str;
840     else
841         result = (char *) 0;
842
843     while (*str) {
844         if (escape_flag) {
845             escape_flag = 0;
846             ++str;
847             continue;
848         }
849
850         if (*str == '\\') {
851             ++str;
852             escape_flag = 1;
853             continue;
854         }
855
856 /*
857  * If this is not in the termination string, continue.
858  */
859         if (strchr (term, *str) == (char *) 0) {
860             ++str;
861             continue;
862         }
863
864 /*
865  * This is the terminator. Mark the end of the string and stop.
866  */
867         *str++ = '\0';
868         break;
869     }
870     return (result);
871 }
872
873 /*
874  * Process the expect string
875  */
876
877 void chat_expect (char *s)
878 {
879     char *expect;
880     char *reply;
881
882     if (strcmp(s, "HANGUP") == 0) {
883         ++hup_next;
884         return;
885     }
886  
887     if (strcmp(s, "ABORT") == 0) {
888         ++abort_next;
889         return;
890     }
891
892     if (strcmp(s, "CLR_ABORT") == 0) {
893         ++clear_abort_next;
894         return;
895     }
896
897     if (strcmp(s, "REPORT") == 0) {
898         ++report_next;
899         return;
900     }
901
902     if (strcmp(s, "CLR_REPORT") == 0) {
903         ++clear_report_next;
904         return;
905     }
906
907     if (strcmp(s, "TIMEOUT") == 0) {
908         ++timeout_next;
909         return;
910     }
911
912     if (strcmp(s, "ECHO") == 0) {
913         ++echo_next;
914         return;
915     }
916
917     if (strcmp(s, "SAY") == 0) {
918         ++say_next;
919         return;
920     }
921
922 /*
923  * Fetch the expect and reply string.
924  */
925     for (;;) {
926         expect = expect_strtok (s, "-");
927         s      = (char *) 0;
928
929         if (expect == (char *) 0)
930             return;
931
932         reply = expect_strtok (s, "-");
933
934 /*
935  * Handle the expect string. If successful then exit.
936  */
937         if (get_string (expect))
938             return;
939
940 /*
941  * If there is a sub-reply string then send it. Otherwise any condition
942  * is terminal.
943  */
944         if (reply == (char *) 0 || exit_code != 3)
945             break;
946
947         chat_send (reply);
948     }
949
950 /*
951  * The expectation did not occur. This is terminal.
952  */
953     if (fail_reason)
954         msgf("Failed (%s)", fail_reason);
955     else
956         msgf("Failed");
957     terminate(exit_code);
958 }
959
960 /*
961  * Translate the input character to the appropriate string for printing
962  * the data.
963  */
964
965 char *character(int c)
966 {
967     static char string[10];
968     char *meta;
969
970     meta = (c & 0x80) ? "M-" : "";
971     c &= 0x7F;
972
973     if (c < 32)
974         sprintf(string, "%s^%c", meta, (int)c + '@');
975     else if (c == 127)
976         sprintf(string, "%s^?", meta);
977     else
978         sprintf(string, "%s%c", meta, c);
979
980     return (string);
981 }
982
983 /*
984  *  process the reply string
985  */
986 int chat_send (register char *s)
987 {
988     char file_data[STR_LEN];
989     int len, ret = 0;
990
991     if (say_next) {
992         say_next = 0;
993         s = clean(s, 1);
994         len = strlen(s);
995         ret = write(2, s, len) != len;
996         free(s);
997         return ret;
998     }
999
1000     if (hup_next) {
1001         hup_next = 0;
1002         if (strcmp(s, "OFF") == 0)
1003            signal(SIGHUP, SIG_IGN);
1004         else
1005            signal(SIGHUP, sighup);
1006         return 0;
1007     }
1008
1009     if (echo_next) {
1010         echo_next = 0;
1011         echo = (strcmp(s, "ON") == 0);
1012         return 0;
1013     }
1014
1015     if (abort_next) {
1016         char *s1;
1017         
1018         abort_next = 0;
1019         
1020         if (n_aborts >= MAX_ABORTS)
1021             fatal(2, "Too many ABORT strings");
1022         
1023         s1 = clean(s, 0);
1024         
1025         if (strlen(s1) + 1 > sizeof(fail_buffer))
1026             fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1027
1028         abort_string[n_aborts++] = s1;
1029
1030         if (verbose)
1031             msgf("abort on (%v)", s1);
1032         return 0;
1033     }
1034
1035     if (clear_abort_next) {
1036         char *s1;
1037         int   i;
1038         int   old_max;
1039         int   pack = 0;
1040         
1041         clear_abort_next = 0;
1042         
1043         s1 = clean(s, 0);
1044         
1045         if (strlen(s1) + 1 > sizeof(fail_buffer))
1046             fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1047
1048         old_max = n_aborts;
1049         for (i=0; i < n_aborts; i++) {
1050             if ( strcmp(s1,abort_string[i]) == 0 ) {
1051                 free(abort_string[i]);
1052                 abort_string[i] = NULL;
1053                 pack++;
1054                 n_aborts--;
1055                 if (verbose)
1056                     msgf("clear abort on (%v)", s1);
1057             }
1058         }
1059         free(s1);
1060         if (pack)
1061             pack_array(abort_string,old_max);
1062         return 0;
1063     }
1064
1065     if (report_next) {
1066         char *s1;
1067         
1068         report_next = 0;
1069         if (n_reports >= MAX_REPORTS)
1070             fatal(2, "Too many REPORT strings");
1071         
1072         s1 = clean(s, 0);
1073         if (strlen(s1) + 1 > sizeof(fail_buffer))
1074             fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1075         
1076         report_string[n_reports++] = s1;
1077         
1078         if (verbose)
1079             msgf("report (%v)", s1);
1080         return 0;
1081     }
1082
1083     if (clear_report_next) {
1084         char *s1;
1085         int   i;
1086         int   old_max;
1087         int   pack = 0;
1088         
1089         clear_report_next = 0;
1090         
1091         s1 = clean(s, 0);
1092         
1093         if (strlen(s1) + 1 > sizeof(fail_buffer))
1094             fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1095
1096         old_max = n_reports;
1097         for (i=0; i < n_reports; i++) {
1098             if ( strcmp(s1,report_string[i]) == 0 ) {
1099                 free(report_string[i]);
1100                 report_string[i] = NULL;
1101                 pack++;
1102                 n_reports--;
1103                 if (verbose)
1104                     msgf("clear report (%v)", s1);
1105             }
1106         }
1107         free(s1);
1108         if (pack)
1109             pack_array(report_string,old_max);
1110         
1111         return 0;
1112     }
1113
1114     if (timeout_next) {
1115         timeout_next = 0;
1116         s = clean(s, 0);
1117         timeout = atoi(s);
1118         
1119         if (timeout <= 0)
1120             timeout = DEFAULT_CHAT_TIMEOUT;
1121
1122         if (verbose)
1123             msgf("timeout set to %d seconds", timeout);
1124
1125         return 0;
1126     }
1127
1128     /*
1129      * The syntax @filename means read the string to send from the
1130      * file `filename'.
1131      */
1132     if (s[0] == '@') {
1133         /* skip the @ and any following white-space */
1134         char *fn = s;
1135         while (*++fn == ' ' || *fn == '\t')
1136             ;
1137
1138         if (*fn != 0) {
1139             FILE *f;
1140             int n = 0;
1141
1142             /* open the file and read until STR_LEN-1 bytes or end-of-file */
1143             f = fopen(fn, "r");
1144             if (f == NULL)
1145                 fatal(1, "%s -- open failed: %m", fn);
1146             while (n < STR_LEN - 1) {
1147                 int nr = fread(&file_data[n], 1, STR_LEN - 1 - n, f);
1148                 if (nr < 0)
1149                     fatal(1, "%s -- read error", fn);
1150                 if (nr == 0)
1151                     break;
1152                 n += nr;
1153             }
1154             fclose(f);
1155
1156             /* use the string we got as the string to send,
1157                but trim off the final newline if any. */
1158             if (n > 0 && file_data[n-1] == '\n')
1159                 --n;
1160             file_data[n] = 0;
1161             s = file_data;
1162         }
1163     }
1164
1165     if (strcmp(s, "EOT") == 0)
1166         s = "^D\\c";
1167     else if (strcmp(s, "BREAK") == 0)
1168         s = "\\K\\c";
1169
1170     if (!put_string(s))
1171         fatal(1, "Failed");
1172
1173     return 0;
1174 }
1175
1176 int get_char(void)
1177 {
1178     int status;
1179     char c;
1180
1181     status = read(0, &c, 1);
1182
1183     switch (status) {
1184     case 1:
1185         return ((int)c & 0x7F);
1186
1187     default:
1188         msgf("warning: read() on stdin returned %d", status);
1189
1190     case -1:
1191         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1192             fatal(2, "Can't get file mode flags on stdin: %m");
1193
1194         if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1195             fatal(2, "Can't set file mode flags on stdin: %m");
1196         
1197         return (-1);
1198     }
1199 }
1200
1201 int put_char(int c)
1202 {
1203     int status;
1204     char ch = c;
1205
1206     usleep(10000);              /* inter-character typing delay (?) */
1207
1208     status = write(1, &ch, 1);
1209
1210     switch (status) {
1211     case 1:
1212         return (0);
1213         
1214     default:
1215         msgf("warning: write() on stdout returned %d", status);
1216         
1217     case -1:
1218         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1219             fatal(2, "Can't get file mode flags on stdin, %m");
1220
1221         if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1222             fatal(2, "Can't set file mode flags on stdin: %m");
1223         
1224         return (-1);
1225     }
1226 }
1227
1228 int write_char(int c)
1229 {
1230     if (alarmed || put_char(c) < 0) {
1231         alarm(0);
1232         alarmed = 0;
1233
1234         if (verbose) {
1235             if (errno == EINTR || errno == EWOULDBLOCK)
1236                 msgf(" -- write timed out");
1237             else
1238                 msgf(" -- write failed: %m");
1239         }
1240         return (0);
1241     }
1242     return (1);
1243 }
1244
1245 int put_string(register char *s)
1246 {
1247     quiet = 0;
1248     s = clean(s, 1);
1249
1250     if (verbose) {
1251         if (quiet)
1252             msgf("send (?????\?)");
1253         else
1254             msgf("send (%v)", s);
1255     }
1256
1257     alarm(timeout); alarmed = 0;
1258
1259     while (*s) {
1260         register char c = *s++;
1261
1262         if (c != '\\') {
1263             if (!write_char (c))
1264                 return 0;
1265             continue;
1266         }
1267
1268         c = *s++;
1269         switch (c) {
1270         case 'd':
1271             sleep(1);
1272             break;
1273
1274         case 'K':
1275             break_sequence();
1276             break;
1277
1278         case 'p':
1279             usleep(10000);      /* 1/100th of a second (arg is microseconds) */
1280             break;
1281
1282         default:
1283             if (!write_char (c))
1284                 return 0;
1285             break;
1286         }
1287     }
1288
1289     alarm(0);
1290     alarmed = 0;
1291     return (1);
1292 }
1293
1294 /*
1295  *      Echo a character to stderr.
1296  *      When called with -1, a '\n' character is generated when
1297  *      the cursor is not at the beginning of a line.
1298  */
1299 int echo_stderr(int n)
1300 {
1301     static int need_lf;
1302     char *s;
1303     int len, ret = 0;
1304
1305     switch (n) {
1306     case '\r':          /* ignore '\r' */
1307         break;
1308     case -1:
1309         if (need_lf == 0)
1310             break;
1311         /* fall through */
1312     case '\n':
1313         ret = write(2, "\n", 1) != 1;
1314         need_lf = 0;
1315         break;
1316     default:
1317         s = character(n);
1318         len = strlen(s);
1319         ret = write(2, s, len) != len;
1320         need_lf = 1;
1321         break;
1322     }
1323     return ret;
1324 }
1325
1326 /*
1327  *      'Wait for' this string to appear on this file descriptor.
1328  */
1329 int get_string(register char *string)
1330 {
1331     char temp[STR_LEN];
1332     int c, printed = 0, len, minlen;
1333     register char *s = temp, *end = s + STR_LEN;
1334     char *logged = temp;
1335
1336     fail_reason = (char *)0;
1337     string = clean(string, 0);
1338     len = strlen(string);
1339     minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1340
1341     if (verbose)
1342         msgf("expect (%v)", string);
1343
1344     if (len > STR_LEN) {
1345         msgf("expect string is too long");
1346         exit_code = 1;
1347         return 0;
1348     }
1349
1350     if (len == 0) {
1351         if (verbose)
1352             msgf("got it");
1353         return (1);
1354     }
1355
1356     alarm(timeout);
1357     alarmed = 0;
1358
1359     while ( ! alarmed && (c = get_char()) >= 0) {
1360         int n, abort_len, report_len;
1361
1362         if (echo) {
1363             if (echo_stderr(c) != 0) {
1364                 fatal(2, "Could not write to stderr, %m");
1365             }
1366         }
1367         if (verbose && c == '\n') {
1368             if (s == logged)
1369                 msgf("");       /* blank line */
1370             else
1371                 msgf("%0.*v", s - logged, logged);
1372             logged = s + 1;
1373         }
1374
1375         *s++ = c;
1376
1377         if (verbose && s >= logged + 80) {
1378             msgf("%0.*v", s - logged, logged);
1379             logged = s;
1380         }
1381
1382         if (Verbose) {
1383            if (c == '\n')
1384                fputc( '\n', stderr );
1385            else if (c != '\r')
1386                fprintf( stderr, "%s", character(c) );
1387         }
1388
1389         if (!report_gathering) {
1390             for (n = 0; n < n_reports; ++n) {
1391                 if ((report_string[n] != (char*) NULL) &&
1392                     s - temp >= (report_len = strlen(report_string[n])) &&
1393                     strncmp(s - report_len, report_string[n], report_len) == 0) {
1394                     time_t time_now   = time ((time_t*) NULL);
1395                     struct tm* tm_now = localtime (&time_now);
1396
1397                     strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1398                     strcat (report_buffer, report_string[n]);
1399
1400                     report_string[n] = (char *) NULL;
1401                     report_gathering = 1;
1402                     break;
1403                 }
1404             }
1405         }
1406         else {
1407             if (!iscntrl (c)) {
1408                 int rep_len = strlen (report_buffer);
1409                 report_buffer[rep_len]     = c;
1410                 report_buffer[rep_len + 1] = '\0';
1411             }
1412             else {
1413                 report_gathering = 0;
1414                 fprintf (report_fp, "chat:  %s\n", report_buffer);
1415             }
1416         }
1417
1418         if (s - temp >= len &&
1419             c == string[len - 1] &&
1420             strncmp(s - len, string, len) == 0) {
1421             if (verbose) {
1422                 if (s > logged)
1423                     msgf("%0.*v", s - logged, logged);
1424                 msgf(" -- got it\n");
1425             }
1426
1427             alarm(0);
1428             alarmed = 0;
1429             return (1);
1430         }
1431
1432         for (n = 0; n < n_aborts; ++n) {
1433             if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1434                 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1435                 if (verbose) {
1436                     if (s > logged)
1437                         msgf("%0.*v", s - logged, logged);
1438                     msgf(" -- failed");
1439                 }
1440
1441                 alarm(0);
1442                 alarmed = 0;
1443                 exit_code = n + 4;
1444                 strcpy(fail_reason = fail_buffer, abort_string[n]);
1445                 return (0);
1446             }
1447         }
1448
1449         if (s >= end) {
1450             if (logged < s - minlen) {
1451                 if (verbose)
1452                     msgf("%0.*v", s - logged, logged);
1453                 logged = s;
1454             }
1455             s -= minlen;
1456             memmove(temp, s, minlen);
1457             logged = temp + (logged - s);
1458             s = temp + minlen;
1459         }
1460
1461         if (alarmed && verbose)
1462             msgf("warning: alarm synchronization problem");
1463     }
1464
1465     alarm(0);
1466     
1467     if (verbose && printed) {
1468         if (alarmed)
1469             msgf(" -- read timed out");
1470         else
1471             msgf(" -- read failed: %m");
1472     }
1473
1474     exit_code = 3;
1475     alarmed   = 0;
1476     return (0);
1477 }
1478
1479 /*
1480  * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1481  */
1482 #ifdef SOL2
1483 #include <sys/param.h>
1484 #if MAXUID > 65536              /* then this is Solaris 2.6 or later */
1485 #undef NO_USLEEP
1486 #endif
1487 #endif /* SOL2 */
1488
1489 #ifdef NO_USLEEP
1490 #include <sys/types.h>
1491 #include <sys/time.h>
1492
1493 /*
1494   usleep -- support routine for 4.2BSD system call emulations
1495   last edit:  29-Oct-1984     D A Gwyn
1496   */
1497
1498 extern int        select();
1499
1500 /* returns 0 if ok, else -1 */
1501 int usleep(long usec)           /* delay in microseconds */
1502 {
1503     static struct {             /* `timeval' */
1504         long    tv_sec;         /* seconds */
1505         long    tv_usec;        /* microsecs */
1506     } delay;                    /* _select() timeout */
1507
1508     delay.tv_sec  = usec / 1000000L;
1509     delay.tv_usec = usec % 1000000L;
1510
1511     return select(0, (long *)0, (long *)0, (long *)0, &delay);
1512 }
1513 #endif
1514
1515 void pack_array (
1516     char **array, /* The address of the array of string pointers */
1517     int end)      /* The index of the next free entry before CLR_ */
1518 {
1519     int i, j;
1520
1521     for (i = 0; i < end; i++) {
1522         if (array[i] == NULL) {
1523             for (j = i+1; j < end; ++j)
1524                 if (array[j] != NULL)
1525                     array[i++] = array[j];
1526             for (; i < end; ++i)
1527                 array[i] = NULL;
1528             break;
1529         }
1530     }
1531 }
1532
1533 /*
1534  * vfmtmsg - format a message into a buffer.  Like vsprintf except we
1535  * also specify the length of the output buffer, and we handle the
1536  * %m (error message) format.
1537  * Doesn't do floating-point formats.
1538  * Returns the number of chars put into buf.
1539  */
1540 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1541
1542 int
1543 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1544 {
1545     int c, i, n;
1546     int width, prec, fillch;
1547     int base, len, neg, quoted;
1548     unsigned long val = 0;
1549     char *str, *buf0;
1550     const char *f;
1551     unsigned char *p;
1552     char num[32];
1553     static char hexchars[] = "0123456789abcdef";
1554
1555     buf0 = buf;
1556     --buflen;
1557     while (buflen > 0) {
1558         for (f = fmt; *f != '%' && *f != 0; ++f)
1559             ;
1560         if (f > fmt) {
1561             len = f - fmt;
1562             if (len > buflen)
1563                 len = buflen;
1564             memcpy(buf, fmt, len);
1565             buf += len;
1566             buflen -= len;
1567             fmt = f;
1568         }
1569         if (*fmt == 0)
1570             break;
1571         c = *++fmt;
1572         width = prec = 0;
1573         fillch = ' ';
1574         if (c == '0') {
1575             fillch = '0';
1576             c = *++fmt;
1577         }
1578         if (c == '*') {
1579             width = va_arg(args, int);
1580             c = *++fmt;
1581         } else {
1582             while (isdigit(c)) {
1583                 width = width * 10 + c - '0';
1584                 c = *++fmt;
1585             }
1586         }
1587         if (c == '.') {
1588             c = *++fmt;
1589             if (c == '*') {
1590                 prec = va_arg(args, int);
1591                 c = *++fmt;
1592             } else {
1593                 while (isdigit(c)) {
1594                     prec = prec * 10 + c - '0';
1595                     c = *++fmt;
1596                 }
1597             }
1598         }
1599         str = 0;
1600         base = 0;
1601         neg = 0;
1602         ++fmt;
1603         switch (c) {
1604         case 'd':
1605             i = va_arg(args, int);
1606             if (i < 0) {
1607                 neg = 1;
1608                 val = -i;
1609             } else
1610                 val = i;
1611             base = 10;
1612             break;
1613         case 'o':
1614             val = va_arg(args, unsigned int);
1615             base = 8;
1616             break;
1617         case 'x':
1618             val = va_arg(args, unsigned int);
1619             base = 16;
1620             break;
1621         case 'p':
1622             val = (unsigned long) va_arg(args, void *);
1623             base = 16;
1624             neg = 2;
1625             break;
1626         case 's':
1627             str = va_arg(args, char *);
1628             break;
1629         case 'c':
1630             num[0] = va_arg(args, int);
1631             num[1] = 0;
1632             str = num;
1633             break;
1634         case 'm':
1635             str = strerror(errno);
1636             break;
1637         case 'v':               /* "visible" string */
1638         case 'q':               /* quoted string */
1639             quoted = c == 'q';
1640             p = va_arg(args, unsigned char *);
1641             if (fillch == '0' && prec > 0) {
1642                 n = prec;
1643             } else {
1644                 n = strlen((char *)p);
1645                 if (prec > 0 && prec < n)
1646                     n = prec;
1647             }
1648             while (n > 0 && buflen > 0) {
1649                 c = *p++;
1650                 --n;
1651                 if (!quoted && c >= 0x80) {
1652                     OUTCHAR('M');
1653                     OUTCHAR('-');
1654                     c -= 0x80;
1655                 }
1656                 if (quoted && (c == '"' || c == '\\'))
1657                     OUTCHAR('\\');
1658                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1659                     if (quoted) {
1660                         OUTCHAR('\\');
1661                         switch (c) {
1662                         case '\t':      OUTCHAR('t');   break;
1663                         case '\n':      OUTCHAR('n');   break;
1664                         case '\b':      OUTCHAR('b');   break;
1665                         case '\f':      OUTCHAR('f');   break;
1666                         default:
1667                             OUTCHAR('x');
1668                             OUTCHAR(hexchars[c >> 4]);
1669                             OUTCHAR(hexchars[c & 0xf]);
1670                         }
1671                     } else {
1672                         if (c == '\t')
1673                             OUTCHAR(c);
1674                         else {
1675                             OUTCHAR('^');
1676                             OUTCHAR(c ^ 0x40);
1677                         }
1678                     }
1679                 } else
1680                     OUTCHAR(c);
1681             }
1682             continue;
1683         default:
1684             *buf++ = '%';
1685             if (c != '%')
1686                 --fmt;          /* so %z outputs %z etc. */
1687             --buflen;
1688             continue;
1689         }
1690         if (base != 0) {
1691             str = num + sizeof(num);
1692             *--str = 0;
1693             while (str > num + neg) {
1694                 *--str = hexchars[val % base];
1695                 val = val / base;
1696                 if (--prec <= 0 && val == 0)
1697                     break;
1698             }
1699             switch (neg) {
1700             case 1:
1701                 *--str = '-';
1702                 break;
1703             case 2:
1704                 *--str = 'x';
1705                 *--str = '0';
1706                 break;
1707             }
1708             len = num + sizeof(num) - 1 - str;
1709         } else {
1710             len = strlen(str);
1711             if (prec > 0 && len > prec)
1712                 len = prec;
1713         }
1714         if (width > 0) {
1715             if (width > buflen)
1716                 width = buflen;
1717             if ((n = width - len) > 0) {
1718                 buflen -= n;
1719                 for (; n > 0; --n)
1720                     *buf++ = fillch;
1721             }
1722         }
1723         if (len > buflen)
1724             len = buflen;
1725         memcpy(buf, str, len);
1726         buf += len;
1727         buflen -= len;
1728     }
1729     *buf = 0;
1730     return buf - buf0;
1731 }