]> git.ozlabs.org Git - ppp.git/blob - chat/chat.c
chat: Clean up usage of clean() function
[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) + 1 > sizeof(fail_buffer))
1024             fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1025
1026         abort_string[n_aborts++] = s1;
1027
1028         if (verbose)
1029             msgf("abort on (%v)", s1);
1030         return;
1031     }
1032
1033     if (clear_abort_next) {
1034         char *s1;
1035         int   i;
1036         int   old_max;
1037         int   pack = 0;
1038         
1039         clear_abort_next = 0;
1040         
1041         s1 = clean(s, 0);
1042         
1043         if (strlen(s1) + 1 > sizeof(fail_buffer))
1044             fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1045
1046         old_max = n_aborts;
1047         for (i=0; i < n_aborts; i++) {
1048             if ( strcmp(s1,abort_string[i]) == 0 ) {
1049                 free(abort_string[i]);
1050                 abort_string[i] = NULL;
1051                 pack++;
1052                 n_aborts--;
1053                 if (verbose)
1054                     msgf("clear abort on (%v)", s1);
1055             }
1056         }
1057         free(s1);
1058         if (pack)
1059             pack_array(abort_string,old_max);
1060         return;
1061     }
1062
1063     if (report_next) {
1064         char *s1;
1065         
1066         report_next = 0;
1067         if (n_reports >= MAX_REPORTS)
1068             fatal(2, "Too many REPORT strings");
1069         
1070         s1 = clean(s, 0);
1071         if (strlen(s1) + 1 > sizeof(fail_buffer))
1072             fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1073         
1074         report_string[n_reports++] = s1;
1075         
1076         if (verbose)
1077             msgf("report (%v)", s1);
1078         return;
1079     }
1080
1081     if (clear_report_next) {
1082         char *s1;
1083         int   i;
1084         int   old_max;
1085         int   pack = 0;
1086         
1087         clear_report_next = 0;
1088         
1089         s1 = clean(s, 0);
1090         
1091         if (strlen(s1) + 1 > sizeof(fail_buffer))
1092             fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1093
1094         old_max = n_reports;
1095         for (i=0; i < n_reports; i++) {
1096             if ( strcmp(s1,report_string[i]) == 0 ) {
1097                 free(report_string[i]);
1098                 report_string[i] = NULL;
1099                 pack++;
1100                 n_reports--;
1101                 if (verbose)
1102                     msgf("clear report (%v)", s1);
1103             }
1104         }
1105         free(s1);
1106         if (pack)
1107             pack_array(report_string,old_max);
1108         
1109         return;
1110     }
1111
1112     if (timeout_next) {
1113         timeout_next = 0;
1114         s = clean(s, 0);
1115         timeout = atoi(s);
1116         
1117         if (timeout <= 0)
1118             timeout = DEFAULT_CHAT_TIMEOUT;
1119
1120         if (verbose)
1121             msgf("timeout set to %d seconds", timeout);
1122
1123         return;
1124     }
1125
1126     /*
1127      * The syntax @filename means read the string to send from the
1128      * file `filename'.
1129      */
1130     if (s[0] == '@') {
1131         /* skip the @ and any following white-space */
1132         char *fn = s;
1133         while (*++fn == ' ' || *fn == '\t')
1134             ;
1135
1136         if (*fn != 0) {
1137             FILE *f;
1138             int n = 0;
1139
1140             /* open the file and read until STR_LEN-1 bytes or end-of-file */
1141             f = fopen(fn, "r");
1142             if (f == NULL)
1143                 fatal(1, "%s -- open failed: %m", fn);
1144             while (n < STR_LEN - 1) {
1145                 int nr = fread(&file_data[n], 1, STR_LEN - 1 - n, f);
1146                 if (nr < 0)
1147                     fatal(1, "%s -- read error", fn);
1148                 if (nr == 0)
1149                     break;
1150                 n += nr;
1151             }
1152             fclose(f);
1153
1154             /* use the string we got as the string to send,
1155                but trim off the final newline if any. */
1156             if (n > 0 && file_data[n-1] == '\n')
1157                 --n;
1158             file_data[n] = 0;
1159             s = file_data;
1160         }
1161     }
1162
1163     if (strcmp(s, "EOT") == 0)
1164         s = "^D\\c";
1165     else if (strcmp(s, "BREAK") == 0)
1166         s = "\\K\\c";
1167
1168     if (!put_string(s))
1169         fatal(1, "Failed");
1170 }
1171
1172 int get_char(void)
1173 {
1174     int status;
1175     char c;
1176
1177     status = read(0, &c, 1);
1178
1179     switch (status) {
1180     case 1:
1181         return ((int)c & 0x7F);
1182
1183     default:
1184         msgf("warning: read() on stdin returned %d", status);
1185
1186     case -1:
1187         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1188             fatal(2, "Can't get file mode flags on stdin: %m");
1189
1190         if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1191             fatal(2, "Can't set file mode flags on stdin: %m");
1192         
1193         return (-1);
1194     }
1195 }
1196
1197 int put_char(int c)
1198 {
1199     int status;
1200     char ch = c;
1201
1202     usleep(10000);              /* inter-character typing delay (?) */
1203
1204     status = write(1, &ch, 1);
1205
1206     switch (status) {
1207     case 1:
1208         return (0);
1209         
1210     default:
1211         msgf("warning: write() on stdout returned %d", status);
1212         
1213     case -1:
1214         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1215             fatal(2, "Can't get file mode flags on stdin, %m");
1216
1217         if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1218             fatal(2, "Can't set file mode flags on stdin: %m");
1219         
1220         return (-1);
1221     }
1222 }
1223
1224 int write_char(int c)
1225 {
1226     if (alarmed || put_char(c) < 0) {
1227         alarm(0);
1228         alarmed = 0;
1229
1230         if (verbose) {
1231             if (errno == EINTR || errno == EWOULDBLOCK)
1232                 msgf(" -- write timed out");
1233             else
1234                 msgf(" -- write failed: %m");
1235         }
1236         return (0);
1237     }
1238     return (1);
1239 }
1240
1241 int put_string(register char *s)
1242 {
1243     quiet = 0;
1244     s = clean(s, 1);
1245
1246     if (verbose) {
1247         if (quiet)
1248             msgf("send (?????\?)");
1249         else
1250             msgf("send (%v)", s);
1251     }
1252
1253     alarm(timeout); alarmed = 0;
1254
1255     while (*s) {
1256         register char c = *s++;
1257
1258         if (c != '\\') {
1259             if (!write_char (c))
1260                 return 0;
1261             continue;
1262         }
1263
1264         c = *s++;
1265         switch (c) {
1266         case 'd':
1267             sleep(1);
1268             break;
1269
1270         case 'K':
1271             break_sequence();
1272             break;
1273
1274         case 'p':
1275             usleep(10000);      /* 1/100th of a second (arg is microseconds) */
1276             break;
1277
1278         default:
1279             if (!write_char (c))
1280                 return 0;
1281             break;
1282         }
1283     }
1284
1285     alarm(0);
1286     alarmed = 0;
1287     return (1);
1288 }
1289
1290 /*
1291  *      Echo a character to stderr.
1292  *      When called with -1, a '\n' character is generated when
1293  *      the cursor is not at the beginning of a line.
1294  */
1295 void echo_stderr(int n)
1296 {
1297     static int need_lf;
1298     char *s;
1299
1300     switch (n) {
1301     case '\r':          /* ignore '\r' */
1302         break;
1303     case -1:
1304         if (need_lf == 0)
1305             break;
1306         /* fall through */
1307     case '\n':
1308         write(2, "\n", 1);
1309         need_lf = 0;
1310         break;
1311     default:
1312         s = character(n);
1313         write(2, s, strlen(s));
1314         need_lf = 1;
1315         break;
1316     }
1317 }
1318
1319 /*
1320  *      'Wait for' this string to appear on this file descriptor.
1321  */
1322 int get_string(register char *string)
1323 {
1324     char temp[STR_LEN];
1325     int c, printed = 0, len, minlen;
1326     register char *s = temp, *end = s + STR_LEN;
1327     char *logged = temp;
1328
1329     fail_reason = (char *)0;
1330     string = clean(string, 0);
1331     len = strlen(string);
1332     minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1333
1334     if (verbose)
1335         msgf("expect (%v)", string);
1336
1337     if (len > STR_LEN) {
1338         msgf("expect string is too long");
1339         exit_code = 1;
1340         return 0;
1341     }
1342
1343     if (len == 0) {
1344         if (verbose)
1345             msgf("got it");
1346         return (1);
1347     }
1348
1349     alarm(timeout);
1350     alarmed = 0;
1351
1352     while ( ! alarmed && (c = get_char()) >= 0) {
1353         int n, abort_len, report_len;
1354
1355         if (echo)
1356             echo_stderr(c);
1357         if (verbose && c == '\n') {
1358             if (s == logged)
1359                 msgf("");       /* blank line */
1360             else
1361                 msgf("%0.*v", s - logged, logged);
1362             logged = s + 1;
1363         }
1364
1365         *s++ = c;
1366
1367         if (verbose && s >= logged + 80) {
1368             msgf("%0.*v", s - logged, logged);
1369             logged = s;
1370         }
1371
1372         if (Verbose) {
1373            if (c == '\n')
1374                fputc( '\n', stderr );
1375            else if (c != '\r')
1376                fprintf( stderr, "%s", character(c) );
1377         }
1378
1379         if (!report_gathering) {
1380             for (n = 0; n < n_reports; ++n) {
1381                 if ((report_string[n] != (char*) NULL) &&
1382                     s - temp >= (report_len = strlen(report_string[n])) &&
1383                     strncmp(s - report_len, report_string[n], report_len) == 0) {
1384                     time_t time_now   = time ((time_t*) NULL);
1385                     struct tm* tm_now = localtime (&time_now);
1386
1387                     strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1388                     strcat (report_buffer, report_string[n]);
1389
1390                     report_string[n] = (char *) NULL;
1391                     report_gathering = 1;
1392                     break;
1393                 }
1394             }
1395         }
1396         else {
1397             if (!iscntrl (c)) {
1398                 int rep_len = strlen (report_buffer);
1399                 report_buffer[rep_len]     = c;
1400                 report_buffer[rep_len + 1] = '\0';
1401             }
1402             else {
1403                 report_gathering = 0;
1404                 fprintf (report_fp, "chat:  %s\n", report_buffer);
1405             }
1406         }
1407
1408         if (s - temp >= len &&
1409             c == string[len - 1] &&
1410             strncmp(s - len, string, len) == 0) {
1411             if (verbose) {
1412                 if (s > logged)
1413                     msgf("%0.*v", s - logged, logged);
1414                 msgf(" -- got it\n");
1415             }
1416
1417             alarm(0);
1418             alarmed = 0;
1419             return (1);
1420         }
1421
1422         for (n = 0; n < n_aborts; ++n) {
1423             if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1424                 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1425                 if (verbose) {
1426                     if (s > logged)
1427                         msgf("%0.*v", s - logged, logged);
1428                     msgf(" -- failed");
1429                 }
1430
1431                 alarm(0);
1432                 alarmed = 0;
1433                 exit_code = n + 4;
1434                 strcpy(fail_reason = fail_buffer, abort_string[n]);
1435                 return (0);
1436             }
1437         }
1438
1439         if (s >= end) {
1440             if (logged < s - minlen) {
1441                 if (verbose)
1442                     msgf("%0.*v", s - logged, logged);
1443                 logged = s;
1444             }
1445             s -= minlen;
1446             memmove(temp, s, minlen);
1447             logged = temp + (logged - s);
1448             s = temp + minlen;
1449         }
1450
1451         if (alarmed && verbose)
1452             msgf("warning: alarm synchronization problem");
1453     }
1454
1455     alarm(0);
1456     
1457     if (verbose && printed) {
1458         if (alarmed)
1459             msgf(" -- read timed out");
1460         else
1461             msgf(" -- read failed: %m");
1462     }
1463
1464     exit_code = 3;
1465     alarmed   = 0;
1466     return (0);
1467 }
1468
1469 /*
1470  * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1471  */
1472 #ifdef SOL2
1473 #include <sys/param.h>
1474 #if MAXUID > 65536              /* then this is Solaris 2.6 or later */
1475 #undef NO_USLEEP
1476 #endif
1477 #endif /* SOL2 */
1478
1479 #ifdef NO_USLEEP
1480 #include <sys/types.h>
1481 #include <sys/time.h>
1482
1483 /*
1484   usleep -- support routine for 4.2BSD system call emulations
1485   last edit:  29-Oct-1984     D A Gwyn
1486   */
1487
1488 extern int        select();
1489
1490 /* returns 0 if ok, else -1 */
1491 int usleep(long usec)           /* delay in microseconds */
1492 {
1493     static struct {             /* `timeval' */
1494         long    tv_sec;         /* seconds */
1495         long    tv_usec;        /* microsecs */
1496     } delay;                    /* _select() timeout */
1497
1498     delay.tv_sec  = usec / 1000000L;
1499     delay.tv_usec = usec % 1000000L;
1500
1501     return select(0, (long *)0, (long *)0, (long *)0, &delay);
1502 }
1503 #endif
1504
1505 void pack_array (
1506     char **array, /* The address of the array of string pointers */
1507     int end)      /* The index of the next free entry before CLR_ */
1508 {
1509     int i, j;
1510
1511     for (i = 0; i < end; i++) {
1512         if (array[i] == NULL) {
1513             for (j = i+1; j < end; ++j)
1514                 if (array[j] != NULL)
1515                     array[i++] = array[j];
1516             for (; i < end; ++i)
1517                 array[i] = NULL;
1518             break;
1519         }
1520     }
1521 }
1522
1523 /*
1524  * vfmtmsg - format a message into a buffer.  Like vsprintf except we
1525  * also specify the length of the output buffer, and we handle the
1526  * %m (error message) format.
1527  * Doesn't do floating-point formats.
1528  * Returns the number of chars put into buf.
1529  */
1530 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1531
1532 int
1533 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1534 {
1535     int c, i, n;
1536     int width, prec, fillch;
1537     int base, len, neg, quoted;
1538     unsigned long val = 0;
1539     char *str, *buf0;
1540     const char *f;
1541     unsigned char *p;
1542     char num[32];
1543     static char hexchars[] = "0123456789abcdef";
1544
1545     buf0 = buf;
1546     --buflen;
1547     while (buflen > 0) {
1548         for (f = fmt; *f != '%' && *f != 0; ++f)
1549             ;
1550         if (f > fmt) {
1551             len = f - fmt;
1552             if (len > buflen)
1553                 len = buflen;
1554             memcpy(buf, fmt, len);
1555             buf += len;
1556             buflen -= len;
1557             fmt = f;
1558         }
1559         if (*fmt == 0)
1560             break;
1561         c = *++fmt;
1562         width = prec = 0;
1563         fillch = ' ';
1564         if (c == '0') {
1565             fillch = '0';
1566             c = *++fmt;
1567         }
1568         if (c == '*') {
1569             width = va_arg(args, int);
1570             c = *++fmt;
1571         } else {
1572             while (isdigit(c)) {
1573                 width = width * 10 + c - '0';
1574                 c = *++fmt;
1575             }
1576         }
1577         if (c == '.') {
1578             c = *++fmt;
1579             if (c == '*') {
1580                 prec = va_arg(args, int);
1581                 c = *++fmt;
1582             } else {
1583                 while (isdigit(c)) {
1584                     prec = prec * 10 + c - '0';
1585                     c = *++fmt;
1586                 }
1587             }
1588         }
1589         str = 0;
1590         base = 0;
1591         neg = 0;
1592         ++fmt;
1593         switch (c) {
1594         case 'd':
1595             i = va_arg(args, int);
1596             if (i < 0) {
1597                 neg = 1;
1598                 val = -i;
1599             } else
1600                 val = i;
1601             base = 10;
1602             break;
1603         case 'o':
1604             val = va_arg(args, unsigned int);
1605             base = 8;
1606             break;
1607         case 'x':
1608             val = va_arg(args, unsigned int);
1609             base = 16;
1610             break;
1611         case 'p':
1612             val = (unsigned long) va_arg(args, void *);
1613             base = 16;
1614             neg = 2;
1615             break;
1616         case 's':
1617             str = va_arg(args, char *);
1618             break;
1619         case 'c':
1620             num[0] = va_arg(args, int);
1621             num[1] = 0;
1622             str = num;
1623             break;
1624         case 'm':
1625             str = strerror(errno);
1626             break;
1627         case 'v':               /* "visible" string */
1628         case 'q':               /* quoted string */
1629             quoted = c == 'q';
1630             p = va_arg(args, unsigned char *);
1631             if (fillch == '0' && prec > 0) {
1632                 n = prec;
1633             } else {
1634                 n = strlen((char *)p);
1635                 if (prec > 0 && prec < n)
1636                     n = prec;
1637             }
1638             while (n > 0 && buflen > 0) {
1639                 c = *p++;
1640                 --n;
1641                 if (!quoted && c >= 0x80) {
1642                     OUTCHAR('M');
1643                     OUTCHAR('-');
1644                     c -= 0x80;
1645                 }
1646                 if (quoted && (c == '"' || c == '\\'))
1647                     OUTCHAR('\\');
1648                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1649                     if (quoted) {
1650                         OUTCHAR('\\');
1651                         switch (c) {
1652                         case '\t':      OUTCHAR('t');   break;
1653                         case '\n':      OUTCHAR('n');   break;
1654                         case '\b':      OUTCHAR('b');   break;
1655                         case '\f':      OUTCHAR('f');   break;
1656                         default:
1657                             OUTCHAR('x');
1658                             OUTCHAR(hexchars[c >> 4]);
1659                             OUTCHAR(hexchars[c & 0xf]);
1660                         }
1661                     } else {
1662                         if (c == '\t')
1663                             OUTCHAR(c);
1664                         else {
1665                             OUTCHAR('^');
1666                             OUTCHAR(c ^ 0x40);
1667                         }
1668                     }
1669                 } else
1670                     OUTCHAR(c);
1671             }
1672             continue;
1673         default:
1674             *buf++ = '%';
1675             if (c != '%')
1676                 --fmt;          /* so %z outputs %z etc. */
1677             --buflen;
1678             continue;
1679         }
1680         if (base != 0) {
1681             str = num + sizeof(num);
1682             *--str = 0;
1683             while (str > num + neg) {
1684                 *--str = hexchars[val % base];
1685                 val = val / base;
1686                 if (--prec <= 0 && val == 0)
1687                     break;
1688             }
1689             switch (neg) {
1690             case 1:
1691                 *--str = '-';
1692                 break;
1693             case 2:
1694                 *--str = 'x';
1695                 *--str = '0';
1696                 break;
1697             }
1698             len = num + sizeof(num) - 1 - str;
1699         } else {
1700             len = strlen(str);
1701             if (prec > 0 && len > prec)
1702                 len = prec;
1703         }
1704         if (width > 0) {
1705             if (width > buflen)
1706                 width = buflen;
1707             if ((n = width - len) > 0) {
1708                 buflen -= n;
1709                 for (; n > 0; --n)
1710                     *buf++ = fillch;
1711             }
1712         }
1713         if (len > buflen)
1714             len = buflen;
1715         memcpy(buf, str, len);
1716         buf += len;
1717         buflen -= len;
1718     }
1719     *buf = 0;
1720     return buf - buf0;
1721 }