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 condtion.
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.
18 * Added SAY keyword to send output to stderr.
19 * This allows to turn ECHO OFF and to output specific, user selected,
20 * text to give progress messages. This best works when stderr
21 * exists (i.e.: pppd in nodetach mode).
23 * Added HANGUP directives to allow for us to be called
24 * back. When HANGUP is set to NO, chat will not hangup at HUP signal.
25 * We rely on timeouts in that case.
27 * Added CLR_ABORT to clear previously set ABORT string. This has been
28 * dictated by the HANGUP above as "NO CARRIER" (for example) must be
29 * an ABORT condition until we know the other host is going to close
30 * the connection for call back. As soon as we have completed the
31 * first stage of the call back sequence, "NO CARRIER" is a valid, non
32 * fatal string. As soon as we got called back (probably get "CONNECT"),
33 * we should re-arm the ABORT "NO CARRIER". Hence the CLR_ABORT command.
34 * Note that CLR_ABORT packs the abort_strings[] array so that we do not
35 * have unused entries not being reclaimed.
37 * In the same vein as above, added CLR_REPORT keyword.
39 * Allow for comments. Line starting with '#' are comments and are
40 * ignored. If a '#' is to be expected as the first character, the
41 * expect string must be quoted.
44 * Francis Demierre <Francis@SwissMail.Com>
45 * Thu May 15 17:15:40 MET DST 1997
48 * Added -r "report file" switch & REPORT keyword.
49 * Robert Geer <bgeer@xmission.com>
52 * Added -e "echo" switch & ECHO keyword
53 * Dick Streefland <dicks@tasking.nl>
56 * Considerable updates and modifications by
57 * Al Longyear <longyear@pobox.com>
58 * Paul Mackerras <paulus@cs.anu.edu.au>
61 * The original author is:
63 * Karl Fox <karl@MorningStar.Com>
64 * Morning Star Technologies, Inc.
73 static char rcsid[] = "$Id: chat.c,v 1.15 1997/07/14 03:50:22 paulus Exp $";
85 #include <sys/types.h>
116 #define O_NONBLOCK O_NDELAY
119 /*************** Micro getopt() *********************************************/
120 #define OPTION(c,v) (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
121 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
122 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
123 #define OPTARG(c,v) (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
124 (_O=4,(char*)0):(char*)0)
125 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
126 #define ARG(c,v) (c?(--c,*v++):(char*)0)
128 static int _O = 0; /* Internal state */
129 /*************** Micro getopt() *********************************************/
133 #define MAX_ABORTS 50
134 #define MAX_REPORTS 50
135 #define DEFAULT_CHAT_TIMEOUT 45
143 FILE* report_fp = (FILE *) 0;
144 char *report_file = (char *) 0;
145 char *chat_file = (char *) 0;
146 int timeout = DEFAULT_CHAT_TIMEOUT;
148 int have_tty_parameters = 0;
151 #define term_parms struct termio
152 #define get_term_param(param) ioctl(0, TCGETA, param)
153 #define set_term_param(param) ioctl(0, TCSETA, param)
154 struct termio saved_tty_parameters;
158 #define term_parms struct termios
159 #define get_term_param(param) tcgetattr(0, param)
160 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
161 struct termios saved_tty_parameters;
164 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
166 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
167 int clear_abort_next = 0;
169 char *report_string[MAX_REPORTS] ;
170 char report_buffer[50] ;
171 int n_reports = 0, report_next = 0, report_gathering = 0 ;
172 int clear_report_next = 0;
174 int say_next = 0, hup_next = 0;
176 void *dup_mem __P((void *b, size_t c));
177 void *copy_of __P((char *s));
178 void usage __P((void));
179 void logf __P((const char *str));
180 void logflush __P((void));
181 void fatal __P((const char *msg));
182 void sysfatal __P((const char *msg));
183 SIGTYPE sigalrm __P((int signo));
184 SIGTYPE sigint __P((int signo));
185 SIGTYPE sigterm __P((int signo));
186 SIGTYPE sighup __P((int signo));
187 void unalarm __P((void));
188 void init __P((void));
189 void set_tty_parameters __P((void));
190 void echo_stderr __P((int));
191 void break_sequence __P((void));
192 void terminate __P((int status));
193 void do_file __P((char *chat_file));
194 int get_string __P((register char *string));
195 int put_string __P((register char *s));
196 int write_char __P((int c));
197 int put_char __P((int c));
198 int get_char __P((void));
199 void chat_send __P((register char *s));
200 char *character __P((int c));
201 void chat_expect __P((register char *s));
202 char *clean __P((register char *s, int sending));
203 void break_sequence __P((void));
204 void terminate __P((int status));
205 void die __P((void));
206 void pack_array __P((char **array, int end));
207 char *expect_strtok __P((char *, char *));
209 int main __P((int, char *[]));
215 void *ans = malloc (c);
218 fatal ("memory error!\n");
227 return dup_mem (s, strlen (s) + 1);
231 * chat [ -v ] [ -t timeout ] [ -f chat-file ] [ -r report-file ] \
232 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
234 * Perform a UUCP-dialer-like chat script on stdin and stdout.
244 program_name = *argv;
247 while ((option = OPTION(argc, argv)) != 0)
264 if ((arg = OPTARG(argc, argv)) != NULL)
266 chat_file = copy_of(arg);
275 if ((arg = OPTARG(argc, argv)) != NULL)
286 arg = OPTARG (argc, argv);
289 if (report_fp != NULL)
293 report_file = copy_of (arg);
294 report_fp = fopen (report_file, "a");
295 if (report_fp != NULL)
299 fprintf (report_fp, "Opening \"%s\"...\n",
313 * Default the report file to the stderr location
315 if (report_fp == NULL)
321 openlog("chat", LOG_PID);
323 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
327 setlogmask(LOG_UPTO(LOG_INFO));
331 setlogmask(LOG_UPTO(LOG_WARNING));
337 if (chat_file != NULL)
339 arg = ARG(argc, argv);
351 while ((arg = ARG(argc, argv)) != NULL)
355 if ((arg = ARG(argc, argv)) != NULL)
367 * Process a chat script when read from a file.
370 void do_file (chat_file)
373 int linect, len, sendflg;
374 char *sp, *arg, quote;
378 cfp = fopen (chat_file, "r");
381 syslog (LOG_ERR, "%s -- open failed: %m", chat_file);
388 while (fgets(buf, STR_LEN, cfp) != NULL)
390 sp = strchr (buf, '\n');
399 /* lines starting with '#' are comments. If a real '#'
400 is to be expected, it should be quoted .... */
401 if ( *sp == '#' ) continue;
405 if (*sp == ' ' || *sp == '\t')
411 if (*sp == '"' || *sp == '\'')
419 syslog (LOG_ERR, "unterminated quote (line %d)",
436 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
462 * We got an error parsing the command line.
467 Usage: %s [-e] [-v] [-t timeout] [-r report-file] {-f chat-file | chat-script}\n",
478 int l = strlen(line);
480 if (l + strlen(str) >= sizeof(line)) {
481 syslog(LOG_INFO, "%s", line);
484 strcpy(line + l, str);
486 if (str[strlen(str)-1] == '\n') {
487 syslog (LOG_INFO, "%s", line);
496 syslog(LOG_INFO, "%s", line);
502 * Terminate with an error.
510 * Print an error message and terminate.
516 syslog(LOG_ERR, "%s", msg);
521 * Print an error message along with the system error message and
528 syslog(LOG_ERR, "%s: %m", msg);
534 SIGTYPE sigalrm(signo)
540 alarmed = 1; /* Reset alarm to avoid race window */
541 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
544 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
546 sysfatal("Can't get file mode flags on stdin");
550 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
552 sysfatal("Can't set file mode flags on stdin");
558 syslog(LOG_INFO, "alarm");
566 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
568 sysfatal("Can't get file mode flags on stdin");
572 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
574 sysfatal("Can't set file mode flags on stdin");
579 SIGTYPE sigint(signo)
585 SIGTYPE sigterm(signo)
591 SIGTYPE sighup(signo)
599 signal(SIGINT, sigint);
600 signal(SIGTERM, sigterm);
601 signal(SIGHUP, sighup);
603 set_tty_parameters();
604 signal(SIGALRM, sigalrm);
609 void set_tty_parameters()
611 #if defined(get_term_param)
614 if (get_term_param (&t) < 0)
616 sysfatal("Can't get terminal parameters");
619 saved_tty_parameters = t;
620 have_tty_parameters = 1;
622 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
630 if (set_term_param (&t) < 0)
632 sysfatal("Can't set terminal parameters");
637 void break_sequence()
644 void terminate(status)
648 if (report_file != (char *) 0 && report_fp != (FILE *) NULL)
651 * Allow the last of the report string to be gathered before we terminate.
653 if (report_gathering) {
656 rep_len = strlen(report_buffer);
657 while (rep_len + 1 <= sizeof(report_buffer)) {
661 if (c < 0 || iscntrl(c))
663 report_buffer[rep_len] = c;
666 report_buffer[rep_len] = 0;
667 fprintf (report_fp, "chat: %s\n", report_buffer);
671 fprintf (report_fp, "Closing \"%s\".\n", report_file);
674 report_fp = (FILE *) NULL;
677 #if defined(get_term_param)
678 if (have_tty_parameters)
680 if (set_term_param (&saved_tty_parameters) < 0)
682 syslog(LOG_ERR, "Can't restore terminal parameters: %m");
692 * 'Clean up' this string.
694 char *clean(s, sending)
698 char temp[STR_LEN], cur_chr;
700 int add_return = sending;
701 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
747 if (sending && *s == '\0')
802 if (isoctal (cur_chr))
808 cur_chr |= *s++ - '0';
812 cur_chr |= *s++ - '0';
816 if (cur_chr != 0 || sending)
818 if (sending && (cur_chr == '\\' || cur_chr == 0))
841 *s1++ = '\0'; /* guarantee closure */
842 *s1++ = '\0'; /* terminate the string */
843 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
847 * A modified version of 'strtok'. This version skips \ sequences.
850 char *expect_strtok (s, term)
853 static char *str = "";
857 * If a string was specified then do initial processing.
864 * If this is the escape flag then reset it and ignore the character.
891 * If this is not in the termination string, continue.
893 if (strchr (term, *str) == (char *) 0)
899 * This is the terminator. Mark the end of the string and stop.
908 * Process the expect string
917 if (strcmp(s, "HANGUP") == 0)
923 if (strcmp(s, "ABORT") == 0)
929 if (strcmp(s, "CLR_ABORT") == 0)
935 if (strcmp(s, "REPORT") == 0)
941 if (strcmp(s, "CLR_REPORT") == 0)
947 if (strcmp(s, "TIMEOUT") == 0)
953 if (strcmp(s, "ECHO") == 0)
958 if (strcmp(s, "SAY") == 0)
964 * Fetch the expect and reply string.
968 expect = expect_strtok (s, "-");
971 if (expect == (char *) 0)
976 reply = expect_strtok (s, "-");
978 * Handle the expect string. If successful then exit.
980 if (get_string (expect))
985 * If there is a sub-reply string then send it. Otherwise any condition
988 if (reply == (char *) 0 || exit_code != 3)
996 * The expectation did not occur. This is terminal.
1000 syslog(LOG_INFO, "Failed (%s)", fail_reason);
1004 syslog(LOG_INFO, "Failed");
1006 terminate(exit_code);
1010 * Translate the input character to the appropriate string for printing
1017 static char string[10];
1020 meta = (c & 0x80) ? "M-" : "";
1025 sprintf(string, "%s^%c", meta, (int)c + '@');
1031 sprintf(string, "%s^?", meta);
1035 sprintf(string, "%s%c", meta, c);
1043 * process the reply string
1052 write(2, s, strlen(s));
1059 if (strcmp(s, "OFF") == 0)
1060 signal(SIGHUP, SIG_IGN);
1062 signal(SIGHUP, sighup);
1068 echo = (strcmp(s, "ON") == 0);
1077 if (n_aborts >= MAX_ABORTS)
1079 fatal("Too many ABORT strings");
1084 if (strlen(s1) > strlen(s)
1085 || strlen(s1) + 1 > sizeof(fail_buffer))
1087 syslog(LOG_WARNING, "Illegal or too-long ABORT string ('%s')", s);
1091 abort_string[n_aborts++] = s1;
1097 for (s1 = s; *s1; ++s1)
1099 logf(character(*s1));
1107 if (clear_abort_next)
1115 clear_abort_next = 0;
1119 if (strlen(s1) > strlen(s)
1120 || strlen(s1) + 1 > sizeof(fail_buffer))
1122 syslog(LOG_WARNING, "Illegal or too-long CLR_ABORT string ('%s')", s);
1127 for (i=0; i < n_aborts; i++)
1129 if ( strcmp(s1,abort_string[i]) == 0 )
1131 free(abort_string[i]);
1132 abort_string[i] = NULL;
1137 logf("clear abort on (");
1139 for (s2 = s; *s2; ++s2)
1141 logf(character(*s2));
1149 if (pack) pack_array(abort_string,old_max);
1158 if (n_reports >= MAX_REPORTS)
1160 fatal("Too many REPORT strings");
1165 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1167 syslog(LOG_WARNING, "Illegal or too-long REPORT string ('%s')", s);
1171 report_string[n_reports++] = s1;
1179 logf(character(*s1));
1187 if (clear_report_next)
1195 clear_report_next = 0;
1199 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1201 syslog(LOG_WARNING, "Illegal or too-long REPORT string ('%s')", s);
1205 old_max = n_reports;
1206 for (i=0; i < n_reports; i++)
1208 if ( strcmp(s1,report_string[i]) == 0 )
1210 free(report_string[i]);
1211 report_string[i] = NULL;
1216 logf("clear report (");
1218 for (s2 = s; *s2; ++s2)
1220 logf(character(*s2));
1228 if (pack) pack_array(report_string,old_max);
1240 timeout = DEFAULT_CHAT_TIMEOUT;
1245 syslog(LOG_INFO, "timeout set to %d seconds", timeout);
1250 if (strcmp(s, "EOT") == 0)
1256 if (strcmp(s, "BREAK") == 0)
1264 syslog(LOG_INFO, "Failed");
1274 status = read(0, &c, 1);
1279 return ((int)c & 0x7F);
1282 syslog(LOG_WARNING, "warning: read() on stdin returned %d",
1286 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1288 sysfatal("Can't get file mode flags on stdin");
1292 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1294 sysfatal("Can't set file mode flags on stdin");
1308 usleep(10000); /* inter-character typing delay (?) */
1310 status = write(1, &ch, 1);
1318 syslog(LOG_WARNING, "warning: write() on stdout returned %d",
1322 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1324 sysfatal("Can't get file mode flags on stdin");
1328 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1330 sysfatal("Can't set file mode flags on stdin");
1341 if (alarmed || put_char(c) < 0)
1350 if (errno == EINTR || errno == EWOULDBLOCK)
1352 syslog(LOG_INFO, " -- write timed out");
1356 syslog(LOG_INFO, " -- write failed: %m");
1380 register char *s1 = s;
1382 for (s1 = s; *s1; ++s1)
1384 logf(character(*s1));
1391 alarm(timeout); alarmed = 0;
1395 register char c = *s++;
1399 if (!write_char (c))
1418 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1422 if (!write_char (c))
1434 * Echo a character to stderr.
1435 * When called with -1, a '\n' character is generated when
1436 * the cursor is not at the beginning of a line.
1446 case '\r': /* ignore '\r' */
1458 write(2, s, strlen(s));
1465 * 'Wait for' this string to appear on this file descriptor.
1467 int get_string(string)
1468 register char *string;
1471 int c, printed = 0, len, minlen;
1472 register char *s = temp, *end = s + STR_LEN;
1474 fail_reason = (char *)0;
1475 string = clean(string, 0);
1476 len = strlen(string);
1477 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1485 for (s1 = string; *s1; ++s1)
1487 logf(character(*s1));
1495 syslog(LOG_INFO, "expect string is too long");
1504 syslog(LOG_INFO, "got it");
1513 while ( ! alarmed && (c = get_char()) >= 0)
1515 int n, abort_len, report_len;
1534 if (c == '\n') fputc( '\n', stderr );
1535 else if (c != '\r') fprintf( stderr, "%s", character(c) );
1540 if (!report_gathering)
1542 for (n = 0; n < n_reports; ++n)
1544 if ((report_string[n] != (char*) NULL) &&
1545 s - temp >= (report_len = strlen(report_string[n])) &&
1546 strncmp(s - report_len, report_string[n], report_len) == 0)
1548 time_t time_now = time ((time_t*) NULL);
1549 struct tm* tm_now = localtime (&time_now);
1551 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1552 strcat (report_buffer, report_string[n]);
1554 report_string[n] = (char *) NULL;
1555 report_gathering = 1;
1564 int rep_len = strlen (report_buffer);
1565 report_buffer[rep_len] = c;
1566 report_buffer[rep_len + 1] = '\0';
1570 report_gathering = 0;
1571 fprintf (report_fp, "chat: %s\n", report_buffer);
1575 if (s - temp >= len &&
1576 c == string[len - 1] &&
1577 strncmp(s - len, string, len) == 0)
1581 logf(" -- got it\n");
1589 for (n = 0; n < n_aborts; ++n)
1591 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1592 strncmp(s - abort_len, abort_string[n], abort_len) == 0)
1596 logf(" -- failed\n");
1602 strcpy(fail_reason = fail_buffer, abort_string[n]);
1609 strncpy (temp, s - minlen, minlen);
1613 if (alarmed && verbose)
1615 syslog(LOG_WARNING, "warning: alarm synchronization problem");
1621 if (verbose && printed)
1625 logf(" -- read timed out\n");
1630 syslog(LOG_INFO, " -- read failed: %m");
1640 #include <sys/types.h>
1641 #include <sys/time.h>
1644 usleep -- support routine for 4.2BSD system call emulations
1645 last edit: 29-Oct-1984 D A Gwyn
1648 extern int select();
1651 usleep( usec ) /* returns 0 if ok, else -1 */
1652 long usec; /* delay in microseconds */
1654 static struct /* `timeval' */
1656 long tv_sec; /* seconds */
1657 long tv_usec; /* microsecs */
1658 } delay; /* _select() timeout */
1660 delay.tv_sec = usec / 1000000L;
1661 delay.tv_usec = usec % 1000000L;
1663 return select( 0, (long *)0, (long *)0, (long *)0, &delay );
1668 pack_array (array, end)
1669 char **array; /* The address of the array of string pointers */
1670 int end; /* The index of the next free entry before CLR_ */
1674 for (i = 0; i < end; i++) {
1675 if (array[i] == NULL) {
1676 for (j = i+1; j < end; ++j)
1677 if (array[j] != NULL)
1678 array[i++] = array[j];
1679 for (; i < end; ++i)