2 * Chat -- a program for automatic session establishment (i.e. dial
3 * the phone and log in).
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.
14 * This software is in the public domain.
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>
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).
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.
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.
41 * In the same vein as above, added CLR_REPORT keyword.
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.
48 * Francis Demierre <Francis@SwissMail.Com>
49 * Thu May 15 17:15:40 MET DST 1997
52 * Added -r "report file" switch & REPORT keyword.
53 * Robert Geer <bgeer@xmission.com>
55 * Added -s "use stderr" and -S "don't use syslog" switches.
57 * Karl O. Pinc <kop@meme.com>
60 * Added -e "echo" switch & ECHO keyword
61 * Dick Streefland <dicks@tasking.nl>
64 * Considerable updates and modifications by
65 * Al Longyear <longyear@pobox.com>
66 * Paul Mackerras <paulus@cs.anu.edu.au>
69 * The original author is:
71 * Karl Fox <karl@MorningStar.Com>
72 * Morning Star Technologies, Inc.
78 * $FreeBSD: src/usr.bin/chat/chat.c,v 1.21 2003/10/31 06:22:03 kientzle Exp $
79 * $DragonFly: src/usr.bin/chat/chat.c,v 1.10 2004/12/31 23:30:27 cpressey Exp $
82 #include <sys/cdefs.h>
83 #include <sys/types.h>
105 #define O_NONBLOCK O_NDELAY
108 /*************** Micro getopt() *********************************************/
109 #define OPTION(c,v) (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
110 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
111 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
112 #define OPTARG(c,v) (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
113 (_O=4,(char*)0):(char*)0)
114 #define ARG(c,v) (c?(--c,*v++):(char*)0)
116 static int _O = 0; /* Internal state */
117 /*************** Micro getopt() *********************************************/
119 #define MAX_ABORTS 50
120 #define MAX_REPORTS 50
121 #define DEFAULT_CHAT_TIMEOUT 45
130 FILE* report_fp = (FILE *) 0;
131 char *report_file = (char *) 0;
132 char *chat_file = (char *) 0;
133 char *phone_num = (char *) 0;
134 char *phone_num2 = (char *) 0;
135 int timeout = DEFAULT_CHAT_TIMEOUT;
137 static char blank[] = "";
139 int have_tty_parameters = 0;
141 #define term_parms struct termios
142 #define get_term_param(param) tcgetattr(0, param)
143 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
144 struct termios saved_tty_parameters;
146 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
148 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
149 int clear_abort_next = 0;
151 char *report_string[MAX_REPORTS] ;
152 char report_buffer[50] ;
153 int n_reports = 0, report_next = 0, report_gathering = 0 ;
154 int clear_report_next = 0;
156 int say_next = 0, hup_next = 0;
158 void *dup_mem(void *b, size_t c);
159 void *copy_of(char *s);
160 static void usage(void);
161 void chat_logf(const char *fmt, ...);
162 void fatal(int code, const char *fmt, ...);
163 SIGTYPE sigalrm(int signo);
164 SIGTYPE sigint(int signo);
165 SIGTYPE sigterm(int signo);
166 SIGTYPE sighup(int signo);
168 void set_tty_parameters(void);
169 void echo_stderr(int);
170 void break_sequence(void);
171 void terminate(int status);
172 void do_file(char *chatfile);
173 int get_string(char *string);
174 int put_string(char *s);
175 int write_char(int c);
178 void chat_send(char *s);
179 char *character(int c);
180 void chat_expect(char *s);
181 char *clean(char *s, int sending);
182 void pack_array(char **array, int end);
183 char *expect_strtok(char *, const char *);
184 int vfmtmsg(char *, int, const char *, va_list); /* vsprintf++ */
187 dup_mem(void *b, size_t c)
189 void *ans = malloc (c);
191 fatal(2, "memory error!");
200 return dup_mem (s, strlen (s) + 1);
204 * chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]
205 * [-T phone-number] [-U phone-number2] [chat-script]
206 * where chat-script has the form:
207 * [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]
209 * Perform a UUCP-dialer-like chat script on stdin and stdout.
212 main(int argc, char *argv[])
219 while ((option = OPTION(argc, argv)) != 0) {
242 if ((arg = OPTARG(argc, argv)) != NULL)
243 chat_file = copy_of(arg);
249 if ((arg = OPTARG(argc, argv)) != NULL)
256 arg = OPTARG (argc, argv);
258 if (report_fp != NULL)
260 report_file = copy_of (arg);
261 report_fp = fopen (report_file, "a");
262 if (report_fp != NULL) {
264 fprintf (report_fp, "Opening \"%s\"...\n",
271 if ((arg = OPTARG(argc, argv)) != NULL)
272 phone_num = copy_of(arg);
278 if ((arg = OPTARG(argc, argv)) != NULL)
279 phone_num2 = copy_of(arg);
290 * Default the report file to the stderr location
292 if (report_fp == NULL)
296 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
299 setlogmask(LOG_UPTO(LOG_INFO));
301 setlogmask(LOG_UPTO(LOG_WARNING));
306 if (chat_file != NULL) {
307 arg = ARG(argc, argv);
313 while ((arg = ARG(argc, argv)) != NULL) {
316 if ((arg = ARG(argc, argv)) != NULL)
326 * Process a chat script when read from a file.
330 do_file(char *chatfile)
333 char *sp, *arg, quote;
337 cfp = fopen (chatfile, "r");
339 fatal(1, "%s -- open failed: %m", chatfile);
344 while (fgets(buf, STR_LEN, cfp) != NULL) {
345 sp = strchr (buf, '\n');
352 /* lines starting with '#' are comments. If a real '#'
353 is to be expected, it should be quoted .... */
357 while (*sp != '\0') {
358 if (*sp == ' ' || *sp == '\t') {
363 if (*sp == '"' || *sp == '\'') {
366 while (*sp != quote) {
368 fatal(1, "unterminated quote (line %d)", linect);
378 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
396 * We got an error parsing the command line.
402 "Usage: chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]\n"
403 " [-T phone-number] [-U phone-number2] [chat-script]\n"
404 "where chat-script has the form:\n"
405 " [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]\n");
412 * Send a message to syslog and/or stderr.
415 chat_logf(const char *fmt, ...)
420 vfmtmsg(line, sizeof(line), fmt, args);
422 syslog(LOG_INFO, "%s", line);
424 fprintf(stderr, "%s\n", line);
428 * Print an error message and terminate.
432 fatal(int code, const char *fmt, ...)
437 vfmtmsg(line, sizeof(line), fmt, args);
439 syslog(LOG_ERR, "%s", line);
441 fprintf(stderr, "%s\n", line);
447 SIGTYPE sigalrm(int signo __unused)
452 alarmed = 1; /* Reset alarm to avoid race window */
453 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
455 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
456 fatal(2, "Can't get file mode flags on stdin: %m");
458 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
459 fatal(2, "Can't set file mode flags on stdin: %m");
465 SIGTYPE sigint(int signo __unused)
470 SIGTYPE sigterm(int signo __unused)
475 SIGTYPE sighup(int signo __unused)
482 signal(SIGINT, sigint);
483 signal(SIGTERM, sigterm);
484 signal(SIGHUP, sighup);
486 set_tty_parameters();
487 signal(SIGALRM, sigalrm);
492 void set_tty_parameters(void)
494 #if defined(get_term_param)
497 if (get_term_param (&t) < 0)
498 fatal(2, "Can't get terminal parameters: %m");
500 saved_tty_parameters = t;
501 have_tty_parameters = 1;
503 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
511 if (set_term_param (&t) < 0)
512 fatal(2, "Can't set terminal parameters: %m");
516 void break_sequence(void)
521 void terminate(int status)
524 if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
526 * Allow the last of the report string to be gathered before we terminate.
528 if (report_gathering) {
532 rep_len = strlen(report_buffer);
533 while (rep_len + 1 <= sizeof(report_buffer)) {
537 if (c < 0 || iscntrl(c))
539 report_buffer[rep_len] = c;
542 report_buffer[rep_len] = 0;
543 fprintf (report_fp, "chat: %s\n", report_buffer);
546 fprintf (report_fp, "Closing \"%s\".\n", report_file);
548 report_fp = (FILE *) NULL;
551 #if defined(get_term_param)
552 if (have_tty_parameters) {
553 if (set_term_param (&saved_tty_parameters) < 0)
554 fatal(2, "Can't restore terminal parameters: %m");
562 * 'Clean up' this string.
565 clean(char *s, int sending)
567 char temp[STR_LEN], cur_chr;
569 int add_return = sending;
570 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
573 /* Don't overflow buffer, leave room for chars we append later */
574 while (*s && s1 - temp < (off_t)(sizeof(temp) - 2 - add_return)) {
576 if (cur_chr == '^') {
578 if (cur_chr == '\0') {
589 if (cur_chr != '\\') {
595 if (cur_chr == '\0') {
609 if (sending && *s == '\0')
626 if (sending && phone_num) {
627 for ( phchar = phone_num; *phchar != '\0'; phchar++)
637 if (sending && phone_num2) {
638 for ( phchar = phone_num2; *phchar != '\0'; phchar++)
677 if (isoctal (cur_chr)) {
681 cur_chr |= *s++ - '0';
684 cur_chr |= *s++ - '0';
688 if (cur_chr != 0 || sending) {
689 if (sending && (cur_chr == '\\' || cur_chr == 0))
706 *s1++ = '\0'; /* guarantee closure */
707 *s1++ = '\0'; /* terminate the string */
708 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
712 * A modified version of 'strtok'. This version skips \ sequences.
716 expect_strtok (char *s, const char *term)
718 static char *str = blank;
723 * If a string was specified then do initial processing.
729 * If this is the escape flag then reset it and ignore the character.
750 * If this is not in the termination string, continue.
752 if (strchr (term, *str) == (char *) 0) {
758 * This is the terminator. Mark the end of the string and stop.
767 * Process the expect string
776 if (strcmp(s, "HANGUP") == 0) {
781 if (strcmp(s, "ABORT") == 0) {
786 if (strcmp(s, "CLR_ABORT") == 0) {
791 if (strcmp(s, "REPORT") == 0) {
796 if (strcmp(s, "CLR_REPORT") == 0) {
801 if (strcmp(s, "TIMEOUT") == 0) {
806 if (strcmp(s, "ECHO") == 0) {
811 if (strcmp(s, "SAY") == 0) {
817 * Fetch the expect and reply string.
820 expect = expect_strtok (s, "-");
823 if (expect == (char *) 0)
826 reply = expect_strtok (s, "-");
829 * Handle the expect string. If successful then exit.
831 if (get_string (expect))
835 * If there is a sub-reply string then send it. Otherwise any condition
838 if (reply == (char *) 0 || exit_code != 3)
845 * The expectation did not occur. This is terminal.
848 chat_logf("Failed (%s)", fail_reason);
851 terminate(exit_code);
855 * Translate the input character to the appropriate string for printing
862 static char string[10];
865 meta = (c & 0x80) ? "M-" : "";
869 sprintf(string, "%s^%c", meta, (int)c + '@');
871 sprintf(string, "%s^?", meta);
873 sprintf(string, "%s%c", meta, c);
879 * process the reply string
887 write(STDERR_FILENO, s, strlen(s));
894 if (strcmp(s, "OFF") == 0)
895 signal(SIGHUP, SIG_IGN);
897 signal(SIGHUP, sighup);
903 echo = (strcmp(s, "ON") == 0);
912 if (n_aborts >= MAX_ABORTS)
913 fatal(2, "Too many ABORT strings");
917 if (strlen(s1) > strlen(s)
918 || strlen(s1) + 1 > sizeof(fail_buffer))
919 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
921 abort_string[n_aborts++] = s1;
924 chat_logf("abort on (%v)", s);
928 if (clear_abort_next) {
934 clear_abort_next = 0;
938 if (strlen(s1) > strlen(s)
939 || strlen(s1) + 1 > sizeof(fail_buffer))
940 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
943 for (i=0; i < n_aborts; i++) {
944 if ( strcmp(s1,abort_string[i]) == 0 ) {
945 free(abort_string[i]);
946 abort_string[i] = NULL;
950 chat_logf("clear abort on (%v)", s);
955 pack_array(abort_string,old_max);
963 if (n_reports >= MAX_REPORTS)
964 fatal(2, "Too many REPORT strings");
968 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
969 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
971 report_string[n_reports++] = s1;
974 chat_logf("report (%v)", s);
978 if (clear_report_next) {
984 clear_report_next = 0;
988 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
989 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
992 for (i=0; i < n_reports; i++) {
993 if ( strcmp(s1,report_string[i]) == 0 ) {
994 free(report_string[i]);
995 report_string[i] = NULL;
999 chat_logf("clear report (%v)", s);
1004 pack_array(report_string,old_max);
1014 timeout = DEFAULT_CHAT_TIMEOUT;
1017 chat_logf("timeout set to %d seconds", timeout);
1022 if (strcmp(s, "EOT") == 0)
1023 s = strdup("^D\\c");
1024 else if (strcmp(s, "BREAK") == 0)
1025 s = strdup("\\K\\c");
1037 status = read(STDIN_FILENO, &c, 1);
1041 return ((int)c & 0x7F);
1044 chat_logf("warning: read() on stdin returned %d", status);
1047 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1048 fatal(2, "Can't get file mode flags on stdin: %m");
1050 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1051 fatal(2, "Can't set file mode flags on stdin: %m");
1062 usleep(10000); /* inter-character typing delay (?) */
1064 status = write(STDOUT_FILENO, &ch, 1);
1071 chat_logf("warning: write() on stdout returned %d", status);
1074 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1075 fatal(2, "Can't get file mode flags on stdin, %m");
1077 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1078 fatal(2, "Can't set file mode flags on stdin: %m");
1087 if (alarmed || put_char(c) < 0) {
1092 if (errno == EINTR || errno == EWOULDBLOCK)
1093 chat_logf(" -- write timed out");
1095 chat_logf(" -- write failed: %m");
1109 chat_logf("send (%v)", quiet ? "??????" : s);
1111 alarm(timeout); alarmed = 0;
1117 if (!write_char (c))
1133 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1137 if (!write_char (c))
1149 * Echo a character to stderr.
1150 * When called with -1, a '\n' character is generated when
1151 * the cursor is not at the beginning of a line.
1160 case '\r': /* ignore '\r' */
1167 write(STDERR_FILENO, "\n", 1);
1172 write(STDERR_FILENO, s, strlen(s));
1179 * 'Wait for' this string to appear on this file descriptor.
1182 get_string(char *string)
1187 char *s = temp, *end = s + STR_LEN;
1188 char *logged = temp;
1190 fail_reason = (char *)0;
1192 if (strlen(string) > STR_LEN) {
1193 chat_logf("expect string is too long");
1198 string = clean(string, 0);
1199 len = strlen(string);
1200 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1203 chat_logf("expect (%v)", string);
1207 chat_logf("got it");
1214 while ( ! alarmed && (c = get_char()) >= 0) {
1215 int n, abort_len, report_len;
1219 if (verbose && c == '\n') {
1221 chat_logf(""); /* blank line */
1223 chat_logf("%0.*v", s - logged, logged);
1229 if (verbose && s >= logged + 80) {
1230 chat_logf("%0.*v", s - logged, logged);
1236 fputc( '\n', stderr );
1238 fprintf( stderr, "%s", character(c) );
1241 if (!report_gathering) {
1242 for (n = 0; n < n_reports; ++n) {
1243 if ((report_string[n] != (char*) NULL) &&
1244 s - temp >= (report_len = strlen(report_string[n])) &&
1245 strncmp(s - report_len, report_string[n], report_len) == 0) {
1246 time_t time_now = time ((time_t*) NULL);
1247 struct tm* tm_now = localtime (&time_now);
1249 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1250 strcat (report_buffer, report_string[n]);
1252 report_string[n] = (char *) NULL;
1253 report_gathering = 1;
1260 int rep_len = strlen (report_buffer);
1261 report_buffer[rep_len] = c;
1262 report_buffer[rep_len + 1] = '\0';
1265 report_gathering = 0;
1266 fprintf (report_fp, "chat: %s\n", report_buffer);
1270 if ((size_t)(s - temp) >= len &&
1271 c == string[len - 1] &&
1272 strncmp(s - len, string, len) == 0) {
1275 chat_logf("%0.*v", s - logged, logged);
1276 chat_logf(" -- got it\n");
1284 for (n = 0; n < n_aborts; ++n) {
1285 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1286 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1289 chat_logf("%0.*v", s - logged, logged);
1290 chat_logf(" -- failed");
1296 strcpy(fail_reason = fail_buffer, abort_string[n]);
1302 if (logged < s - minlen) {
1303 chat_logf("%0.*v", s - logged, logged);
1307 memmove(temp, s, minlen);
1308 logged = temp + (logged - s);
1312 if (alarmed && verbose)
1313 chat_logf("warning: alarm synchronization problem");
1318 if (verbose && printed) {
1320 chat_logf(" -- read timed out");
1322 chat_logf(" -- read failed: %m");
1331 pack_array(char **array, int end)
1335 for (i = 0; i < end; i++) {
1336 if (array[i] == NULL) {
1337 for (j = i+1; j < end; ++j)
1338 if (array[j] != NULL)
1339 array[i++] = array[j];
1340 for (; i < end; ++i)
1348 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1349 * also specify the length of the output buffer, and we handle the
1350 * %m (error message) format.
1351 * Doesn't do floating-point formats.
1352 * Returns the number of chars put into buf.
1354 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1357 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1360 int width, prec, fillch;
1361 int base, len, neg, quoted;
1362 unsigned long val = 0;
1367 static char hexchars[] = "0123456789abcdef";
1371 while (buflen > 0) {
1372 for (f = fmt; *f != '%' && *f != 0; ++f)
1378 memcpy(buf, fmt, len);
1393 width = va_arg(args, int);
1396 while (isdigit(c)) {
1397 width = width * 10 + c - '0';
1404 prec = va_arg(args, int);
1407 while (isdigit(c)) {
1408 prec = prec * 10 + c - '0';
1419 i = va_arg(args, int);
1428 val = va_arg(args, unsigned int);
1432 val = va_arg(args, unsigned int);
1436 val = (unsigned long) va_arg(args, void *);
1441 str = va_arg(args, char *);
1444 num[0] = va_arg(args, int);
1449 str = strerror(errno);
1451 case 'v': /* "visible" string */
1452 case 'q': /* quoted string */
1454 p = va_arg(args, unsigned char *);
1455 if (fillch == '0' && prec > 0) {
1458 n = strlen((char *)p);
1459 if (prec > 0 && prec < n)
1462 while (n > 0 && buflen > 0) {
1465 if (!quoted && c >= 0x80) {
1470 if (quoted && (c == '"' || c == '\\'))
1472 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1476 case '\t': OUTCHAR('t'); break;
1477 case '\n': OUTCHAR('n'); break;
1478 case '\b': OUTCHAR('b'); break;
1479 case '\f': OUTCHAR('f'); break;
1482 OUTCHAR(hexchars[c >> 4]);
1483 OUTCHAR(hexchars[c & 0xf]);
1500 --fmt; /* so %z outputs %z etc. */
1505 str = num + sizeof(num);
1507 while (str > num + neg) {
1508 *--str = hexchars[val % base];
1510 if (--prec <= 0 && val == 0)
1522 len = num + sizeof(num) - 1 - str;
1525 if (prec > 0 && len > prec)
1531 if ((n = width - len) > 0) {
1539 memcpy(buf, str, len);