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