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