xref: /dragonfly/usr.bin/chat/chat.c (revision 3d33658b)
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  */
80 
81 #include <sys/types.h>
82 #include <sys/stat.h>
83 #include <ctype.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <signal.h>
87 #include <stdarg.h>
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <syslog.h>
92 #include <termios.h>
93 #include <time.h>
94 #include <unistd.h>
95 
96 #define	STR_LEN	1024
97 
98 #ifndef SIGTYPE
99 #define SIGTYPE void
100 #endif
101 
102 #ifndef O_NONBLOCK
103 #define O_NONBLOCK	O_NDELAY
104 #endif
105 
106 #define	MAX_ABORTS		50
107 #define	MAX_REPORTS		50
108 #define	DEFAULT_CHAT_TIMEOUT	45
109 
110 static int echo          = 0;
111 static int verbose       = 0;
112 static int to_log        = 1;
113 static int to_stderr     = 0;
114 static int Verbose       = 0;
115 static int quiet         = 0;
116 static int exit_code     = 0;
117 static FILE* report_fp   = NULL;
118 static char *report_file = NULL;
119 static char *chat_file   = NULL;
120 static char *phone_num   = NULL;
121 static char *phone_num2  = NULL;
122 static int timeout       = DEFAULT_CHAT_TIMEOUT;
123 
124 static char blank[] = "";
125 
126 static int have_tty_parameters = 0;
127 
128 #define term_parms struct termios
129 #define get_term_param(param) tcgetattr(0, param)
130 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
131 static struct termios saved_tty_parameters;
132 
133 static char *abort_string[MAX_ABORTS], *fail_reason = NULL,
134 	fail_buffer[50];
135 static int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
136 static int clear_abort_next = 0;
137 
138 static char *report_string[MAX_REPORTS] ;
139 static char  report_buffer[50] ;
140 static int n_reports = 0, report_next = 0, report_gathering = 0 ;
141 static int clear_report_next = 0;
142 
143 static int say_next = 0, hup_next = 0;
144 
145 static void *dup_mem(void *b, size_t c);
146 static void *copy_of(char *s);
147 static void usage(void);
148 static void chat_logf(const char *fmt, ...);
149 static void fatal(int code, const char *fmt, ...) __dead2;
150 static SIGTYPE sigalrm(int signo);
151 static SIGTYPE sigint(int signo) __dead2;
152 static SIGTYPE sigterm(int signo) __dead2;
153 static SIGTYPE sighup(int signo) __dead2;
154 static void init(void);
155 static void set_tty_parameters(void);
156 static void echo_stderr(int);
157 static void break_sequence(void);
158 static void terminate(int status) __dead2;
159 static void do_file(char *chatfile);
160 static int  get_string(char *string);
161 static int  put_string(char *s);
162 static int  write_char(int c);
163 static int  put_char(int c);
164 static int  get_char(void);
165 static void chat_send(char *s);
166 static char *character(int c);
167 static void chat_expect(char *s);
168 static char *clean(char *s, int sending);
169 static void pack_array(char **array, int end);
170 static char *expect_strtok(char *, const char *);
171 static int vfmtmsg(char *, int, const char *, va_list);	/* vsprintf++ */
172 
173 static void *
174 dup_mem(void *b, size_t c)
175 {
176     void *ans = malloc (c);
177     if (!ans)
178 	fatal(2, "memory error!");
179 
180     memcpy (ans, b, c);
181     return ans;
182 }
183 
184 static void *
185 copy_of(char *s)
186 {
187     return dup_mem (s, strlen (s) + 1);
188 }
189 
190 /*
191  * chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]
192  *      [-T phone-number] [-U phone-number2] [chat-script]
193  * where chat-script has the form:
194  *	[...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]
195  *
196  * Perform a UUCP-dialer-like chat script on stdin and stdout.
197  */
198 int
199 main(int argc, char *argv[])
200 {
201     int option;
202 
203     tzset();
204 
205     while ((option = getopt(argc, argv, "ef:r:sSt:T:U:vV")) != -1) {
206 	switch (option) {
207 	case 'e':
208 	    ++echo;
209 	    break;
210 
211 	case 'f':
212 	    if (chat_file != NULL)
213 		free(chat_file);
214 	    chat_file = copy_of(optarg);
215 	    break;
216 
217 	case 'r':
218 	    if (report_fp != NULL)
219 		fclose(report_fp);
220 	    if (report_file != NULL)
221 		free(report_file);
222 	    report_file = copy_of(optarg);
223 	    report_fp = fopen(report_file, "a");
224 	    if (report_fp != NULL) {
225 		if (verbose)
226 		    fprintf(report_fp, "Opening \"%s\"...\n", report_file);
227 	    } else
228 		fatal(2, "cannot open \"%s\" for appending", report_file);
229 	    break;
230 
231 	case 's':
232 	    ++to_stderr;
233 	    break;
234 
235 	case 'S':
236 	    to_log = 0;
237 	    break;
238 
239 	case 't':
240 	    timeout = atoi(optarg);
241 	    break;
242 
243 	case 'T':
244 	    if (phone_num != NULL)
245 		free(phone_num);
246 	    phone_num = copy_of(optarg);
247 	    break;
248 
249 	case 'U':
250 	    if (phone_num2 != NULL)
251 		free(phone_num2);
252 	    phone_num2 = copy_of(optarg);
253 	    break;
254 
255 	case 'v':
256 	    ++verbose;
257 	    break;
258 
259 	case 'V':
260 	    ++Verbose;
261 	    break;
262 
263 	default:
264 	    usage();
265 	    break;
266 	}
267     }
268 
269     argc -= optind;
270     argv += optind;
271 
272 /*
273  * Default the report file to the stderr location
274  */
275     if (report_fp == NULL)
276 	report_fp = stderr;
277 
278     if (to_log) {
279 	openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
280 
281 	if (verbose)
282 	    setlogmask(LOG_UPTO(LOG_INFO));
283 	else
284 	    setlogmask(LOG_UPTO(LOG_WARNING));
285     }
286 
287     if (chat_file != NULL) {
288 	if (*argv != NULL)
289 	    usage();
290 	else {
291             init();
292 	    do_file(chat_file);
293 	}
294     } else {
295 	init();
296 	while (*argv != NULL && argc > 0) {
297 	    chat_expect(*argv);
298 	    argv++;
299 	    argc--;
300 
301 	    if (*argv != NULL && argc > 0) {
302 		chat_send(*argv);
303 		argv++;
304 		argc--;
305 	    }
306 	}
307     }
308 
309     terminate(0);
310     return 0;
311 }
312 
313 /*
314  *  Process a chat script when read from a file.
315  */
316 
317 static void
318 do_file(char *chatfile)
319 {
320     int linect, sendflg;
321     char *sp, *arg, quote;
322     char buf [STR_LEN];
323     FILE *cfp;
324 
325     cfp = fopen (chatfile, "r");
326     if (cfp == NULL)
327 	fatal(1, "%s -- open failed: %m", chatfile);
328 
329     linect = 0;
330     sendflg = 0;
331 
332     while (fgets(buf, STR_LEN, cfp) != NULL) {
333 	sp = strchr (buf, '\n');
334 	if (sp)
335 	    *sp = '\0';
336 
337 	linect++;
338 	sp = buf;
339 
340         /* lines starting with '#' are comments. If a real '#'
341            is to be expected, it should be quoted .... */
342         if ( *sp == '#' )
343 	    continue;
344 
345 	while (*sp != '\0') {
346 	    if (*sp == ' ' || *sp == '\t') {
347 		++sp;
348 		continue;
349 	    }
350 
351 	    if (*sp == '"' || *sp == '\'') {
352 		quote = *sp++;
353 		arg = sp;
354 		while (*sp != quote) {
355 		    if (*sp == '\0')
356 			fatal(1, "unterminated quote (line %d)", linect);
357 
358 		    if (*sp++ == '\\') {
359 			if (*sp != '\0')
360 			    ++sp;
361 		    }
362 		}
363 	    }
364 	    else {
365 		arg = sp;
366 		while (*sp != '\0' && *sp != ' ' && *sp != '\t')
367 		    ++sp;
368 	    }
369 
370 	    if (*sp != '\0')
371 		*sp++ = '\0';
372 
373 	    if (sendflg)
374 		chat_send (arg);
375 	    else
376 		chat_expect (arg);
377 	    sendflg = !sendflg;
378 	}
379     }
380     fclose (cfp);
381 }
382 
383 /*
384  *	We got an error parsing the command line.
385  */
386 static void
387 usage(void)
388 {
389     fprintf(stderr,
390       "Usage: chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]\n"
391       "            [-T phone-number] [-U phone-number2] [chat-script]\n"
392       "where chat-script has the form:\n"
393       "            [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]\n");
394     exit(1);
395 }
396 
397 static char line[1024];
398 
399 /*
400  * Send a message to syslog and/or stderr.
401  */
402 static void
403 chat_logf(const char *fmt, ...)
404 {
405     va_list args;
406 
407     va_start(args, fmt);
408     vfmtmsg(line, sizeof(line), fmt, args);
409     if (to_log)
410 	syslog(LOG_INFO, "%s", line);
411     if (to_stderr)
412 	fprintf(stderr, "%s\n", line);
413 }
414 
415 /*
416  *	Print an error message and terminate.
417  */
418 
419 static void
420 fatal(int code, const char *fmt, ...)
421 {
422     va_list args;
423 
424     va_start(args, fmt);
425     vfmtmsg(line, sizeof(line), fmt, args);
426     if (to_log)
427 	syslog(LOG_ERR, "%s", line);
428     if (to_stderr)
429 	fprintf(stderr, "%s\n", line);
430     terminate(code);
431 }
432 
433 static int alarmed = 0;
434 
435 static SIGTYPE sigalrm(int signo __unused)
436 {
437     int flags;
438 
439     alarm(1);
440     alarmed = 1;		/* Reset alarm to avoid race window */
441     signal(SIGALRM, sigalrm);	/* that can cause hanging in read() */
442 
443     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
444 	fatal(2, "Can't get file mode flags on stdin: %m");
445 
446     if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
447 	fatal(2, "Can't set file mode flags on stdin: %m");
448 
449     if (verbose)
450 	chat_logf("alarm");
451 }
452 
453 static SIGTYPE sigint(int signo __unused)
454 {
455     fatal(2, "SIGINT");
456 }
457 
458 static SIGTYPE sigterm(int signo __unused)
459 {
460     fatal(2, "SIGTERM");
461 }
462 
463 static SIGTYPE sighup(int signo __unused)
464 {
465     fatal(2, "SIGHUP");
466 }
467 
468 static void init(void)
469 {
470     signal(SIGINT, sigint);
471     signal(SIGTERM, sigterm);
472     signal(SIGHUP, sighup);
473 
474     set_tty_parameters();
475     signal(SIGALRM, sigalrm);
476     alarm(0);
477     alarmed = 0;
478 }
479 
480 static void set_tty_parameters(void)
481 {
482 #if defined(get_term_param)
483     term_parms t;
484 
485     if (get_term_param (&t) < 0)
486 	fatal(2, "Can't get terminal parameters: %m");
487 
488     saved_tty_parameters = t;
489     have_tty_parameters  = 1;
490 
491     t.c_iflag     |= IGNBRK | ISTRIP | IGNPAR;
492     t.c_oflag      = 0;
493     t.c_lflag      = 0;
494     t.c_cc[VERASE] =
495     t.c_cc[VKILL]  = 0;
496     t.c_cc[VMIN]   = 1;
497     t.c_cc[VTIME]  = 0;
498 
499     if (set_term_param (&t) < 0)
500 	fatal(2, "Can't set terminal parameters: %m");
501 #endif
502 }
503 
504 static void break_sequence(void)
505 {
506     tcsendbreak (0, 0);
507 }
508 
509 static void terminate(int status)
510 {
511     echo_stderr(-1);
512     if (report_file != NULL && report_fp != NULL) {
513 /*
514  * Allow the last of the report string to be gathered before we terminate.
515  */
516 	if (report_gathering) {
517 	    int c;
518 	    size_t rep_len;
519 
520 	    rep_len = strlen(report_buffer);
521 	    while (rep_len + 1 <= sizeof(report_buffer)) {
522 		alarm(1);
523 		c = get_char();
524 		alarm(0);
525 		if (c < 0 || iscntrl(c))
526 		    break;
527 		report_buffer[rep_len] = c;
528 		++rep_len;
529 	    }
530 	    report_buffer[rep_len] = 0;
531 	    fprintf (report_fp, "chat:  %s\n", report_buffer);
532 	}
533 	if (verbose)
534 	    fprintf (report_fp, "Closing \"%s\".\n", report_file);
535 	fclose (report_fp);
536 	report_fp = NULL;
537     }
538 
539 #if defined(get_term_param)
540     if (have_tty_parameters) {
541 	if (set_term_param (&saved_tty_parameters) < 0)
542 	    fatal(2, "Can't restore terminal parameters: %m");
543     }
544 #endif
545 
546     exit(status);
547 }
548 
549 /*
550  *	'Clean up' this string.
551  */
552 static char *
553 clean(char *s, int sending)
554 {
555     char temp[STR_LEN], cur_chr;
556     char *s1, *phchar;
557     int add_return = sending;
558 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
559 
560     s1 = temp;
561     /* Don't overflow buffer, leave room for chars we append later */
562     while (*s && s1 - temp < (off_t)(sizeof(temp) - 2 - add_return)) {
563 	cur_chr = *s++;
564 	if (cur_chr == '^') {
565 	    cur_chr = *s++;
566 	    if (cur_chr == '\0') {
567 		*s1++ = '^';
568 		break;
569 	    }
570 	    cur_chr &= 0x1F;
571 	    if (cur_chr != 0) {
572 		*s1++ = cur_chr;
573 	    }
574 	    continue;
575 	}
576 
577 	if (cur_chr != '\\') {
578 	    *s1++ = cur_chr;
579 	    continue;
580 	}
581 
582 	cur_chr = *s++;
583 	if (cur_chr == '\0') {
584 	    if (sending) {
585 		*s1++ = '\\';
586 		*s1++ = '\\';
587 	    }
588 	    break;
589 	}
590 
591 	switch (cur_chr) {
592 	case 'b':
593 	    *s1++ = '\b';
594 	    break;
595 
596 	case 'c':
597 	    if (sending && *s == '\0')
598 		add_return = 0;
599 	    else
600 		*s1++ = cur_chr;
601 	    break;
602 
603 	case '\\':
604 	case 'K':
605 	case 'p':
606 	case 'd':
607 	    if (sending)
608 		*s1++ = '\\';
609 
610 	    *s1++ = cur_chr;
611 	    break;
612 
613 	case 'T':
614 	    if (sending && phone_num) {
615 		for ( phchar = phone_num; *phchar != '\0'; phchar++)
616 		    *s1++ = *phchar;
617 	    }
618 	    else {
619 		*s1++ = '\\';
620 		*s1++ = 'T';
621 	    }
622 	    break;
623 
624 	case 'U':
625 	    if (sending && phone_num2) {
626 		for ( phchar = phone_num2; *phchar != '\0'; phchar++)
627 		    *s1++ = *phchar;
628 	    }
629 	    else {
630 		*s1++ = '\\';
631 		*s1++ = 'U';
632 	    }
633 	    break;
634 
635 	case 'q':
636 	    quiet = 1;
637 	    break;
638 
639 	case 'r':
640 	    *s1++ = '\r';
641 	    break;
642 
643 	case 'n':
644 	    *s1++ = '\n';
645 	    break;
646 
647 	case 's':
648 	    *s1++ = ' ';
649 	    break;
650 
651 	case 't':
652 	    *s1++ = '\t';
653 	    break;
654 
655 	case 'N':
656 	    if (sending) {
657 		*s1++ = '\\';
658 		*s1++ = '\0';
659 	    }
660 	    else
661 		*s1++ = 'N';
662 	    break;
663 
664 	default:
665 	    if (isoctal (cur_chr)) {
666 		cur_chr &= 0x07;
667 		if (isoctal (*s)) {
668 		    cur_chr <<= 3;
669 		    cur_chr |= *s++ - '0';
670 		    if (isoctal (*s)) {
671 			cur_chr <<= 3;
672 			cur_chr |= *s++ - '0';
673 		    }
674 		}
675 
676 		if (cur_chr != 0 || sending) {
677 		    if (sending && (cur_chr == '\\' || cur_chr == 0))
678 			*s1++ = '\\';
679 		    *s1++ = cur_chr;
680 		}
681 		break;
682 	    }
683 
684 	    if (sending)
685 		*s1++ = '\\';
686 	    *s1++ = cur_chr;
687 	    break;
688 	}
689     }
690 
691     if (add_return)
692 	*s1++ = '\r';
693 
694     *s1++ = '\0'; /* guarantee closure */
695     *s1++ = '\0'; /* terminate the string */
696     return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
697 }
698 
699 /*
700  * A modified version of 'strtok'. This version skips \ sequences.
701  */
702 
703 static char *
704 expect_strtok (char *s, const char *term)
705 {
706     static  char *str   = blank;
707     int	    escape_flag = 0;
708     char   *result;
709 
710 /*
711  * If a string was specified then do initial processing.
712  */
713     if (s)
714 	str = s;
715 
716 /*
717  * If this is the escape flag then reset it and ignore the character.
718  */
719     if (*str)
720 	result = str;
721     else
722 	result = NULL;
723 
724     while (*str) {
725 	if (escape_flag) {
726 	    escape_flag = 0;
727 	    ++str;
728 	    continue;
729 	}
730 
731 	if (*str == '\\') {
732 	    ++str;
733 	    escape_flag = 1;
734 	    continue;
735 	}
736 
737 /*
738  * If this is not in the termination string, continue.
739  */
740 	if (strchr (term, *str) == NULL) {
741 	    ++str;
742 	    continue;
743 	}
744 
745 /*
746  * This is the terminator. Mark the end of the string and stop.
747  */
748 	*str++ = '\0';
749 	break;
750     }
751     return (result);
752 }
753 
754 /*
755  * Process the expect string
756  */
757 
758 static void
759 chat_expect(char *s)
760 {
761     char *expect;
762     char *reply;
763 
764     if (strcmp(s, "HANGUP") == 0) {
765 	++hup_next;
766         return;
767     }
768 
769     if (strcmp(s, "ABORT") == 0) {
770 	++abort_next;
771 	return;
772     }
773 
774     if (strcmp(s, "CLR_ABORT") == 0) {
775 	++clear_abort_next;
776 	return;
777     }
778 
779     if (strcmp(s, "REPORT") == 0) {
780 	++report_next;
781 	return;
782     }
783 
784     if (strcmp(s, "CLR_REPORT") == 0) {
785 	++clear_report_next;
786 	return;
787     }
788 
789     if (strcmp(s, "TIMEOUT") == 0) {
790 	++timeout_next;
791 	return;
792     }
793 
794     if (strcmp(s, "ECHO") == 0) {
795 	++echo_next;
796 	return;
797     }
798 
799     if (strcmp(s, "SAY") == 0) {
800 	++say_next;
801 	return;
802     }
803 
804 /*
805  * Fetch the expect and reply string.
806  */
807     for (;;) {
808 	expect = expect_strtok (s, "-");
809 	s      = NULL;
810 
811 	if (expect == NULL)
812 	    return;
813 
814 	reply = expect_strtok (s, "-");
815 
816 /*
817  * Handle the expect string. If successful then exit.
818  */
819 	if (get_string (expect))
820 	    return;
821 
822 /*
823  * If there is a sub-reply string then send it. Otherwise any condition
824  * is terminal.
825  */
826 	if (reply == NULL || exit_code != 3)
827 	    break;
828 
829 	chat_send (reply);
830     }
831 
832 /*
833  * The expectation did not occur. This is terminal.
834  */
835     if (fail_reason)
836 	chat_logf("Failed (%s)", fail_reason);
837     else
838 	chat_logf("Failed");
839     terminate(exit_code);
840 }
841 
842 /*
843  * Translate the input character to the appropriate string for printing
844  * the data.
845  */
846 
847 static char *
848 character(int c)
849 {
850     static char string[10];
851     const char *meta;
852 
853     meta = (c & 0x80) ? "M-" : "";
854     c &= 0x7F;
855 
856     if (c < 32)
857 	sprintf(string, "%s^%c", meta, (int)c + '@');
858     else if (c == 127)
859 	sprintf(string, "%s^?", meta);
860     else
861 	sprintf(string, "%s%c", meta, c);
862 
863     return (string);
864 }
865 
866 /*
867  *  process the reply string
868  */
869 static void
870 chat_send(char *s)
871 {
872     if (say_next) {
873 	say_next = 0;
874 	s = clean(s,0);
875 	write(STDERR_FILENO, s, strlen(s));
876         free(s);
877 	return;
878     }
879 
880     if (hup_next) {
881         hup_next = 0;
882 	if (strcmp(s, "OFF") == 0)
883            signal(SIGHUP, SIG_IGN);
884         else
885            signal(SIGHUP, sighup);
886         return;
887     }
888 
889     if (echo_next) {
890 	echo_next = 0;
891 	echo = (strcmp(s, "ON") == 0);
892 	return;
893     }
894 
895     if (abort_next) {
896 	char *s1;
897 
898 	abort_next = 0;
899 
900 	if (n_aborts >= MAX_ABORTS)
901 	    fatal(2, "Too many ABORT strings");
902 
903 	s1 = clean(s, 0);
904 
905 	if (strlen(s1) > strlen(s)
906 	    || strlen(s1) + 1 > sizeof(fail_buffer))
907 	    fatal(1, "Illegal or too-long ABORT string ('%v')", s);
908 
909 	abort_string[n_aborts++] = s1;
910 
911 	if (verbose)
912 	    chat_logf("abort on (%v)", s);
913 	return;
914     }
915 
916     if (clear_abort_next) {
917 	char *s1;
918 	int   i;
919         int   old_max;
920 	int   pack = 0;
921 
922 	clear_abort_next = 0;
923 
924 	s1 = clean(s, 0);
925 
926 	if (strlen(s1) > strlen(s)
927 	    || strlen(s1) + 1 > sizeof(fail_buffer))
928 	    fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
929 
930         old_max = n_aborts;
931 	for (i=0; i < n_aborts; i++) {
932 	    if ( strcmp(s1,abort_string[i]) == 0 ) {
933 		free(abort_string[i]);
934 		abort_string[i] = NULL;
935 		pack++;
936 		n_aborts--;
937 		if (verbose)
938 		    chat_logf("clear abort on (%v)", s);
939 	    }
940 	}
941         free(s1);
942 	if (pack)
943 	    pack_array(abort_string,old_max);
944 	return;
945     }
946 
947     if (report_next) {
948 	char *s1;
949 
950 	report_next = 0;
951 	if (n_reports >= MAX_REPORTS)
952 	    fatal(2, "Too many REPORT strings");
953 
954 	s1 = clean(s, 0);
955 
956 	if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
957 	    fatal(1, "Illegal or too-long REPORT string ('%v')", s);
958 
959 	report_string[n_reports++] = s1;
960 
961 	if (verbose)
962 	    chat_logf("report (%v)", s);
963 	return;
964     }
965 
966     if (clear_report_next) {
967 	char *s1;
968 	int   i;
969 	int   old_max;
970 	int   pack = 0;
971 
972 	clear_report_next = 0;
973 
974 	s1 = clean(s, 0);
975 
976 	if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
977 	    fatal(1, "Illegal or too-long REPORT string ('%v')", s);
978 
979 	old_max = n_reports;
980 	for (i=0; i < n_reports; i++) {
981 	    if ( strcmp(s1,report_string[i]) == 0 ) {
982 		free(report_string[i]);
983 		report_string[i] = NULL;
984 		pack++;
985 		n_reports--;
986 		if (verbose)
987 		    chat_logf("clear report (%v)", s);
988 	    }
989 	}
990         free(s1);
991         if (pack)
992 	    pack_array(report_string,old_max);
993 
994 	return;
995     }
996 
997     if (timeout_next) {
998 	timeout_next = 0;
999 	timeout = atoi(s);
1000 
1001 	if (timeout <= 0)
1002 	    timeout = DEFAULT_CHAT_TIMEOUT;
1003 
1004 	if (verbose)
1005 	    chat_logf("timeout set to %d seconds", timeout);
1006 
1007 	return;
1008     }
1009 
1010     if (strcmp(s, "EOT") == 0)
1011 	s = strdup("^D\\c");
1012     else if (strcmp(s, "BREAK") == 0)
1013 	s = strdup("\\K\\c");
1014 
1015     if (!put_string(s))
1016 	fatal(1, "Failed");
1017 }
1018 
1019 static int
1020 get_char(void)
1021 {
1022     int status;
1023     char c;
1024 
1025     status = read(STDIN_FILENO, &c, 1);
1026 
1027     switch (status) {
1028     case 1:
1029 	return ((int)c & 0x7F);
1030 
1031     default:
1032 	chat_logf("warning: read() on stdin returned %d", status);
1033 	/* FALLTHROUGH */
1034 
1035     case -1:
1036 	if ((status = fcntl(0, F_GETFL, 0)) == -1)
1037 	    fatal(2, "Can't get file mode flags on stdin: %m");
1038 
1039 	if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1040 	    fatal(2, "Can't set file mode flags on stdin: %m");
1041 
1042 	return (-1);
1043     }
1044 }
1045 
1046 static int put_char(int c)
1047 {
1048     int status;
1049     char ch = c;
1050 
1051     usleep(10000);		/* inter-character typing delay (?) */
1052 
1053     status = write(STDOUT_FILENO, &ch, 1);
1054 
1055     switch (status) {
1056     case 1:
1057 	return (0);
1058 
1059     default:
1060 	chat_logf("warning: write() on stdout returned %d", status);
1061 	/* FALLTHROUGH */
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 static 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 static 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 static 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 static 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 = NULL;
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] != 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 (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] = 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 static 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 static 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 = NULL;
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