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.
16 * Please send all bug reports, requests for information, etc. to:
18 * Al Longyear (longyear@netcom.com)
19 * (I was the last person to change this code.)
21 * Added -r "report file" switch & REPORT keyword.
22 * Robert Geer <bgeer@xmission.com>
24 * Added -e "echo" switch & ECHO keyword
25 * Dick Streefland <dicks@tasking.nl>
27 * The original author is:
29 * Karl Fox <karl@MorningStar.Com>
30 * Morning Star Technologies, Inc.
37 static char rcsid[] = "$Id: chat.c,v 1.13 1997/03/04 03:25:59 paulus Exp $";
46 #include <sys/types.h>
77 #define O_NONBLOCK O_NDELAY
80 /*************** Micro getopt() *********************************************/
81 #define OPTION(c,v) (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
82 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
83 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
84 #define OPTARG(c,v) (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
85 (_O=4,(char*)0):(char*)0)
86 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
87 #define ARG(c,v) (c?(--c,*v++):(char*)0)
89 static int _O = 0; /* Internal state */
90 /*************** Micro getopt() *********************************************/
95 #define MAX_REPORTS 50
96 #define DEFAULT_CHAT_TIMEOUT 45
104 FILE* report_fp = (FILE *) 0;
105 char *report_file = (char *) 0;
106 char *chat_file = (char *) 0;
107 int timeout = DEFAULT_CHAT_TIMEOUT;
109 int have_tty_parameters = 0;
112 #define term_parms struct termio
113 #define get_term_param(param) ioctl(0, TCGETA, param)
114 #define set_term_param(param) ioctl(0, TCSETA, param)
115 struct termio saved_tty_parameters;
119 #define term_parms struct termios
120 #define get_term_param(param) tcgetattr(0, param)
121 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
122 struct termios saved_tty_parameters;
125 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
127 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
129 char *report_string[MAX_REPORTS] ;
130 char report_buffer[50] ;
131 int n_reports = 0, report_next = 0, report_gathering = 0 ;
133 void *dup_mem __P((void *b, size_t c));
134 void *copy_of __P((char *s));
135 void usage __P((void));
136 void logf __P((const char *str));
137 void logflush __P((void));
138 void fatal __P((const char *msg));
139 void sysfatal __P((const char *msg));
140 SIGTYPE sigalrm __P((int signo));
141 SIGTYPE sigint __P((int signo));
142 SIGTYPE sigterm __P((int signo));
143 SIGTYPE sighup __P((int signo));
144 void unalarm __P((void));
145 void init __P((void));
146 void set_tty_parameters __P((void));
147 void echo_stderr __P((int));
148 void break_sequence __P((void));
149 void terminate __P((int status));
150 void do_file __P((char *chat_file));
151 int get_string __P((register char *string));
152 int put_string __P((register char *s));
153 int write_char __P((int c));
154 int put_char __P((int c));
155 int get_char __P((void));
156 void chat_send __P((register char *s));
157 char *character __P((int c));
158 void chat_expect __P((register char *s));
159 char *clean __P((register char *s, int sending));
160 void break_sequence __P((void));
161 void terminate __P((int status));
162 void die __P((void));
168 void *ans = malloc (c);
171 fatal ("memory error!\n");
180 return dup_mem (s, strlen (s) + 1);
184 * chat [ -v ] [ -t timeout ] [ -f chat-file ] [ -r report-file ] \
185 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
187 * Perform a UUCP-dialer-like chat script on stdin and stdout.
197 program_name = *argv;
200 while (option = OPTION(argc, argv))
217 if (arg = OPTARG(argc, argv))
219 chat_file = copy_of(arg);
228 if (arg = OPTARG(argc, argv))
239 arg = OPTARG (argc, argv);
242 if (report_fp != NULL)
246 report_file = copy_of (arg);
247 report_fp = fopen (report_file, "a");
248 if (report_fp != NULL)
252 fprintf (report_fp, "Opening \"%s\"...\n",
266 * Default the report file to the stderr location
268 if (report_fp == NULL)
274 openlog("chat", LOG_PID);
276 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
280 setlogmask(LOG_UPTO(LOG_INFO));
284 setlogmask(LOG_UPTO(LOG_WARNING));
290 if (chat_file != NULL)
292 arg = ARG(argc, argv);
304 while (arg = ARG(argc, argv))
308 if (arg = ARG(argc, argv))
319 * Process a chat script when read from a file.
322 void do_file (chat_file)
325 int linect, len, sendflg;
326 char *sp, *arg, quote;
330 cfp = fopen (chat_file, "r");
333 syslog (LOG_ERR, "%s -- open failed: %m", chat_file);
340 while (fgets(buf, STR_LEN, cfp) != NULL)
342 sp = strchr (buf, '\n');
352 if (*sp == ' ' || *sp == '\t')
358 if (*sp == '"' || *sp == '\'')
366 syslog (LOG_ERR, "unterminated quote (line %d)",
383 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
409 * We got an error parsing the command line.
414 Usage: %s [-e] [-v] [-t timeout] [-r report-file] {-f chat-file | chat-script}\n",
425 int l = strlen(line);
427 if (l + strlen(str) >= sizeof(line)) {
428 syslog(LOG_INFO, "%s", line);
431 strcpy(line + l, str);
433 if (str[strlen(str)-1] == '\n') {
434 syslog (LOG_INFO, "%s", line);
443 syslog(LOG_INFO, "%s", line);
449 * Terminate with an error.
457 * Print an error message and terminate.
463 syslog(LOG_ERR, "%s", msg);
468 * Print an error message along with the system error message and
475 syslog(LOG_ERR, "%s: %m", msg);
481 SIGTYPE sigalrm(signo)
487 alarmed = 1; /* Reset alarm to avoid race window */
488 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
491 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
493 sysfatal("Can't get file mode flags on stdin");
497 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
499 sysfatal("Can't set file mode flags on stdin");
505 syslog(LOG_INFO, "alarm");
513 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
515 sysfatal("Can't get file mode flags on stdin");
519 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
521 sysfatal("Can't set file mode flags on stdin");
526 SIGTYPE sigint(signo)
532 SIGTYPE sigterm(signo)
538 SIGTYPE sighup(signo)
546 signal(SIGINT, sigint);
547 signal(SIGTERM, sigterm);
548 signal(SIGHUP, sighup);
550 set_tty_parameters();
551 signal(SIGALRM, sigalrm);
556 void set_tty_parameters()
558 #if defined(get_term_param)
561 if (get_term_param (&t) < 0)
563 sysfatal("Can't get terminal parameters");
566 saved_tty_parameters = t;
567 have_tty_parameters = 1;
569 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
577 if (set_term_param (&t) < 0)
579 sysfatal("Can't set terminal parameters");
584 void break_sequence()
591 void terminate(status)
595 if (report_file != (char *) 0 && report_fp != (FILE *) NULL)
598 * Allow the last of the report string to be gathered before we terminate.
600 if (report_gathering) {
603 rep_len = strlen(report_buffer);
604 while (rep_len + 1 <= sizeof(report_buffer)) {
608 if (c < 0 || iscntrl(c))
610 report_buffer[rep_len] = c;
613 report_buffer[rep_len] = 0;
614 fprintf (report_fp, "chat: %s\n", report_buffer);
618 fprintf (report_fp, "Closing \"%s\".\n", report_file);
621 report_fp = (FILE *) NULL;
624 #if defined(get_term_param)
625 if (have_tty_parameters)
627 if (set_term_param (&saved_tty_parameters) < 0)
629 syslog(LOG_ERR, "Can't restore terminal parameters: %m");
639 * 'Clean up' this string.
641 char *clean(s, sending)
645 char temp[STR_LEN], cur_chr;
647 int add_return = sending;
648 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
694 if (sending && *s == '\0')
749 if (isoctal (cur_chr))
755 cur_chr |= *s++ - '0';
759 cur_chr |= *s++ - '0';
763 if (cur_chr != 0 || sending)
765 if (sending && (cur_chr == '\\' || cur_chr == 0))
788 *s1++ = '\0'; /* guarantee closure */
789 *s1++ = '\0'; /* terminate the string */
790 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
794 * A modified version of 'strtok'. This version skips \ sequences.
797 char *expect_strtok (s, term)
800 static char *str = "";
804 * If a string was specified then do initial processing.
811 * If this is the escape flag then reset it and ignore the character.
838 * If this is not in the termination string, continue.
840 if (strchr (term, *str) == (char *) 0)
846 * This is the terminator. Mark the end of the string and stop.
855 * Process the expect string
864 if (strcmp(s, "ABORT") == 0)
870 if (strcmp(s, "REPORT") == 0)
876 if (strcmp(s, "TIMEOUT") == 0)
882 if (strcmp(s, "ECHO") == 0)
888 * Fetch the expect and reply string.
892 expect = expect_strtok (s, "-");
895 if (expect == (char *) 0)
900 reply = expect_strtok (s, "-");
902 * Handle the expect string. If successful then exit.
904 if (get_string (expect))
909 * If there is a sub-reply string then send it. Otherwise any condition
912 if (reply == (char *) 0 || exit_code != 3)
920 * The expectation did not occur. This is terminal.
924 syslog(LOG_INFO, "Failed (%s)", fail_reason);
928 syslog(LOG_INFO, "Failed");
930 terminate(exit_code);
934 * Translate the input character to the appropriate string for printing
941 static char string[10];
944 meta = (c & 0x80) ? "M-" : "";
949 sprintf(string, "%s^%c", meta, (int)c + '@');
955 sprintf(string, "%s^?", meta);
959 sprintf(string, "%s%c", meta, c);
967 * process the reply string
975 echo = (strcmp(s, "ON") == 0);
984 if (n_aborts >= MAX_ABORTS)
986 fatal("Too many ABORT strings");
991 if (strlen(s1) > strlen(s)
992 || strlen(s1) + 1 > sizeof(fail_buffer))
994 syslog(LOG_WARNING, "Illegal or too-long ABORT string ('%s')", s);
998 abort_string[n_aborts++] = s1;
1004 for (s1 = s; *s1; ++s1)
1006 logf(character(*s1));
1019 if (n_reports >= MAX_REPORTS)
1021 fatal("Too many REPORT strings");
1026 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1028 syslog(LOG_WARNING, "Illegal or too-long REPORT string ('%s')", s);
1032 report_string[n_reports++] = s1;
1040 logf(character(*s1));
1055 timeout = DEFAULT_CHAT_TIMEOUT;
1060 syslog(LOG_INFO, "timeout set to %d seconds", timeout);
1065 if (strcmp(s, "EOT") == 0)
1071 if (strcmp(s, "BREAK") == 0)
1079 syslog(LOG_INFO, "Failed");
1089 status = read(0, &c, 1);
1094 return ((int)c & 0x7F);
1097 syslog(LOG_WARNING, "warning: read() on stdin returned %d",
1101 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1103 sysfatal("Can't get file mode flags on stdin");
1107 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1109 sysfatal("Can't set file mode flags on stdin");
1123 usleep(10000); /* inter-character typing delay (?) */
1125 status = write(1, &ch, 1);
1133 syslog(LOG_WARNING, "warning: write() on stdout returned %d",
1137 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1139 sysfatal("Can't get file mode flags on stdin");
1143 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1145 sysfatal("Can't set file mode flags on stdin");
1156 if (alarmed || put_char(c) < 0)
1165 if (errno == EINTR || errno == EWOULDBLOCK)
1167 syslog(LOG_INFO, " -- write timed out");
1171 syslog(LOG_INFO, " -- write failed: %m");
1194 register char *s1 = s;
1196 for (s1 = s; *s1; ++s1)
1198 logf(character(*s1));
1205 alarm(timeout); alarmed = 0;
1209 register char c = *s++;
1213 if (!write_char (c))
1232 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1236 if (!write_char (c))
1248 * Echo a character to stderr.
1249 * When called with -1, a '\n' character is generated when
1250 * the cursor is not at the beginning of a line.
1260 case '\r': /* ignore '\r' */
1272 write(2, s, strlen(s));
1279 * 'Wait for' this string to appear on this file descriptor.
1281 int get_string(string)
1282 register char *string;
1285 int c, printed = 0, len, minlen;
1286 register char *s = temp, *end = s + STR_LEN;
1288 fail_reason = (char *)0;
1289 string = clean(string, 0);
1290 len = strlen(string);
1291 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1299 for (s1 = string; *s1; ++s1)
1301 logf(character(*s1));
1309 syslog(LOG_INFO, "expect string is too long");
1318 syslog(LOG_INFO, "got it");
1327 while ( ! alarmed && (c = get_char()) >= 0)
1329 int n, abort_len, report_len;
1348 if (c == '\n') fputc( '\n', stderr );
1349 else if (c != '\r') fprintf( stderr, "%s", character(c) );
1354 if (!report_gathering)
1356 for (n = 0; n < n_reports; ++n)
1358 if ((report_string[n] != (char*) NULL) &&
1359 s - temp >= (report_len = strlen(report_string[n])) &&
1360 strncmp(s - report_len, report_string[n], report_len) == 0)
1362 time_t time_now = time ((time_t*) NULL);
1363 struct tm* tm_now = localtime (&time_now);
1365 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1366 strcat (report_buffer, report_string[n]);
1368 report_string[n] = (char *) NULL;
1369 report_gathering = 1;
1378 int rep_len = strlen (report_buffer);
1379 report_buffer[rep_len] = c;
1380 report_buffer[rep_len + 1] = '\0';
1384 report_gathering = 0;
1385 fprintf (report_fp, "chat: %s\n", report_buffer);
1389 if (s - temp >= len &&
1390 c == string[len - 1] &&
1391 strncmp(s - len, string, len) == 0)
1395 logf(" -- got it\n");
1403 for (n = 0; n < n_aborts; ++n)
1405 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1406 strncmp(s - abort_len, abort_string[n], abort_len) == 0)
1410 logf(" -- failed\n");
1416 strcpy(fail_reason = fail_buffer, abort_string[n]);
1423 strncpy (temp, s - minlen, minlen);
1427 if (alarmed && verbose)
1429 syslog(LOG_WARNING, "warning: alarm synchronization problem");
1435 if (verbose && printed)
1439 logf(" -- read timed out\n");
1444 syslog(LOG_INFO, " -- read failed: %m");
1454 #include <sys/types.h>
1455 #include <sys/time.h>
1458 usleep -- support routine for 4.2BSD system call emulations
1459 last edit: 29-Oct-1984 D A Gwyn
1462 extern int select();
1465 usleep( usec ) /* returns 0 if ok, else -1 */
1466 long usec; /* delay in microseconds */
1468 static struct /* `timeval' */
1470 long tv_sec; /* seconds */
1471 long tv_usec; /* microsecs */
1472 } delay; /* _select() timeout */
1474 delay.tv_sec = usec / 1000000L;
1475 delay.tv_usec = usec % 1000000L;
1477 return select( 0, (long *)0, (long *)0, (long *)0, &delay );