]> git.ozlabs.org Git - ppp.git/blob - chat/chat.c
add -s, -S, -T, -U flags
[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.16 1997/11/27 06:00:06 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 #if __STDC__
110 #include <stdarg.h>
111 #define __V(x)  x
112 #else
113 #include <varargs.h>
114 #define __V(x)  (va_alist) va_dcl
115 #define const
116 #endif
117
118 #define STR_LEN 1024
119
120 #ifndef SIGTYPE
121 #define SIGTYPE void
122 #endif
123
124 #undef __P
125 #undef __V
126
127 #ifdef __STDC__
128 #include <stdarg.h>
129 #define __V(x)  x
130 #define __P(x)  x
131 #else
132 #include <varargs.h>
133 #define __V(x)  (va_alist) va_dcl
134 #define __P(x)  ()
135 #define const
136 #endif
137
138 #ifndef O_NONBLOCK
139 #define O_NONBLOCK      O_NDELAY
140 #endif
141
142 /*************** Micro getopt() *********************************************/
143 #define OPTION(c,v)     (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
144                                 ((--c,++v),_O=4,c)&&**v=='-'&&v[0][1]?*++*v=='-'\
145                                 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
146 #define OPTARG(c,v)     (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
147                                 (_O=4,(char*)0):(char*)0)
148 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
149 #define ARG(c,v)        (c?(--c,*v++):(char*)0)
150
151 static int _O = 0;              /* Internal state */
152 /*************** Micro getopt() *********************************************/
153
154 char *program_name;
155
156 #define MAX_ABORTS              50
157 #define MAX_REPORTS             50
158 #define DEFAULT_CHAT_TIMEOUT    45
159
160 int echo          = 0;
161 int verbose       = 0;
162 int to_log        = 1;
163 int to_stderr     = 0;
164 int Verbose       = 0;
165 int quiet         = 0;
166 int report        = 0;
167 int exit_code     = 0;
168 FILE* report_fp   = (FILE *) 0;
169 char *report_file = (char *) 0;
170 char *chat_file   = (char *) 0;
171 char *phone_num   = (char *) 0;
172 char *phone_num2  = (char *) 0;
173 int timeout       = DEFAULT_CHAT_TIMEOUT;
174
175 int have_tty_parameters = 0;
176
177 #ifdef TERMIO
178 #define term_parms struct termio
179 #define get_term_param(param) ioctl(0, TCGETA, param)
180 #define set_term_param(param) ioctl(0, TCSETA, param)
181 struct termio saved_tty_parameters;
182 #endif
183
184 #ifdef TERMIOS
185 #define term_parms struct termios
186 #define get_term_param(param) tcgetattr(0, param)
187 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
188 struct termios saved_tty_parameters;
189 #endif
190
191 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
192         fail_buffer[50];
193 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
194 int clear_abort_next = 0;
195
196 char *report_string[MAX_REPORTS] ;
197 char  report_buffer[50] ;
198 int n_reports = 0, report_next = 0, report_gathering = 0 ; 
199 int clear_report_next = 0;
200
201 int say_next = 0, hup_next = 0;
202
203 void *dup_mem __P((void *b, size_t c));
204 void *copy_of __P((char *s));
205 void usage __P((void));
206 void logf __P((const char *fmt, ...));
207 void fatal __P((int code, const char *fmt, ...));
208 SIGTYPE sigalrm __P((int signo));
209 SIGTYPE sigint __P((int signo));
210 SIGTYPE sigterm __P((int signo));
211 SIGTYPE sighup __P((int signo));
212 void unalarm __P((void));
213 void init __P((void));
214 void set_tty_parameters __P((void));
215 void echo_stderr __P((int));
216 void break_sequence __P((void));
217 void terminate __P((int status));
218 void do_file __P((char *chat_file));
219 int  get_string __P((register char *string));
220 int  put_string __P((register char *s));
221 int  write_char __P((int c));
222 int  put_char __P((int c));
223 int  get_char __P((void));
224 void chat_send __P((register char *s));
225 char *character __P((int c));
226 void chat_expect __P((register char *s));
227 char *clean __P((register char *s, int sending));
228 void break_sequence __P((void));
229 void terminate __P((int status));
230 void pack_array __P((char **array, int end));
231 char *expect_strtok __P((char *, char *));
232 int vfmtmsg __P((char *, int, const char *, va_list));  /* vsprintf++ */
233
234 int main __P((int, char *[]));
235
236 void *dup_mem(b, c)
237 void *b;
238 size_t c;
239 {
240     void *ans = malloc (c);
241     if (!ans)
242         fatal(2, "memory error!");
243
244     memcpy (ans, b, c);
245     return ans;
246 }
247
248 void *copy_of (s)
249 char *s;
250 {
251     return dup_mem (s, strlen (s) + 1);
252 }
253
254 /*
255  * chat [ -v ] [-T number] [-U number] [ -t timeout ] [ -f chat-file ] \
256  * [ -r report-file ] \
257  *              [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
258  *
259  *      Perform a UUCP-dialer-like chat script on stdin and stdout.
260  */
261 int
262 main(argc, argv)
263      int argc;
264      char **argv;
265 {
266     int option;
267     char *arg;
268
269     program_name = *argv;
270     tzset();
271
272     while ((option = OPTION(argc, argv)) != 0) {
273         switch (option) {
274         case 'e':
275             ++echo;
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 (chat_file)
388 char *chat_file;
389 {
390     int linect, sendflg;
391     char *sp, *arg, quote;
392     char buf [STR_LEN];
393     FILE *cfp;
394
395     cfp = fopen (chat_file, "r");
396     if (cfp == NULL)
397         fatal(1, "%s -- open failed: %m", chat_file);
398
399     linect = 0;
400     sendflg = 0;
401
402     while (fgets(buf, STR_LEN, cfp) != NULL) {
403         sp = strchr (buf, '\n');
404         if (sp)
405             *sp = '\0';
406
407         linect++;
408         sp = buf;
409
410         /* lines starting with '#' are comments. If a real '#'
411            is to be expected, it should be quoted .... */
412         if ( *sp == '#' )
413             continue;
414
415         while (*sp != '\0') {
416             if (*sp == ' ' || *sp == '\t') {
417                 ++sp;
418                 continue;
419             }
420
421             if (*sp == '"' || *sp == '\'') {
422                 quote = *sp++;
423                 arg = sp;
424                 while (*sp != quote) {
425                     if (*sp == '\0')
426                         fatal(1, "unterminated quote (line %d)", linect);
427
428                     if (*sp++ == '\\') {
429                         if (*sp != '\0')
430                             ++sp;
431                     }
432                 }
433             }
434             else {
435                 arg = sp;
436                 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
437                     ++sp;
438             }
439
440             if (*sp != '\0')
441                 *sp++ = '\0';
442
443             if (sendflg)
444                 chat_send (arg);
445             else
446                 chat_expect (arg);
447             sendflg = !sendflg;
448         }
449     }
450     fclose (cfp);
451 }
452
453 /*
454  *      We got an error parsing the command line.
455  */
456 void usage()
457 {
458     fprintf(stderr, "\
459 Usage: %s [-e] [-v] [-t timeout] [-r report-file] [-T phone-number]\n\
460      [-U phone-number2] {-f chat-file | chat-script}\n", program_name);
461     exit(1);
462 }
463
464 char line[1024];
465
466 /*
467  * Send a message to syslog and/or stderr.
468  */
469 void logf __V((const char *fmt, ...))
470 {
471     va_list args;
472
473 #if __STDC__
474     va_start(args, fmt);
475 #else
476     char *fmt;
477     va_start(args);
478     fmt = va_arg(args, char *);
479 #endif
480
481     vfmtmsg(line, sizeof(line), fmt, args);
482     if (to_log)
483         syslog(LOG_INFO, "%s", line);
484     if (to_stderr)
485         fprintf(stderr, "%s\n", line);
486 }
487
488 /*
489  *      Print an error message and terminate.
490  */
491
492 void fatal __V((int code, const char *fmt, ...))
493 {
494     va_list args;
495
496 #if __STDC__
497     va_start(args, fmt);
498 #else
499     int code;
500     char *fmt;
501     va_start(args);
502     code = va_arg(args, int);
503     fmt = va_arg(args, char *);
504 #endif
505
506     vfmtmsg(line, sizeof(line), fmt, args);
507     if (to_log)
508         syslog(LOG_ERR, "%s", line);
509     if (to_stderr)
510         fprintf(stderr, "%s\n", line);
511     terminate(code);
512 }
513
514 int alarmed = 0;
515
516 SIGTYPE sigalrm(signo)
517 int signo;
518 {
519     int flags;
520
521     alarm(1);
522     alarmed = 1;                /* Reset alarm to avoid race window */
523     signal(SIGALRM, sigalrm);   /* that can cause hanging in read() */
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     if (verbose)
532         logf("alarm");
533 }
534
535 void unalarm()
536 {
537     int flags;
538
539     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
540         fatal(2, "Can't get file mode flags on stdin: %m");
541
542     if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
543         fatal(2, "Can't set file mode flags on stdin: %m");
544 }
545
546 SIGTYPE sigint(signo)
547 int signo;
548 {
549     fatal(2, "SIGINT");
550 }
551
552 SIGTYPE sigterm(signo)
553 int signo;
554 {
555     fatal(2, "SIGTERM");
556 }
557
558 SIGTYPE sighup(signo)
559 int signo;
560 {
561     fatal(2, "SIGHUP");
562 }
563
564 void init()
565 {
566     signal(SIGINT, sigint);
567     signal(SIGTERM, sigterm);
568     signal(SIGHUP, sighup);
569
570     set_tty_parameters();
571     signal(SIGALRM, sigalrm);
572     alarm(0);
573     alarmed = 0;
574 }
575
576 void set_tty_parameters()
577 {
578 #if defined(get_term_param)
579     term_parms t;
580
581     if (get_term_param (&t) < 0)
582         fatal(2, "Can't get terminal parameters: %m");
583
584     saved_tty_parameters = t;
585     have_tty_parameters  = 1;
586
587     t.c_iflag     |= IGNBRK | ISTRIP | IGNPAR;
588     t.c_oflag      = 0;
589     t.c_lflag      = 0;
590     t.c_cc[VERASE] =
591     t.c_cc[VKILL]  = 0;
592     t.c_cc[VMIN]   = 1;
593     t.c_cc[VTIME]  = 0;
594
595     if (set_term_param (&t) < 0)
596         fatal(2, "Can't set terminal parameters: %m");
597 #endif
598 }
599
600 void break_sequence()
601 {
602 #ifdef TERMIOS
603     tcsendbreak (0, 0);
604 #endif
605 }
606
607 void terminate(status)
608 int status;
609 {
610     echo_stderr(-1);
611     if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
612 /*
613  * Allow the last of the report string to be gathered before we terminate.
614  */
615         if (report_gathering) {
616             int c, rep_len;
617
618             rep_len = strlen(report_buffer);
619             while (rep_len + 1 <= sizeof(report_buffer)) {
620                 alarm(1);
621                 c = get_char();
622                 alarm(0);
623                 if (c < 0 || iscntrl(c))
624                     break;
625                 report_buffer[rep_len] = c;
626                 ++rep_len;
627             }
628             report_buffer[rep_len] = 0;
629             fprintf (report_fp, "chat:  %s\n", report_buffer);
630         }
631         if (verbose)
632             fprintf (report_fp, "Closing \"%s\".\n", report_file);
633         fclose (report_fp);
634         report_fp = (FILE *) NULL;
635     }
636
637 #if defined(get_term_param)
638     if (have_tty_parameters) {
639         if (set_term_param (&saved_tty_parameters) < 0)
640             fatal(2, "Can't restore terminal parameters: %m");
641     }
642 #endif
643
644     exit(status);
645 }
646
647 /*
648  *      'Clean up' this string.
649  */
650 char *clean(s, sending)
651 register char *s;
652 int sending;  /* set to 1 when sending (putting) this string. */
653 {
654     char temp[STR_LEN], cur_chr;
655     register char *s1, *phchar;
656     int add_return = sending;
657 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
658
659     s1 = temp;
660     while (*s) {
661         cur_chr = *s++;
662         if (cur_chr == '^') {
663             cur_chr = *s++;
664             if (cur_chr == '\0') {
665                 *s1++ = '^';
666                 break;
667             }
668             cur_chr &= 0x1F;
669             if (cur_chr != 0) {
670                 *s1++ = cur_chr;
671             }
672             continue;
673         }
674
675         if (cur_chr != '\\') {
676             *s1++ = cur_chr;
677             continue;
678         }
679
680         cur_chr = *s++;
681         if (cur_chr == '\0') {
682             if (sending) {
683                 *s1++ = '\\';
684                 *s1++ = '\\';
685             }
686             break;
687         }
688
689         switch (cur_chr) {
690         case 'b':
691             *s1++ = '\b';
692             break;
693
694         case 'c':
695             if (sending && *s == '\0')
696                 add_return = 0;
697             else
698                 *s1++ = cur_chr;
699             break;
700
701         case '\\':
702         case 'K':
703         case 'p':
704         case 'd':
705             if (sending)
706                 *s1++ = '\\';
707
708             *s1++ = cur_chr;
709             break;
710
711         case 'T':
712             if (sending && phone_num) {
713                 for ( phchar = phone_num; *phchar != '\0'; phchar++) 
714                     *s1++ = *phchar;
715             }
716             else {
717                 *s1++ = '\\';
718                 *s1++ = 'T';
719             }
720             break;
721
722         case 'U':
723             if (sending && phone_num2) {
724                 for ( phchar = phone_num2; *phchar != '\0'; phchar++) 
725                     *s1++ = *phchar;
726             }
727             else {
728                 *s1++ = '\\';
729                 *s1++ = 'U';
730             }
731             break;
732
733         case 'q':
734             quiet = 1;
735             break;
736
737         case 'r':
738             *s1++ = '\r';
739             break;
740
741         case 'n':
742             *s1++ = '\n';
743             break;
744
745         case 's':
746             *s1++ = ' ';
747             break;
748
749         case 't':
750             *s1++ = '\t';
751             break;
752
753         case 'N':
754             if (sending) {
755                 *s1++ = '\\';
756                 *s1++ = '\0';
757             }
758             else
759                 *s1++ = 'N';
760             break;
761             
762         default:
763             if (isoctal (cur_chr)) {
764                 cur_chr &= 0x07;
765                 if (isoctal (*s)) {
766                     cur_chr <<= 3;
767                     cur_chr |= *s++ - '0';
768                     if (isoctal (*s)) {
769                         cur_chr <<= 3;
770                         cur_chr |= *s++ - '0';
771                     }
772                 }
773
774                 if (cur_chr != 0 || sending) {
775                     if (sending && (cur_chr == '\\' || cur_chr == 0))
776                         *s1++ = '\\';
777                     *s1++ = cur_chr;
778                 }
779                 break;
780             }
781
782             if (sending)
783                 *s1++ = '\\';
784             *s1++ = cur_chr;
785             break;
786         }
787     }
788
789     if (add_return)
790         *s1++ = '\r';
791
792     *s1++ = '\0'; /* guarantee closure */
793     *s1++ = '\0'; /* terminate the string */
794     return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
795 }
796
797 /*
798  * A modified version of 'strtok'. This version skips \ sequences.
799  */
800
801 char *expect_strtok (s, term)
802      char *s, *term;
803 {
804     static  char *str   = "";
805     int     escape_flag = 0;
806     char   *result;
807
808 /*
809  * If a string was specified then do initial processing.
810  */
811     if (s)
812         str = s;
813
814 /*
815  * If this is the escape flag then reset it and ignore the character.
816  */
817     if (*str)
818         result = str;
819     else
820         result = (char *) 0;
821
822     while (*str) {
823         if (escape_flag) {
824             escape_flag = 0;
825             ++str;
826             continue;
827         }
828
829         if (*str == '\\') {
830             ++str;
831             escape_flag = 1;
832             continue;
833         }
834
835 /*
836  * If this is not in the termination string, continue.
837  */
838         if (strchr (term, *str) == (char *) 0) {
839             ++str;
840             continue;
841         }
842
843 /*
844  * This is the terminator. Mark the end of the string and stop.
845  */
846         *str++ = '\0';
847         break;
848     }
849     return (result);
850 }
851
852 /*
853  * Process the expect string
854  */
855
856 void chat_expect (s)
857 char *s;
858 {
859     char *expect;
860     char *reply;
861
862     if (strcmp(s, "HANGUP") == 0) {
863         ++hup_next;
864         return;
865     }
866  
867     if (strcmp(s, "ABORT") == 0) {
868         ++abort_next;
869         return;
870     }
871
872     if (strcmp(s, "CLR_ABORT") == 0) {
873         ++clear_abort_next;
874         return;
875     }
876
877     if (strcmp(s, "REPORT") == 0) {
878         ++report_next;
879         return;
880     }
881
882     if (strcmp(s, "CLR_REPORT") == 0) {
883         ++clear_report_next;
884         return;
885     }
886
887     if (strcmp(s, "TIMEOUT") == 0) {
888         ++timeout_next;
889         return;
890     }
891
892     if (strcmp(s, "ECHO") == 0) {
893         ++echo_next;
894         return;
895     }
896
897     if (strcmp(s, "SAY") == 0) {
898         ++say_next;
899         return;
900     }
901
902 /*
903  * Fetch the expect and reply string.
904  */
905     for (;;) {
906         expect = expect_strtok (s, "-");
907         s      = (char *) 0;
908
909         if (expect == (char *) 0)
910             return;
911
912         reply = expect_strtok (s, "-");
913
914 /*
915  * Handle the expect string. If successful then exit.
916  */
917         if (get_string (expect))
918             return;
919
920 /*
921  * If there is a sub-reply string then send it. Otherwise any condition
922  * is terminal.
923  */
924         if (reply == (char *) 0 || exit_code != 3)
925             break;
926
927         chat_send (reply);
928     }
929
930 /*
931  * The expectation did not occur. This is terminal.
932  */
933     if (fail_reason)
934         logf("Failed (%s)", fail_reason);
935     else
936         logf("Failed");
937     terminate(exit_code);
938 }
939
940 /*
941  * Translate the input character to the appropriate string for printing
942  * the data.
943  */
944
945 char *character(c)
946 int c;
947 {
948     static char string[10];
949     char *meta;
950
951     meta = (c & 0x80) ? "M-" : "";
952     c &= 0x7F;
953
954     if (c < 32)
955         sprintf(string, "%s^%c", meta, (int)c + '@');
956     else if (c == 127)
957         sprintf(string, "%s^?", meta);
958     else
959         sprintf(string, "%s%c", meta, c);
960
961     return (string);
962 }
963
964 /*
965  *  process the reply string
966  */
967 void chat_send (s)
968 register char *s;
969 {
970     if (say_next) {
971         say_next = 0;
972         s = clean(s,0);
973         write(2, s, strlen(s));
974         free(s);
975         return;
976     }
977
978     if (hup_next) {
979         hup_next = 0;
980         if (strcmp(s, "OFF") == 0)
981            signal(SIGHUP, SIG_IGN);
982         else
983            signal(SIGHUP, sighup);
984         return;
985     }
986
987     if (echo_next) {
988         echo_next = 0;
989         echo = (strcmp(s, "ON") == 0);
990         return;
991     }
992
993     if (abort_next) {
994         char *s1;
995         
996         abort_next = 0;
997         
998         if (n_aborts >= MAX_ABORTS)
999             fatal(2, "Too many ABORT strings");
1000         
1001         s1 = clean(s, 0);
1002         
1003         if (strlen(s1) > strlen(s)
1004             || strlen(s1) + 1 > sizeof(fail_buffer))
1005             fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1006
1007         abort_string[n_aborts++] = s1;
1008
1009         if (verbose)
1010             logf("abort on (%v)", s);
1011         return;
1012     }
1013
1014     if (clear_abort_next) {
1015         char *s1;
1016         char *s2 = s;
1017         int   i;
1018         int   old_max;
1019         int   pack = 0;
1020         
1021         clear_abort_next = 0;
1022         
1023         s1 = clean(s, 0);
1024         
1025         if (strlen(s1) > strlen(s)
1026             || strlen(s1) + 1 > sizeof(fail_buffer))
1027             fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1028
1029         old_max = n_aborts;
1030         for (i=0; i < n_aborts; i++) {
1031             if ( strcmp(s1,abort_string[i]) == 0 ) {
1032                 free(abort_string[i]);
1033                 abort_string[i] = NULL;
1034                 pack++;
1035                 n_aborts--;
1036                 if (verbose)
1037                     logf("clear abort on (%v)", s);
1038             }
1039         }
1040         free(s1);
1041         if (pack)
1042             pack_array(abort_string,old_max);
1043         return;
1044     }
1045
1046     if (report_next) {
1047         char *s1;
1048         
1049         report_next = 0;
1050         if (n_reports >= MAX_REPORTS)
1051             fatal(2, "Too many REPORT strings");
1052         
1053         s1 = clean(s, 0);
1054         
1055         if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1056             fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1057         
1058         report_string[n_reports++] = s1;
1059         
1060         if (verbose)
1061             logf("report (%v)", s);
1062         return;
1063     }
1064
1065     if (clear_report_next) {
1066         char *s1;
1067         char *s2 = s;
1068         int   i;
1069         int   old_max;
1070         int   pack = 0;
1071         
1072         clear_report_next = 0;
1073         
1074         s1 = clean(s, 0);
1075         
1076         if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1077             fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1078
1079         old_max = n_reports;
1080         for (i=0; i < n_reports; i++) {
1081             if ( strcmp(s1,report_string[i]) == 0 ) {
1082                 free(report_string[i]);
1083                 report_string[i] = NULL;
1084                 pack++;
1085                 n_reports--;
1086                 if (verbose)
1087                     logf("clear report (%v)", s);
1088             }
1089         }
1090         free(s1);
1091         if (pack)
1092             pack_array(report_string,old_max);
1093         
1094         return;
1095     }
1096
1097     if (timeout_next) {
1098         timeout_next = 0;
1099         timeout = atoi(s);
1100         
1101         if (timeout <= 0)
1102             timeout = DEFAULT_CHAT_TIMEOUT;
1103
1104         if (verbose)
1105             logf("timeout set to %d seconds", timeout);
1106
1107         return;
1108     }
1109
1110     if (strcmp(s, "EOT") == 0)
1111         s = "^D\\c";
1112     else if (strcmp(s, "BREAK") == 0)
1113         s = "\\K\\c";
1114
1115     if (!put_string(s))
1116         fatal(1, "Failed");
1117 }
1118
1119 int get_char()
1120 {
1121     int status;
1122     char c;
1123
1124     status = read(0, &c, 1);
1125
1126     switch (status) {
1127     case 1:
1128         return ((int)c & 0x7F);
1129
1130     default:
1131         logf("warning: read() on stdin returned %d", status);
1132
1133     case -1:
1134         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1135             fatal(2, "Can't get file mode flags on stdin: %m");
1136
1137         if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1138             fatal(2, "Can't set file mode flags on stdin: %m");
1139         
1140         return (-1);
1141     }
1142 }
1143
1144 int put_char(c)
1145 int c;
1146 {
1147     int status;
1148     char ch = c;
1149
1150     usleep(10000);              /* inter-character typing delay (?) */
1151
1152     status = write(1, &ch, 1);
1153
1154     switch (status) {
1155     case 1:
1156         return (0);
1157         
1158     default:
1159         logf("warning: write() on stdout returned %d", status);
1160         
1161     case -1:
1162         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1163             fatal(2, "Can't get file mode flags on stdin, %m");
1164
1165         if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1166             fatal(2, "Can't set file mode flags on stdin: %m");
1167         
1168         return (-1);
1169     }
1170 }
1171
1172 int write_char (c)
1173 int c;
1174 {
1175     if (alarmed || put_char(c) < 0) {
1176         alarm(0);
1177         alarmed = 0;
1178
1179         if (verbose) {
1180             if (errno == EINTR || errno == EWOULDBLOCK)
1181                 logf(" -- write timed out");
1182             else
1183                 logf(" -- write failed: %m");
1184         }
1185         return (0);
1186     }
1187     return (1);
1188 }
1189
1190 int put_string (s)
1191 register char *s;
1192 {
1193     quiet = 0;
1194     s = clean(s, 1);
1195
1196     if (verbose) {
1197         if (quiet)
1198             logf("send (??????)");
1199         else
1200             logf("send (%v)", s);
1201     }
1202
1203     alarm(timeout); alarmed = 0;
1204
1205     while (*s) {
1206         register char c = *s++;
1207
1208         if (c != '\\') {
1209             if (!write_char (c))
1210                 return 0;
1211             continue;
1212         }
1213
1214         c = *s++;
1215         switch (c) {
1216         case 'd':
1217             sleep(1);
1218             break;
1219
1220         case 'K':
1221             break_sequence();
1222             break;
1223
1224         case 'p':
1225             usleep(10000);      /* 1/100th of a second (arg is microseconds) */
1226             break;
1227
1228         default:
1229             if (!write_char (c))
1230                 return 0;
1231             break;
1232         }
1233     }
1234
1235     alarm(0);
1236     alarmed = 0;
1237     return (1);
1238 }
1239
1240 /*
1241  *      Echo a character to stderr.
1242  *      When called with -1, a '\n' character is generated when
1243  *      the cursor is not at the beginning of a line.
1244  */
1245 void echo_stderr(n)
1246 int n;
1247 {
1248     static int need_lf;
1249     char *s;
1250
1251     switch (n) {
1252     case '\r':          /* ignore '\r' */
1253         break;
1254     case -1:
1255         if (need_lf == 0)
1256             break;
1257         /* fall through */
1258     case '\n':
1259         write(2, "\n", 1);
1260         need_lf = 0;
1261         break;
1262     default:
1263         s = character(n);
1264         write(2, s, strlen(s));
1265         need_lf = 1;
1266         break;
1267     }
1268 }
1269
1270 /*
1271  *      'Wait for' this string to appear on this file descriptor.
1272  */
1273 int get_string(string)
1274 register char *string;
1275 {
1276     char temp[STR_LEN];
1277     int c, printed = 0, len, minlen;
1278     register char *s = temp, *end = s + STR_LEN;
1279     char *logged = temp;
1280
1281     fail_reason = (char *)0;
1282     string = clean(string, 0);
1283     len = strlen(string);
1284     minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1285
1286     if (verbose)
1287         logf("expect (%v)", string);
1288
1289     if (len > STR_LEN) {
1290         logf("expect string is too long");
1291         exit_code = 1;
1292         return 0;
1293     }
1294
1295     if (len == 0) {
1296         if (verbose)
1297             logf("got it");
1298         return (1);
1299     }
1300
1301     alarm(timeout);
1302     alarmed = 0;
1303
1304     while ( ! alarmed && (c = get_char()) >= 0) {
1305         int n, abort_len, report_len;
1306
1307         if (echo)
1308             echo_stderr(c);
1309         if (verbose && c == '\n') {
1310             if (s == logged)
1311                 logf("");       /* blank line */
1312             else
1313                 logf("%0.*v", s - logged, logged);
1314             logged = s + 1;
1315         }
1316
1317         *s++ = c;
1318
1319         if (verbose && s >= logged + 80) {
1320             logf("%0.*v", s - logged, logged);
1321             logged = s;
1322         }
1323
1324         if (Verbose) {
1325            if (c == '\n')
1326                fputc( '\n', stderr );
1327            else if (c != '\r')
1328                fprintf( stderr, "%s", character(c) );
1329         }
1330
1331         if (!report_gathering) {
1332             for (n = 0; n < n_reports; ++n) {
1333                 if ((report_string[n] != (char*) NULL) &&
1334                     s - temp >= (report_len = strlen(report_string[n])) &&
1335                     strncmp(s - report_len, report_string[n], report_len) == 0) {
1336                     time_t time_now   = time ((time_t*) NULL);
1337                     struct tm* tm_now = localtime (&time_now);
1338
1339                     strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1340                     strcat (report_buffer, report_string[n]);
1341
1342                     report_string[n] = (char *) NULL;
1343                     report_gathering = 1;
1344                     break;
1345                 }
1346             }
1347         }
1348         else {
1349             if (!iscntrl (c)) {
1350                 int rep_len = strlen (report_buffer);
1351                 report_buffer[rep_len]     = c;
1352                 report_buffer[rep_len + 1] = '\0';
1353             }
1354             else {
1355                 report_gathering = 0;
1356                 fprintf (report_fp, "chat:  %s\n", report_buffer);
1357             }
1358         }
1359
1360         if (s - temp >= len &&
1361             c == string[len - 1] &&
1362             strncmp(s - len, string, len) == 0) {
1363             if (verbose) {
1364                 if (s > logged)
1365                     logf("%0.*v", s - logged, logged);
1366                 logf(" -- got it\n");
1367             }
1368
1369             alarm(0);
1370             alarmed = 0;
1371             return (1);
1372         }
1373
1374         for (n = 0; n < n_aborts; ++n) {
1375             if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1376                 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1377                 if (verbose) {
1378                     if (s > logged)
1379                         logf("%0.*v", s - logged, logged);
1380                     logf(" -- failed");
1381                 }
1382
1383                 alarm(0);
1384                 alarmed = 0;
1385                 exit_code = n + 4;
1386                 strcpy(fail_reason = fail_buffer, abort_string[n]);
1387                 return (0);
1388             }
1389         }
1390
1391         if (s >= end) {
1392             if (logged < s - minlen) {
1393                 logf("%0.*v", s - logged, logged);
1394                 logged = s;
1395             }
1396             s -= minlen;
1397             memmove(temp, s, minlen);
1398             logged = temp + (logged - s);
1399             s = temp + minlen;
1400         }
1401
1402         if (alarmed && verbose)
1403             logf("warning: alarm synchronization problem");
1404     }
1405
1406     alarm(0);
1407     
1408     if (verbose && printed) {
1409         if (alarmed)
1410             logf(" -- read timed out");
1411         else
1412             logf(" -- read failed: %m");
1413     }
1414
1415     exit_code = 3;
1416     alarmed   = 0;
1417     return (0);
1418 }
1419
1420 #ifdef NO_USLEEP
1421 #include <sys/types.h>
1422 #include <sys/time.h>
1423
1424 /*
1425   usleep -- support routine for 4.2BSD system call emulations
1426   last edit:  29-Oct-1984     D A Gwyn
1427   */
1428
1429 extern int        select();
1430
1431 int
1432 usleep( usec )                            /* returns 0 if ok, else -1 */
1433     long                usec;           /* delay in microseconds */
1434 {
1435     static struct {             /* `timeval' */
1436         long    tv_sec;         /* seconds */
1437         long    tv_usec;        /* microsecs */
1438     } delay;                    /* _select() timeout */
1439
1440     delay.tv_sec  = usec / 1000000L;
1441     delay.tv_usec = usec % 1000000L;
1442
1443     return select(0, (long *)0, (long *)0, (long *)0, &delay);
1444 }
1445 #endif
1446
1447 void
1448 pack_array (array, end)
1449     char **array; /* The address of the array of string pointers */
1450     int    end;   /* The index of the next free entry before CLR_ */
1451 {
1452     int i, j;
1453
1454     for (i = 0; i < end; i++) {
1455         if (array[i] == NULL) {
1456             for (j = i+1; j < end; ++j)
1457                 if (array[j] != NULL)
1458                     array[i++] = array[j];
1459             for (; i < end; ++i)
1460                 array[i] = NULL;
1461             break;
1462         }
1463     }
1464 }
1465
1466 /*
1467  * vfmtmsg - format a message into a buffer.  Like vsprintf except we
1468  * also specify the length of the output buffer, and we handle the
1469  * %m (error message) format.
1470  * Doesn't do floating-point formats.
1471  * Returns the number of chars put into buf.
1472  */
1473 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1474
1475 int
1476 vfmtmsg(buf, buflen, fmt, args)
1477     char *buf;
1478     int buflen;
1479     const char *fmt;
1480     va_list args;
1481 {
1482     int c, i, n;
1483     int width, prec, fillch;
1484     int base, len, neg, quoted;
1485     unsigned long val = 0;
1486     char *str, *buf0;
1487     const char *f;
1488     unsigned char *p;
1489     char num[32];
1490     time_t t;
1491     static char hexchars[] = "0123456789abcdef";
1492
1493     buf0 = buf;
1494     --buflen;
1495     while (buflen > 0) {
1496         for (f = fmt; *f != '%' && *f != 0; ++f)
1497             ;
1498         if (f > fmt) {
1499             len = f - fmt;
1500             if (len > buflen)
1501                 len = buflen;
1502             memcpy(buf, fmt, len);
1503             buf += len;
1504             buflen -= len;
1505             fmt = f;
1506         }
1507         if (*fmt == 0)
1508             break;
1509         c = *++fmt;
1510         width = prec = 0;
1511         fillch = ' ';
1512         if (c == '0') {
1513             fillch = '0';
1514             c = *++fmt;
1515         }
1516         if (c == '*') {
1517             width = va_arg(args, int);
1518             c = *++fmt;
1519         } else {
1520             while (isdigit(c)) {
1521                 width = width * 10 + c - '0';
1522                 c = *++fmt;
1523             }
1524         }
1525         if (c == '.') {
1526             c = *++fmt;
1527             if (c == '*') {
1528                 prec = va_arg(args, int);
1529                 c = *++fmt;
1530             } else {
1531                 while (isdigit(c)) {
1532                     prec = prec * 10 + c - '0';
1533                     c = *++fmt;
1534                 }
1535             }
1536         }
1537         str = 0;
1538         base = 0;
1539         neg = 0;
1540         ++fmt;
1541         switch (c) {
1542         case 'd':
1543             i = va_arg(args, int);
1544             if (i < 0) {
1545                 neg = 1;
1546                 val = -i;
1547             } else
1548                 val = i;
1549             base = 10;
1550             break;
1551         case 'o':
1552             val = va_arg(args, unsigned int);
1553             base = 8;
1554             break;
1555         case 'x':
1556             val = va_arg(args, unsigned int);
1557             base = 16;
1558             break;
1559         case 'p':
1560             val = (unsigned long) va_arg(args, void *);
1561             base = 16;
1562             neg = 2;
1563             break;
1564         case 's':
1565             str = va_arg(args, char *);
1566             break;
1567         case 'c':
1568             num[0] = va_arg(args, int);
1569             num[1] = 0;
1570             str = num;
1571             break;
1572         case 'm':
1573             str = strerror(errno);
1574             break;
1575         case 'v':               /* "visible" string */
1576         case 'q':               /* quoted string */
1577             quoted = c == 'q';
1578             p = va_arg(args, unsigned char *);
1579             if (fillch == '0' && prec > 0) {
1580                 n = prec;
1581             } else {
1582                 n = strlen((char *)p);
1583                 if (prec > 0 && prec < n)
1584                     n = prec;
1585             }
1586             while (n > 0 && buflen > 0) {
1587                 c = *p++;
1588                 --n;
1589                 if (!quoted && c >= 0x80) {
1590                     OUTCHAR('M');
1591                     OUTCHAR('-');
1592                     c -= 0x80;
1593                 }
1594                 if (quoted && (c == '"' || c == '\\'))
1595                     OUTCHAR('\\');
1596                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1597                     if (quoted) {
1598                         OUTCHAR('\\');
1599                         switch (c) {
1600                         case '\t':      OUTCHAR('t');   break;
1601                         case '\n':      OUTCHAR('n');   break;
1602                         case '\b':      OUTCHAR('b');   break;
1603                         case '\f':      OUTCHAR('f');   break;
1604                         default:
1605                             OUTCHAR('x');
1606                             OUTCHAR(hexchars[c >> 4]);
1607                             OUTCHAR(hexchars[c & 0xf]);
1608                         }
1609                     } else {
1610                         if (c == '\t')
1611                             OUTCHAR(c);
1612                         else {
1613                             OUTCHAR('^');
1614                             OUTCHAR(c ^ 0x40);
1615                         }
1616                     }
1617                 } else
1618                     OUTCHAR(c);
1619             }
1620             continue;
1621         default:
1622             *buf++ = '%';
1623             if (c != '%')
1624                 --fmt;          /* so %z outputs %z etc. */
1625             --buflen;
1626             continue;
1627         }
1628         if (base != 0) {
1629             str = num + sizeof(num);
1630             *--str = 0;
1631             while (str > num + neg) {
1632                 *--str = hexchars[val % base];
1633                 val = val / base;
1634                 if (--prec <= 0 && val == 0)
1635                     break;
1636             }
1637             switch (neg) {
1638             case 1:
1639                 *--str = '-';
1640                 break;
1641             case 2:
1642                 *--str = 'x';
1643                 *--str = '0';
1644                 break;
1645             }
1646             len = num + sizeof(num) - 1 - str;
1647         } else {
1648             len = strlen(str);
1649             if (prec > 0 && len > prec)
1650                 len = prec;
1651         }
1652         if (width > 0) {
1653             if (width > buflen)
1654                 width = buflen;
1655             if ((n = width - len) > 0) {
1656                 buflen -= n;
1657                 for (; n > 0; --n)
1658                     *buf++ = fillch;
1659             }
1660         }
1661         if (len > buflen)
1662             len = buflen;
1663         memcpy(buf, str, len);
1664         buf += len;
1665         buflen -= len;
1666     }
1667     *buf = 0;
1668     return buf - buf0;
1669 }