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