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