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