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 /*************** 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 [ -v ] [-T number] [-U number] [ -t timeout ] [ -f chat-file ] \
205 * [ -r report-file ] \
206 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
208 * Perform a UUCP-dialer-like chat script on stdin and stdout.
211 main(int argc, char *argv[])
218 while ((option = OPTION(argc, argv)) != 0) {
241 if ((arg = OPTARG(argc, argv)) != NULL)
242 chat_file = copy_of(arg);
248 if ((arg = OPTARG(argc, argv)) != NULL)
255 arg = OPTARG (argc, argv);
257 if (report_fp != NULL)
259 report_file = copy_of (arg);
260 report_fp = fopen (report_file, "a");
261 if (report_fp != NULL) {
263 fprintf (report_fp, "Opening \"%s\"...\n",
270 if ((arg = OPTARG(argc, argv)) != NULL)
271 phone_num = copy_of(arg);
277 if ((arg = OPTARG(argc, argv)) != NULL)
278 phone_num2 = copy_of(arg);
289 * Default the report file to the stderr location
291 if (report_fp == NULL)
295 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
298 setlogmask(LOG_UPTO(LOG_INFO));
300 setlogmask(LOG_UPTO(LOG_WARNING));
305 if (chat_file != NULL) {
306 arg = ARG(argc, argv);
312 while ((arg = ARG(argc, argv)) != NULL) {
315 if ((arg = ARG(argc, argv)) != NULL)
325 * Process a chat script when read from a file.
329 do_file(char *chatfile)
332 char *sp, *arg, quote;
336 cfp = fopen (chatfile, "r");
338 fatal(1, "%s -- open failed: %m", chatfile);
343 while (fgets(buf, STR_LEN, cfp) != NULL) {
344 sp = strchr (buf, '\n');
351 /* lines starting with '#' are comments. If a real '#'
352 is to be expected, it should be quoted .... */
356 while (*sp != '\0') {
357 if (*sp == ' ' || *sp == '\t') {
362 if (*sp == '"' || *sp == '\'') {
365 while (*sp != quote) {
367 fatal(1, "unterminated quote (line %d)", linect);
377 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
395 * We got an error parsing the command line.
401 Usage: chat [-e] [-v] [-V] [-t timeout] [-r report-file] [-T phone-number]\n\
402 [-U phone-number2] {-f chat-file | chat-script}\n");
409 * Send a message to syslog and/or stderr.
412 chat_logf(const char *fmt, ...)
417 vfmtmsg(line, sizeof(line), fmt, args);
419 syslog(LOG_INFO, "%s", line);
421 fprintf(stderr, "%s\n", line);
425 * Print an error message and terminate.
429 fatal(int code, const char *fmt, ...)
434 vfmtmsg(line, sizeof(line), fmt, args);
436 syslog(LOG_ERR, "%s", line);
438 fprintf(stderr, "%s\n", line);
444 SIGTYPE sigalrm(int signo __unused)
449 alarmed = 1; /* Reset alarm to avoid race window */
450 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
452 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
453 fatal(2, "Can't get file mode flags on stdin: %m");
455 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
456 fatal(2, "Can't set file mode flags on stdin: %m");
462 SIGTYPE sigint(int signo __unused)
467 SIGTYPE sigterm(int signo __unused)
472 SIGTYPE sighup(int signo __unused)
479 signal(SIGINT, sigint);
480 signal(SIGTERM, sigterm);
481 signal(SIGHUP, sighup);
483 set_tty_parameters();
484 signal(SIGALRM, sigalrm);
489 void set_tty_parameters(void)
491 #if defined(get_term_param)
494 if (get_term_param (&t) < 0)
495 fatal(2, "Can't get terminal parameters: %m");
497 saved_tty_parameters = t;
498 have_tty_parameters = 1;
500 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
508 if (set_term_param (&t) < 0)
509 fatal(2, "Can't set terminal parameters: %m");
513 void break_sequence(void)
518 void terminate(int status)
521 if (report_file != (char *) 0 && report_fp != (FILE *) NULL) {
523 * Allow the last of the report string to be gathered before we terminate.
525 if (report_gathering) {
529 rep_len = strlen(report_buffer);
530 while (rep_len + 1 <= sizeof(report_buffer)) {
534 if (c < 0 || iscntrl(c))
536 report_buffer[rep_len] = c;
539 report_buffer[rep_len] = 0;
540 fprintf (report_fp, "chat: %s\n", report_buffer);
543 fprintf (report_fp, "Closing \"%s\".\n", report_file);
545 report_fp = (FILE *) NULL;
548 #if defined(get_term_param)
549 if (have_tty_parameters) {
550 if (set_term_param (&saved_tty_parameters) < 0)
551 fatal(2, "Can't restore terminal parameters: %m");
559 * 'Clean up' this string.
562 clean(char *s, int sending)
564 char temp[STR_LEN], cur_chr;
566 int add_return = sending;
567 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
570 /* Don't overflow buffer, leave room for chars we append later */
571 while (*s && s1 - temp < (off_t)(sizeof(temp) - 2 - add_return)) {
573 if (cur_chr == '^') {
575 if (cur_chr == '\0') {
586 if (cur_chr != '\\') {
592 if (cur_chr == '\0') {
606 if (sending && *s == '\0')
623 if (sending && phone_num) {
624 for ( phchar = phone_num; *phchar != '\0'; phchar++)
634 if (sending && phone_num2) {
635 for ( phchar = phone_num2; *phchar != '\0'; phchar++)
674 if (isoctal (cur_chr)) {
678 cur_chr |= *s++ - '0';
681 cur_chr |= *s++ - '0';
685 if (cur_chr != 0 || sending) {
686 if (sending && (cur_chr == '\\' || cur_chr == 0))
703 *s1++ = '\0'; /* guarantee closure */
704 *s1++ = '\0'; /* terminate the string */
705 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
709 * A modified version of 'strtok'. This version skips \ sequences.
713 expect_strtok (char *s, const char *term)
715 static char *str = blank;
720 * If a string was specified then do initial processing.
726 * If this is the escape flag then reset it and ignore the character.
747 * If this is not in the termination string, continue.
749 if (strchr (term, *str) == (char *) 0) {
755 * This is the terminator. Mark the end of the string and stop.
764 * Process the expect string
773 if (strcmp(s, "HANGUP") == 0) {
778 if (strcmp(s, "ABORT") == 0) {
783 if (strcmp(s, "CLR_ABORT") == 0) {
788 if (strcmp(s, "REPORT") == 0) {
793 if (strcmp(s, "CLR_REPORT") == 0) {
798 if (strcmp(s, "TIMEOUT") == 0) {
803 if (strcmp(s, "ECHO") == 0) {
808 if (strcmp(s, "SAY") == 0) {
814 * Fetch the expect and reply string.
817 expect = expect_strtok (s, "-");
820 if (expect == (char *) 0)
823 reply = expect_strtok (s, "-");
826 * Handle the expect string. If successful then exit.
828 if (get_string (expect))
832 * If there is a sub-reply string then send it. Otherwise any condition
835 if (reply == (char *) 0 || exit_code != 3)
842 * The expectation did not occur. This is terminal.
845 chat_logf("Failed (%s)", fail_reason);
848 terminate(exit_code);
852 * Translate the input character to the appropriate string for printing
859 static char string[10];
862 meta = (c & 0x80) ? "M-" : "";
866 sprintf(string, "%s^%c", meta, (int)c + '@');
868 sprintf(string, "%s^?", meta);
870 sprintf(string, "%s%c", meta, c);
876 * process the reply string
884 write(STDERR_FILENO, s, strlen(s));
891 if (strcmp(s, "OFF") == 0)
892 signal(SIGHUP, SIG_IGN);
894 signal(SIGHUP, sighup);
900 echo = (strcmp(s, "ON") == 0);
909 if (n_aborts >= MAX_ABORTS)
910 fatal(2, "Too many ABORT strings");
914 if (strlen(s1) > strlen(s)
915 || strlen(s1) + 1 > sizeof(fail_buffer))
916 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
918 abort_string[n_aborts++] = s1;
921 chat_logf("abort on (%v)", s);
925 if (clear_abort_next) {
931 clear_abort_next = 0;
935 if (strlen(s1) > strlen(s)
936 || strlen(s1) + 1 > sizeof(fail_buffer))
937 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
940 for (i=0; i < n_aborts; i++) {
941 if ( strcmp(s1,abort_string[i]) == 0 ) {
942 free(abort_string[i]);
943 abort_string[i] = NULL;
947 chat_logf("clear abort on (%v)", s);
952 pack_array(abort_string,old_max);
960 if (n_reports >= MAX_REPORTS)
961 fatal(2, "Too many REPORT strings");
965 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
966 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
968 report_string[n_reports++] = s1;
971 chat_logf("report (%v)", s);
975 if (clear_report_next) {
981 clear_report_next = 0;
985 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
986 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
989 for (i=0; i < n_reports; i++) {
990 if ( strcmp(s1,report_string[i]) == 0 ) {
991 free(report_string[i]);
992 report_string[i] = NULL;
996 chat_logf("clear report (%v)", s);
1001 pack_array(report_string,old_max);
1011 timeout = DEFAULT_CHAT_TIMEOUT;
1014 chat_logf("timeout set to %d seconds", timeout);
1019 if (strcmp(s, "EOT") == 0)
1020 s = strdup("^D\\c");
1021 else if (strcmp(s, "BREAK") == 0)
1022 s = strdup("\\K\\c");
1034 status = read(STDIN_FILENO, &c, 1);
1038 return ((int)c & 0x7F);
1041 chat_logf("warning: read() on stdin returned %d", status);
1044 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1045 fatal(2, "Can't get file mode flags on stdin: %m");
1047 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1048 fatal(2, "Can't set file mode flags on stdin: %m");
1059 usleep(10000); /* inter-character typing delay (?) */
1061 status = write(STDOUT_FILENO, &ch, 1);
1068 chat_logf("warning: write() on stdout returned %d", status);
1071 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1072 fatal(2, "Can't get file mode flags on stdin, %m");
1074 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1075 fatal(2, "Can't set file mode flags on stdin: %m");
1084 if (alarmed || put_char(c) < 0) {
1089 if (errno == EINTR || errno == EWOULDBLOCK)
1090 chat_logf(" -- write timed out");
1092 chat_logf(" -- write failed: %m");
1106 chat_logf("send (%v)", quiet ? "??????" : s);
1108 alarm(timeout); alarmed = 0;
1114 if (!write_char (c))
1130 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1134 if (!write_char (c))
1146 * Echo a character to stderr.
1147 * When called with -1, a '\n' character is generated when
1148 * the cursor is not at the beginning of a line.
1157 case '\r': /* ignore '\r' */
1164 write(STDERR_FILENO, "\n", 1);
1169 write(STDERR_FILENO, s, strlen(s));
1176 * 'Wait for' this string to appear on this file descriptor.
1179 get_string(char *string)
1184 char *s = temp, *end = s + STR_LEN;
1185 char *logged = temp;
1187 fail_reason = (char *)0;
1189 if (strlen(string) > STR_LEN) {
1190 chat_logf("expect string is too long");
1195 string = clean(string, 0);
1196 len = strlen(string);
1197 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1200 chat_logf("expect (%v)", string);
1204 chat_logf("got it");
1211 while ( ! alarmed && (c = get_char()) >= 0) {
1212 int n, abort_len, report_len;
1216 if (verbose && c == '\n') {
1218 chat_logf(""); /* blank line */
1220 chat_logf("%0.*v", s - logged, logged);
1226 if (verbose && s >= logged + 80) {
1227 chat_logf("%0.*v", s - logged, logged);
1233 fputc( '\n', stderr );
1235 fprintf( stderr, "%s", character(c) );
1238 if (!report_gathering) {
1239 for (n = 0; n < n_reports; ++n) {
1240 if ((report_string[n] != (char*) NULL) &&
1241 s - temp >= (report_len = strlen(report_string[n])) &&
1242 strncmp(s - report_len, report_string[n], report_len) == 0) {
1243 time_t time_now = time ((time_t*) NULL);
1244 struct tm* tm_now = localtime (&time_now);
1246 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1247 strcat (report_buffer, report_string[n]);
1249 report_string[n] = (char *) NULL;
1250 report_gathering = 1;
1257 int rep_len = strlen (report_buffer);
1258 report_buffer[rep_len] = c;
1259 report_buffer[rep_len + 1] = '\0';
1262 report_gathering = 0;
1263 fprintf (report_fp, "chat: %s\n", report_buffer);
1267 if ((size_t)(s - temp) >= len &&
1268 c == string[len - 1] &&
1269 strncmp(s - len, string, len) == 0) {
1272 chat_logf("%0.*v", s - logged, logged);
1273 chat_logf(" -- got it\n");
1281 for (n = 0; n < n_aborts; ++n) {
1282 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1283 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1286 chat_logf("%0.*v", s - logged, logged);
1287 chat_logf(" -- failed");
1293 strcpy(fail_reason = fail_buffer, abort_string[n]);
1299 if (logged < s - minlen) {
1300 chat_logf("%0.*v", s - logged, logged);
1304 memmove(temp, s, minlen);
1305 logged = temp + (logged - s);
1309 if (alarmed && verbose)
1310 chat_logf("warning: alarm synchronization problem");
1315 if (verbose && printed) {
1317 chat_logf(" -- read timed out");
1319 chat_logf(" -- read failed: %m");
1328 pack_array(char **array, int end)
1332 for (i = 0; i < end; i++) {
1333 if (array[i] == NULL) {
1334 for (j = i+1; j < end; ++j)
1335 if (array[j] != NULL)
1336 array[i++] = array[j];
1337 for (; i < end; ++i)
1345 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1346 * also specify the length of the output buffer, and we handle the
1347 * %m (error message) format.
1348 * Doesn't do floating-point formats.
1349 * Returns the number of chars put into buf.
1351 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1354 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1357 int width, prec, fillch;
1358 int base, len, neg, quoted;
1359 unsigned long val = 0;
1364 static char hexchars[] = "0123456789abcdef";
1368 while (buflen > 0) {
1369 for (f = fmt; *f != '%' && *f != 0; ++f)
1375 memcpy(buf, fmt, len);
1390 width = va_arg(args, int);
1393 while (isdigit(c)) {
1394 width = width * 10 + c - '0';
1401 prec = va_arg(args, int);
1404 while (isdigit(c)) {
1405 prec = prec * 10 + c - '0';
1416 i = va_arg(args, int);
1425 val = va_arg(args, unsigned int);
1429 val = va_arg(args, unsigned int);
1433 val = (unsigned long) va_arg(args, void *);
1438 str = va_arg(args, char *);
1441 num[0] = va_arg(args, int);
1446 str = strerror(errno);
1448 case 'v': /* "visible" string */
1449 case 'q': /* quoted string */
1451 p = va_arg(args, unsigned char *);
1452 if (fillch == '0' && prec > 0) {
1455 n = strlen((char *)p);
1456 if (prec > 0 && prec < n)
1459 while (n > 0 && buflen > 0) {
1462 if (!quoted && c >= 0x80) {
1467 if (quoted && (c == '"' || c == '\\'))
1469 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1473 case '\t': OUTCHAR('t'); break;
1474 case '\n': OUTCHAR('n'); break;
1475 case '\b': OUTCHAR('b'); break;
1476 case '\f': OUTCHAR('f'); break;
1479 OUTCHAR(hexchars[c >> 4]);
1480 OUTCHAR(hexchars[c & 0xf]);
1497 --fmt; /* so %z outputs %z etc. */
1502 str = num + sizeof(num);
1504 while (str > num + neg) {
1505 *--str = hexchars[val % base];
1507 if (--prec <= 0 && val == 0)
1519 len = num + sizeof(num) - 1 - str;
1522 if (prec > 0 && len > prec)
1528 if ((n = width - len) > 0) {
1536 memcpy(buf, str, len);