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.
80 #include <sys/cdefs.h>
81 __FBSDID("$FreeBSD$");
83 #include <sys/types.h>
105 #define O_NONBLOCK O_NDELAY
108 #define MAX_ABORTS 50
109 #define MAX_REPORTS 50
110 #define DEFAULT_CHAT_TIMEOUT 45
115 static int to_stderr;
118 static int exit_code;
119 static FILE* report_fp;
120 static char *report_file;
121 static char *chat_file;
122 static char *phone_num;
123 static char *phone_num2;
124 static int timeout = DEFAULT_CHAT_TIMEOUT;
126 static char blank[] = "";
128 static int have_tty_parameters;
130 #define term_parms struct termios
131 #define get_term_param(param) tcgetattr(0, param)
132 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
133 static struct termios saved_tty_parameters;
135 static char *abort_string[MAX_ABORTS], *fail_reason, fail_buffer[50];
136 static int n_aborts, abort_next, timeout_next, echo_next;
137 static int clear_abort_next;
139 static char *report_string[MAX_REPORTS];
140 static char report_buffer[50];
141 static int n_reports, report_next, report_gathering;
142 static int clear_report_next;
144 static int say_next, hup_next;
146 void *dup_mem(void *b, size_t c);
147 void *copy_of(char *s);
148 static void usage(void);
149 void chat_logf(const char *fmt, ...);
150 void fatal(int code, const char *fmt, ...);
151 SIGTYPE sigalrm(int signo);
152 SIGTYPE sigint(int signo);
153 SIGTYPE sigterm(int signo);
154 SIGTYPE sighup(int signo);
156 void set_tty_parameters(void);
157 void echo_stderr(int);
158 void break_sequence(void);
159 void terminate(int status);
160 void do_file(char *chatfile);
161 int get_string(char *string);
162 int put_string(char *s);
163 int write_char(int c);
166 void chat_send(char *s);
167 char *character(int c);
168 void chat_expect(char *s);
169 char *clean(char *s, int sending);
170 void pack_array(char **array, int end);
171 char *expect_strtok(char *, const char *);
172 int vfmtmsg(char *, int, const char *, va_list); /* vsprintf++ */
175 dup_mem(void *b, size_t c)
177 void *ans = malloc (c);
179 fatal(2, "memory error!");
188 return dup_mem (s, strlen (s) + 1);
192 * chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]
193 * [-T phone-number] [-U phone-number2] [chat-script]
194 * where chat-script has the form:
195 * [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]
197 * Perform a UUCP-dialer-like chat script on stdin and stdout.
200 main(int argc, char *argv[])
206 while ((option = getopt(argc, argv, "ef:r:sSt:T:U:vV")) != -1) {
213 if (chat_file != NULL)
215 chat_file = copy_of(optarg);
219 if (report_fp != NULL)
221 if (report_file != NULL)
223 report_file = copy_of(optarg);
224 report_fp = fopen(report_file, "a");
225 if (report_fp != NULL) {
227 fprintf(report_fp, "Opening \"%s\"...\n", report_file);
229 fatal(2, "cannot open \"%s\" for appending", report_file);
241 timeout = atoi(optarg);
245 if (phone_num != NULL)
247 phone_num = copy_of(optarg);
251 if (phone_num2 != NULL)
253 phone_num2 = copy_of(optarg);
274 * Default the report file to the stderr location
276 if (report_fp == NULL)
280 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
283 setlogmask(LOG_UPTO(LOG_INFO));
285 setlogmask(LOG_UPTO(LOG_WARNING));
288 if (chat_file != NULL) {
297 while (*argv != NULL && argc > 0) {
302 if (*argv != NULL && argc > 0) {
315 * Process a chat script when read from a file.
319 do_file(char *chatfile)
322 char *sp, *arg, quote;
326 cfp = fopen (chatfile, "r");
328 fatal(1, "%s -- open failed: %m", chatfile);
333 while (fgets(buf, STR_LEN, cfp) != NULL) {
334 sp = strchr (buf, '\n');
341 /* lines starting with '#' are comments. If a real '#'
342 is to be expected, it should be quoted .... */
346 while (*sp != '\0') {
347 if (*sp == ' ' || *sp == '\t') {
352 if (*sp == '"' || *sp == '\'') {
355 while (*sp != quote) {
357 fatal(1, "unterminated quote (line %d)", linect);
367 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
385 * We got an error parsing the command line.
391 "Usage: chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]\n"
392 " [-T phone-number] [-U phone-number2] [chat-script]\n"
393 "where chat-script has the form:\n"
394 " [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]\n");
399 * Send a message to syslog and/or stderr.
402 chat_logf(const char *fmt, ...)
408 vfmtmsg(line, sizeof(line), fmt, args);
411 syslog(LOG_INFO, "%s", line);
413 fprintf(stderr, "%s\n", line);
417 * Print an error message and terminate.
421 fatal(int code, const char *fmt, ...)
427 vfmtmsg(line, sizeof(line), fmt, args);
430 syslog(LOG_ERR, "%s", line);
432 fprintf(stderr, "%s\n", line);
438 SIGTYPE sigalrm(int signo __unused)
443 alarmed = 1; /* Reset alarm to avoid race window */
444 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
446 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
447 fatal(2, "Can't get file mode flags on stdin: %m");
449 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
450 fatal(2, "Can't set file mode flags on stdin: %m");
456 SIGTYPE sigint(int signo __unused)
461 SIGTYPE sigterm(int signo __unused)
466 SIGTYPE sighup(int signo __unused)
473 signal(SIGINT, sigint);
474 signal(SIGTERM, sigterm);
475 signal(SIGHUP, sighup);
477 set_tty_parameters();
478 signal(SIGALRM, sigalrm);
483 void set_tty_parameters(void)
485 #if defined(get_term_param)
488 if (get_term_param (&t) < 0)
489 fatal(2, "Can't get terminal parameters: %m");
491 saved_tty_parameters = t;
492 have_tty_parameters = 1;
494 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
502 if (set_term_param (&t) < 0)
503 fatal(2, "Can't set terminal parameters: %m");
507 void break_sequence(void)
512 void terminate(int status)
515 if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
517 * Allow the last of the report string to be gathered before we terminate.
519 if (report_gathering) {
523 rep_len = strlen(report_buffer);
524 while (rep_len + 1 <= sizeof(report_buffer)) {
528 if (c < 0 || iscntrl(c))
530 report_buffer[rep_len] = c;
533 report_buffer[rep_len] = 0;
534 fprintf (report_fp, "chat: %s\n", report_buffer);
537 fprintf (report_fp, "Closing \"%s\".\n", report_file);
539 report_fp = (FILE *) NULL;
542 #if defined(get_term_param)
543 if (have_tty_parameters) {
544 if (set_term_param (&saved_tty_parameters) < 0)
545 fatal(2, "Can't restore terminal parameters: %m");
553 * 'Clean up' this string.
556 clean(char *s, int sending)
558 char temp[STR_LEN], cur_chr;
560 int add_return = sending;
561 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
564 /* Don't overflow buffer, leave room for chars we append later */
565 while (*s && s1 - temp < (off_t)(sizeof(temp) - 2 - add_return)) {
567 if (cur_chr == '^') {
569 if (cur_chr == '\0') {
580 if (cur_chr != '\\') {
586 if (cur_chr == '\0') {
600 if (sending && *s == '\0')
617 if (sending && phone_num) {
618 for ( phchar = phone_num; *phchar != '\0'; phchar++)
628 if (sending && phone_num2) {
629 for ( phchar = phone_num2; *phchar != '\0'; phchar++)
668 if (isoctal (cur_chr)) {
672 cur_chr |= *s++ - '0';
675 cur_chr |= *s++ - '0';
679 if (cur_chr != 0 || sending) {
680 if (sending && (cur_chr == '\\' || cur_chr == 0))
697 *s1++ = '\0'; /* guarantee closure */
698 *s1++ = '\0'; /* terminate the string */
699 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
703 * A modified version of 'strtok'. This version skips \ sequences.
707 expect_strtok (char *s, const char *term)
709 static char *str = blank;
714 * If a string was specified then do initial processing.
720 * If this is the escape flag then reset it and ignore the character.
741 * If this is not in the termination string, continue.
743 if (strchr (term, *str) == (char *) 0) {
749 * This is the terminator. Mark the end of the string and stop.
758 * Process the expect string
767 if (strcmp(s, "HANGUP") == 0) {
772 if (strcmp(s, "ABORT") == 0) {
777 if (strcmp(s, "CLR_ABORT") == 0) {
782 if (strcmp(s, "REPORT") == 0) {
787 if (strcmp(s, "CLR_REPORT") == 0) {
792 if (strcmp(s, "TIMEOUT") == 0) {
797 if (strcmp(s, "ECHO") == 0) {
802 if (strcmp(s, "SAY") == 0) {
808 * Fetch the expect and reply string.
811 expect = expect_strtok (s, "-");
814 if (expect == (char *) 0)
817 reply = expect_strtok (s, "-");
820 * Handle the expect string. If successful then exit.
822 if (get_string (expect))
826 * If there is a sub-reply string then send it. Otherwise any condition
829 if (reply == (char *) 0 || exit_code != 3)
836 * The expectation did not occur. This is terminal.
839 chat_logf("Failed (%s)", fail_reason);
842 terminate(exit_code);
846 * Translate the input character to the appropriate string for printing
853 static char string[10];
856 meta = (c & 0x80) ? "M-" : "";
860 sprintf(string, "%s^%c", meta, (int)c + '@');
862 sprintf(string, "%s^?", meta);
864 sprintf(string, "%s%c", meta, c);
870 * process the reply string
878 write(STDERR_FILENO, s, strlen(s));
885 if (strcmp(s, "OFF") == 0)
886 signal(SIGHUP, SIG_IGN);
888 signal(SIGHUP, sighup);
894 echo = (strcmp(s, "ON") == 0);
903 if (n_aborts >= MAX_ABORTS)
904 fatal(2, "Too many ABORT strings");
908 if (strlen(s1) > strlen(s)
909 || strlen(s1) + 1 > sizeof(fail_buffer))
910 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
912 abort_string[n_aborts++] = s1;
915 chat_logf("abort on (%v)", s);
919 if (clear_abort_next) {
925 clear_abort_next = 0;
929 if (strlen(s1) > strlen(s)
930 || strlen(s1) + 1 > sizeof(fail_buffer))
931 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
934 for (i=0; i < n_aborts; i++) {
935 if ( strcmp(s1,abort_string[i]) == 0 ) {
936 free(abort_string[i]);
937 abort_string[i] = NULL;
941 chat_logf("clear abort on (%v)", s);
946 pack_array(abort_string,old_max);
954 if (n_reports >= MAX_REPORTS)
955 fatal(2, "Too many REPORT strings");
959 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
960 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
962 report_string[n_reports++] = s1;
965 chat_logf("report (%v)", s);
969 if (clear_report_next) {
975 clear_report_next = 0;
979 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
980 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
983 for (i=0; i < n_reports; i++) {
984 if ( strcmp(s1,report_string[i]) == 0 ) {
985 free(report_string[i]);
986 report_string[i] = NULL;
990 chat_logf("clear report (%v)", s);
995 pack_array(report_string,old_max);
1005 timeout = DEFAULT_CHAT_TIMEOUT;
1008 chat_logf("timeout set to %d seconds", timeout);
1013 if (strcmp(s, "EOT") == 0)
1014 s = strdup("^D\\c");
1015 else if (strcmp(s, "BREAK") == 0)
1016 s = strdup("\\K\\c");
1028 status = read(STDIN_FILENO, &c, 1);
1032 return ((int)c & 0x7F);
1035 chat_logf("warning: read() on stdin returned %d", status);
1038 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1039 fatal(2, "Can't get file mode flags on stdin: %m");
1041 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1042 fatal(2, "Can't set file mode flags on stdin: %m");
1053 usleep(10000); /* inter-character typing delay (?) */
1055 status = write(STDOUT_FILENO, &ch, 1);
1062 chat_logf("warning: write() on stdout returned %d", status);
1065 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1066 fatal(2, "Can't get file mode flags on stdin, %m");
1068 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1069 fatal(2, "Can't set file mode flags on stdin: %m");
1078 if (alarmed || put_char(c) < 0) {
1083 if (errno == EINTR || errno == EWOULDBLOCK)
1084 chat_logf(" -- write timed out");
1086 chat_logf(" -- write failed: %m");
1100 chat_logf("send (%v)", quiet ? "??????" : s);
1102 alarm(timeout); alarmed = 0;
1108 if (!write_char (c))
1124 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1128 if (!write_char (c))
1140 * Echo a character to stderr.
1141 * When called with -1, a '\n' character is generated when
1142 * the cursor is not at the beginning of a line.
1151 case '\r': /* ignore '\r' */
1158 write(STDERR_FILENO, "\n", 1);
1163 write(STDERR_FILENO, s, strlen(s));
1170 * 'Wait for' this string to appear on this file descriptor.
1173 get_string(char *string)
1178 char *s = temp, *end = s + STR_LEN;
1179 char *logged = temp;
1181 fail_reason = (char *)0;
1183 if (strlen(string) > STR_LEN) {
1184 chat_logf("expect string is too long");
1189 string = clean(string, 0);
1190 len = strlen(string);
1191 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1194 chat_logf("expect (%v)", string);
1198 chat_logf("got it");
1205 while ( ! alarmed && (c = get_char()) >= 0) {
1206 int n, abort_len, report_len;
1210 if (verbose && c == '\n') {
1212 chat_logf(""); /* blank line */
1214 chat_logf("%0.*v", s - logged, logged);
1220 if (verbose && s >= logged + 80) {
1221 chat_logf("%0.*v", s - logged, logged);
1227 fputc( '\n', stderr );
1229 fprintf( stderr, "%s", character(c) );
1232 if (!report_gathering) {
1233 for (n = 0; n < n_reports; ++n) {
1234 if ((report_string[n] != (char*) NULL) &&
1235 s - temp >= (report_len = strlen(report_string[n])) &&
1236 strncmp(s - report_len, report_string[n], report_len) == 0) {
1237 time_t time_now = time ((time_t*) NULL);
1238 struct tm* tm_now = localtime (&time_now);
1240 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1241 strcat (report_buffer, report_string[n]);
1243 report_string[n] = (char *) NULL;
1244 report_gathering = 1;
1251 int rep_len = strlen (report_buffer);
1252 report_buffer[rep_len] = c;
1253 report_buffer[rep_len + 1] = '\0';
1256 report_gathering = 0;
1257 fprintf (report_fp, "chat: %s\n", report_buffer);
1261 if ((size_t)(s - temp) >= len &&
1262 c == string[len - 1] &&
1263 strncmp(s - len, string, len) == 0) {
1266 chat_logf("%0.*v", s - logged, logged);
1267 chat_logf(" -- got it\n");
1275 for (n = 0; n < n_aborts; ++n) {
1276 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1277 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1280 chat_logf("%0.*v", s - logged, logged);
1281 chat_logf(" -- failed");
1287 strcpy(fail_reason = fail_buffer, abort_string[n]);
1293 if (logged < s - minlen) {
1294 chat_logf("%0.*v", s - logged, logged);
1298 memmove(temp, s, minlen);
1299 logged = temp + (logged - s);
1303 if (alarmed && verbose)
1304 chat_logf("warning: alarm synchronization problem");
1309 if (verbose && printed) {
1311 chat_logf(" -- read timed out");
1313 chat_logf(" -- read failed: %m");
1322 pack_array(char **array, int end)
1326 for (i = 0; i < end; i++) {
1327 if (array[i] == NULL) {
1328 for (j = i+1; j < end; ++j)
1329 if (array[j] != NULL)
1330 array[i++] = array[j];
1331 for (; i < end; ++i)
1339 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1340 * also specify the length of the output buffer, and we handle the
1341 * %m (error message) format.
1342 * Doesn't do floating-point formats.
1343 * Returns the number of chars put into buf.
1345 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1348 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1351 int width, prec, fillch;
1352 int base, len, neg, quoted;
1353 unsigned long val = 0;
1358 static char hexchars[] = "0123456789abcdef";
1362 while (buflen > 0) {
1363 for (f = fmt; *f != '%' && *f != 0; ++f)
1369 memcpy(buf, fmt, len);
1384 width = va_arg(args, int);
1387 while (isdigit(c)) {
1388 width = width * 10 + c - '0';
1395 prec = va_arg(args, int);
1398 while (isdigit(c)) {
1399 prec = prec * 10 + c - '0';
1410 i = va_arg(args, int);
1419 val = va_arg(args, unsigned int);
1423 val = va_arg(args, unsigned int);
1427 val = (unsigned long) va_arg(args, void *);
1432 str = va_arg(args, char *);
1435 num[0] = va_arg(args, int);
1440 str = strerror(errno);
1442 case 'v': /* "visible" string */
1443 case 'q': /* quoted string */
1445 p = va_arg(args, unsigned char *);
1446 if (fillch == '0' && prec > 0) {
1449 n = strlen((char *)p);
1450 if (prec > 0 && prec < n)
1453 while (n > 0 && buflen > 0) {
1456 if (!quoted && c >= 0x80) {
1461 if (quoted && (c == '"' || c == '\\'))
1463 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1467 case '\t': OUTCHAR('t'); break;
1468 case '\n': OUTCHAR('n'); break;
1469 case '\b': OUTCHAR('b'); break;
1470 case '\f': OUTCHAR('f'); break;
1473 OUTCHAR(hexchars[c >> 4]);
1474 OUTCHAR(hexchars[c & 0xf]);
1491 --fmt; /* so %z outputs %z etc. */
1496 str = num + sizeof(num);
1498 while (str > num + neg) {
1499 *--str = hexchars[val % base];
1501 if (--prec <= 0 && val == 0)
1513 len = num + sizeof(num) - 1 - str;
1516 if (prec > 0 && len > prec)
1522 if ((n = width - len) > 0) {
1530 memcpy(buf, str, len);