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