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 #include <sys/types.h>
103 #define O_NONBLOCK O_NDELAY
106 #define MAX_ABORTS 50
107 #define MAX_REPORTS 50
108 #define DEFAULT_CHAT_TIMEOUT 45
113 static int to_stderr;
116 static int exit_code;
117 static FILE* report_fp;
118 static char *report_file;
119 static char *chat_file;
120 static char *phone_num;
121 static char *phone_num2;
122 static int timeout = DEFAULT_CHAT_TIMEOUT;
124 static char blank[] = "";
126 static int have_tty_parameters;
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;
133 static char *abort_string[MAX_ABORTS], *fail_reason, fail_buffer[50];
134 static int n_aborts, abort_next, timeout_next, echo_next;
135 static int clear_abort_next;
137 static char *report_string[MAX_REPORTS];
138 static char report_buffer[50];
139 static int n_reports, report_next, report_gathering;
140 static int clear_report_next;
142 static int say_next, hup_next;
144 void *dup_mem(void *b, size_t c);
145 void *copy_of(char *s);
146 static void usage(void) __dead2;
147 void chat_logf(const char *fmt, ...);
148 void fatal(int code, const char *fmt, ...);
149 SIGTYPE sigalrm(int signo);
150 SIGTYPE sigint(int signo);
151 SIGTYPE sigterm(int signo);
152 SIGTYPE sighup(int signo);
154 void set_tty_parameters(void);
155 void echo_stderr(int);
156 void break_sequence(void);
157 void terminate(int status);
158 void do_file(char *chatfile);
159 int get_string(char *string);
160 int put_string(char *s);
161 int write_char(int c);
164 void chat_send(char *s);
165 char *character(int c);
166 void chat_expect(char *s);
167 char *clean(char *s, int sending);
168 void pack_array(char **array, int end);
169 char *expect_strtok(char *, const char *);
170 int vfmtmsg(char *, int, const char *, va_list); /* vsprintf++ */
173 dup_mem(void *b, size_t c)
175 void *ans = malloc (c);
177 fatal(2, "memory error!");
186 return dup_mem (s, strlen (s) + 1);
190 * chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]
191 * [-T phone-number] [-U phone-number2] [chat-script]
192 * where chat-script has the form:
193 * [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]
195 * Perform a UUCP-dialer-like chat script on stdin and stdout.
198 main(int argc, char *argv[])
204 while ((option = getopt(argc, argv, "ef:r:sSt:T:U:vV")) != -1) {
211 if (chat_file != NULL)
213 chat_file = copy_of(optarg);
217 if (report_fp != NULL)
219 if (report_file != NULL)
221 report_file = copy_of(optarg);
222 report_fp = fopen(report_file, "a");
223 if (report_fp != NULL) {
225 fprintf(report_fp, "Opening \"%s\"...\n", report_file);
227 fatal(2, "cannot open \"%s\" for appending", report_file);
239 timeout = atoi(optarg);
243 if (phone_num != NULL)
245 phone_num = copy_of(optarg);
249 if (phone_num2 != NULL)
251 phone_num2 = copy_of(optarg);
272 * Default the report file to the stderr location
274 if (report_fp == NULL)
278 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
281 setlogmask(LOG_UPTO(LOG_INFO));
283 setlogmask(LOG_UPTO(LOG_WARNING));
286 if (chat_file != NULL) {
295 while (*argv != NULL && argc > 0) {
300 if (*argv != NULL && argc > 0) {
313 * Process a chat script when read from a file.
317 do_file(char *chatfile)
320 char *sp, *arg, quote;
324 cfp = fopen (chatfile, "r");
326 fatal(1, "%s -- open failed: %m", chatfile);
331 while (fgets(buf, STR_LEN, cfp) != NULL) {
332 sp = strchr (buf, '\n');
339 /* lines starting with '#' are comments. If a real '#'
340 is to be expected, it should be quoted .... */
344 while (*sp != '\0') {
345 if (*sp == ' ' || *sp == '\t') {
350 if (*sp == '"' || *sp == '\'') {
353 while (*sp != quote) {
355 fatal(1, "unterminated quote (line %d)", linect);
365 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
383 * We got an error parsing the command line.
389 "Usage: chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]\n"
390 " [-T phone-number] [-U phone-number2] [chat-script]\n"
391 "where chat-script has the form:\n"
392 " [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]\n");
397 * Send a message to syslog and/or stderr.
400 chat_logf(const char *fmt, ...)
406 vfmtmsg(line, sizeof(line), fmt, args);
409 syslog(LOG_INFO, "%s", line);
411 fprintf(stderr, "%s\n", line);
415 * Print an error message and terminate.
419 fatal(int code, const char *fmt, ...)
425 vfmtmsg(line, sizeof(line), fmt, args);
428 syslog(LOG_ERR, "%s", line);
430 fprintf(stderr, "%s\n", line);
436 SIGTYPE sigalrm(int signo __unused)
441 alarmed = 1; /* Reset alarm to avoid race window */
442 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
444 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
445 fatal(2, "Can't get file mode flags on stdin: %m");
447 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
448 fatal(2, "Can't set file mode flags on stdin: %m");
454 SIGTYPE sigint(int signo __unused)
459 SIGTYPE sigterm(int signo __unused)
464 SIGTYPE sighup(int signo __unused)
471 signal(SIGINT, sigint);
472 signal(SIGTERM, sigterm);
473 signal(SIGHUP, sighup);
475 set_tty_parameters();
476 signal(SIGALRM, sigalrm);
481 void set_tty_parameters(void)
483 #if defined(get_term_param)
486 if (get_term_param (&t) < 0)
487 fatal(2, "Can't get terminal parameters: %m");
489 saved_tty_parameters = t;
490 have_tty_parameters = 1;
492 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
500 if (set_term_param (&t) < 0)
501 fatal(2, "Can't set terminal parameters: %m");
505 void break_sequence(void)
510 void terminate(int status)
513 if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
515 * Allow the last of the report string to be gathered before we terminate.
517 if (report_gathering) {
521 rep_len = strlen(report_buffer);
522 while (rep_len + 1 < sizeof(report_buffer)) {
526 if (c < 0 || iscntrl(c))
528 report_buffer[rep_len] = c;
531 report_buffer[rep_len] = 0;
532 fprintf (report_fp, "chat: %s\n", report_buffer);
535 fprintf (report_fp, "Closing \"%s\".\n", report_file);
537 report_fp = (FILE *) NULL;
540 #if defined(get_term_param)
541 if (have_tty_parameters) {
542 if (set_term_param (&saved_tty_parameters) < 0)
543 fatal(2, "Can't restore terminal parameters: %m");
551 * 'Clean up' this string.
554 clean(char *s, int sending)
556 char temp[STR_LEN], cur_chr;
558 int add_return = sending;
559 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
562 /* Don't overflow buffer, leave room for chars we append later */
563 while (*s && s1 - temp < (off_t)(sizeof(temp) - 2 - add_return)) {
565 if (cur_chr == '^') {
567 if (cur_chr == '\0') {
578 if (cur_chr != '\\') {
584 if (cur_chr == '\0') {
598 if (sending && *s == '\0')
615 if (sending && phone_num) {
616 for ( phchar = phone_num; *phchar != '\0'; phchar++)
626 if (sending && phone_num2) {
627 for ( phchar = phone_num2; *phchar != '\0'; phchar++)
666 if (isoctal (cur_chr)) {
670 cur_chr |= *s++ - '0';
673 cur_chr |= *s++ - '0';
677 if (cur_chr != 0 || sending) {
678 if (sending && (cur_chr == '\\' || cur_chr == 0))
695 *s1++ = '\0'; /* guarantee closure */
696 *s1++ = '\0'; /* terminate the string */
697 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
701 * A modified version of 'strtok'. This version skips \ sequences.
705 expect_strtok (char *s, const char *term)
707 static char *str = blank;
712 * If a string was specified then do initial processing.
718 * If this is the escape flag then reset it and ignore the character.
739 * If this is not in the termination string, continue.
741 if (strchr (term, *str) == (char *) 0) {
747 * This is the terminator. Mark the end of the string and stop.
756 * Process the expect string
765 if (strcmp(s, "HANGUP") == 0) {
770 if (strcmp(s, "ABORT") == 0) {
775 if (strcmp(s, "CLR_ABORT") == 0) {
780 if (strcmp(s, "REPORT") == 0) {
785 if (strcmp(s, "CLR_REPORT") == 0) {
790 if (strcmp(s, "TIMEOUT") == 0) {
795 if (strcmp(s, "ECHO") == 0) {
800 if (strcmp(s, "SAY") == 0) {
806 * Fetch the expect and reply string.
809 expect = expect_strtok (s, "-");
812 if (expect == (char *) 0)
815 reply = expect_strtok (s, "-");
818 * Handle the expect string. If successful then exit.
820 if (get_string (expect))
824 * If there is a sub-reply string then send it. Otherwise any condition
827 if (reply == (char *) 0 || exit_code != 3)
834 * The expectation did not occur. This is terminal.
837 chat_logf("Failed (%s)", fail_reason);
840 terminate(exit_code);
844 * Translate the input character to the appropriate string for printing
851 static char string[10];
854 meta = (c & 0x80) ? "M-" : "";
858 sprintf(string, "%s^%c", meta, (int)c + '@');
860 sprintf(string, "%s^?", meta);
862 sprintf(string, "%s%c", meta, c);
868 * process the reply string
876 write(STDERR_FILENO, s, strlen(s));
883 if (strcmp(s, "OFF") == 0)
884 signal(SIGHUP, SIG_IGN);
886 signal(SIGHUP, sighup);
892 echo = (strcmp(s, "ON") == 0);
901 if (n_aborts >= MAX_ABORTS)
902 fatal(2, "Too many ABORT strings");
906 if (strlen(s1) > strlen(s)
907 || strlen(s1) + 1 > sizeof(fail_buffer))
908 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
910 abort_string[n_aborts++] = s1;
913 chat_logf("abort on (%v)", s);
917 if (clear_abort_next) {
923 clear_abort_next = 0;
927 if (strlen(s1) > strlen(s)
928 || strlen(s1) + 1 > sizeof(fail_buffer))
929 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
932 for (i=0; i < n_aborts; i++) {
933 if ( strcmp(s1,abort_string[i]) == 0 ) {
934 free(abort_string[i]);
935 abort_string[i] = NULL;
939 chat_logf("clear abort on (%v)", s);
944 pack_array(abort_string,old_max);
952 if (n_reports >= MAX_REPORTS)
953 fatal(2, "Too many REPORT strings");
957 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
958 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
960 report_string[n_reports++] = s1;
963 chat_logf("report (%v)", s);
967 if (clear_report_next) {
973 clear_report_next = 0;
977 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
978 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
981 for (i=0; i < n_reports; i++) {
982 if ( strcmp(s1,report_string[i]) == 0 ) {
983 free(report_string[i]);
984 report_string[i] = NULL;
988 chat_logf("clear report (%v)", s);
993 pack_array(report_string,old_max);
1003 timeout = DEFAULT_CHAT_TIMEOUT;
1006 chat_logf("timeout set to %d seconds", timeout);
1011 if (strcmp(s, "EOT") == 0)
1012 s = strdup("^D\\c");
1013 else if (strcmp(s, "BREAK") == 0)
1014 s = strdup("\\K\\c");
1026 status = read(STDIN_FILENO, &c, 1);
1030 return ((int)c & 0x7F);
1033 chat_logf("warning: read() on stdin returned %d", status);
1036 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1037 fatal(2, "Can't get file mode flags on stdin: %m");
1039 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1040 fatal(2, "Can't set file mode flags on stdin: %m");
1051 usleep(10000); /* inter-character typing delay (?) */
1053 status = write(STDOUT_FILENO, &ch, 1);
1060 chat_logf("warning: write() on stdout returned %d", status);
1063 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1064 fatal(2, "Can't get file mode flags on stdin, %m");
1066 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1067 fatal(2, "Can't set file mode flags on stdin: %m");
1076 if (alarmed || put_char(c) < 0) {
1081 if (errno == EINTR || errno == EWOULDBLOCK)
1082 chat_logf(" -- write timed out");
1084 chat_logf(" -- write failed: %m");
1098 chat_logf("send (%v)", quiet ? "??????" : s);
1100 alarm(timeout); alarmed = 0;
1106 if (!write_char (c))
1122 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1126 if (!write_char (c))
1138 * Echo a character to stderr.
1139 * When called with -1, a '\n' character is generated when
1140 * the cursor is not at the beginning of a line.
1149 case '\r': /* ignore '\r' */
1156 write(STDERR_FILENO, "\n", 1);
1161 write(STDERR_FILENO, s, strlen(s));
1168 * 'Wait for' this string to appear on this file descriptor.
1171 get_string(char *string)
1176 char *s = temp, *end = s + STR_LEN;
1177 char *logged = temp;
1179 fail_reason = (char *)0;
1181 if (strlen(string) > STR_LEN) {
1182 chat_logf("expect string is too long");
1187 string = clean(string, 0);
1188 len = strlen(string);
1189 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1192 chat_logf("expect (%v)", string);
1196 chat_logf("got it");
1203 while ( ! alarmed && (c = get_char()) >= 0) {
1204 int n, abort_len, report_len;
1208 if (verbose && c == '\n') {
1210 chat_logf(""); /* blank line */
1212 chat_logf("%0.*v", s - logged, logged);
1218 if (verbose && s >= logged + 80) {
1219 chat_logf("%0.*v", s - logged, logged);
1225 fputc( '\n', stderr );
1227 fprintf( stderr, "%s", character(c) );
1230 if (!report_gathering) {
1231 for (n = 0; n < n_reports; ++n) {
1232 if ((report_string[n] != (char*) NULL) &&
1233 s - temp >= (report_len = strlen(report_string[n])) &&
1234 strncmp(s - report_len, report_string[n], report_len) == 0) {
1235 time_t time_now = time ((time_t*) NULL);
1236 struct tm* tm_now = localtime (&time_now);
1238 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1239 strcat (report_buffer, report_string[n]);
1241 report_string[n] = (char *) NULL;
1242 report_gathering = 1;
1249 int rep_len = strlen (report_buffer);
1250 report_buffer[rep_len] = c;
1251 report_buffer[rep_len + 1] = '\0';
1254 report_gathering = 0;
1255 fprintf (report_fp, "chat: %s\n", report_buffer);
1259 if ((size_t)(s - temp) >= len &&
1260 c == string[len - 1] &&
1261 strncmp(s - len, string, len) == 0) {
1264 chat_logf("%0.*v", s - logged, logged);
1265 chat_logf(" -- got it\n");
1273 for (n = 0; n < n_aborts; ++n) {
1274 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1275 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1278 chat_logf("%0.*v", s - logged, logged);
1279 chat_logf(" -- failed");
1285 strcpy(fail_reason = fail_buffer, abort_string[n]);
1291 if (logged < s - minlen) {
1292 chat_logf("%0.*v", s - logged, logged);
1296 memmove(temp, s, minlen);
1297 logged = temp + (logged - s);
1301 if (alarmed && verbose)
1302 chat_logf("warning: alarm synchronization problem");
1313 pack_array(char **array, int end)
1317 for (i = 0; i < end; i++) {
1318 if (array[i] == NULL) {
1319 for (j = i+1; j < end; ++j)
1320 if (array[j] != NULL)
1321 array[i++] = array[j];
1322 for (; i < end; ++i)
1330 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1331 * also specify the length of the output buffer, and we handle the
1332 * %m (error message) format.
1333 * Doesn't do floating-point formats.
1334 * Returns the number of chars put into buf.
1336 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1339 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1342 int width, prec, fillch;
1343 int base, len, neg, quoted;
1344 unsigned long val = 0;
1349 static char hexchars[] = "0123456789abcdef";
1353 while (buflen > 0) {
1354 for (f = fmt; *f != '%' && *f != 0; ++f)
1360 memcpy(buf, fmt, len);
1375 width = va_arg(args, int);
1378 while (isdigit(c)) {
1379 width = width * 10 + c - '0';
1386 prec = va_arg(args, int);
1389 while (isdigit(c)) {
1390 prec = prec * 10 + c - '0';
1401 i = va_arg(args, int);
1410 val = va_arg(args, unsigned int);
1414 val = va_arg(args, unsigned int);
1418 val = (unsigned long) va_arg(args, void *);
1423 str = va_arg(args, char *);
1426 num[0] = va_arg(args, int);
1431 str = strerror(errno);
1433 case 'v': /* "visible" string */
1434 case 'q': /* quoted string */
1436 p = va_arg(args, unsigned char *);
1437 if (fillch == '0' && prec > 0) {
1440 n = strlen((char *)p);
1441 if (prec > 0 && prec < n)
1444 while (n > 0 && buflen > 0) {
1447 if (!quoted && c >= 0x80) {
1452 if (quoted && (c == '"' || c == '\\'))
1454 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1458 case '\t': OUTCHAR('t'); break;
1459 case '\n': OUTCHAR('n'); break;
1460 case '\b': OUTCHAR('b'); break;
1461 case '\f': OUTCHAR('f'); break;
1464 OUTCHAR(hexchars[c >> 4]);
1465 OUTCHAR(hexchars[c & 0xf]);
1482 --fmt; /* so %z outputs %z etc. */
1487 str = num + sizeof(num);
1489 while (str > num + neg) {
1490 *--str = hexchars[val % base];
1492 if (--prec <= 0 && val == 0)
1504 len = num + sizeof(num) - 1 - str;
1507 if (prec > 0 && len > prec)
1513 if ((n = width - len) > 0) {
1521 memcpy(buf, str, len);