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