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