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