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.
38 static char rcsid[] = "$Id: chat.c,v 1.14 1997/04/30 05:40:50 paulus Exp $";
50 #include <sys/types.h>
81 #define O_NONBLOCK O_NDELAY
84 /*************** Micro getopt() *********************************************/
85 #define OPTION(c,v) (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
86 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
87 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
88 #define OPTARG(c,v) (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
89 (_O=4,(char*)0):(char*)0)
90 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
91 #define ARG(c,v) (c?(--c,*v++):(char*)0)
93 static int _O = 0; /* Internal state */
94 /*************** Micro getopt() *********************************************/
99 #define MAX_REPORTS 50
100 #define DEFAULT_CHAT_TIMEOUT 45
108 FILE* report_fp = (FILE *) 0;
109 char *report_file = (char *) 0;
110 char *chat_file = (char *) 0;
111 int timeout = DEFAULT_CHAT_TIMEOUT;
113 int have_tty_parameters = 0;
116 #define term_parms struct termio
117 #define get_term_param(param) ioctl(0, TCGETA, param)
118 #define set_term_param(param) ioctl(0, TCSETA, param)
119 struct termio saved_tty_parameters;
123 #define term_parms struct termios
124 #define get_term_param(param) tcgetattr(0, param)
125 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
126 struct termios saved_tty_parameters;
129 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
131 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
133 char *report_string[MAX_REPORTS] ;
134 char report_buffer[50] ;
135 int n_reports = 0, report_next = 0, report_gathering = 0 ;
137 void *dup_mem __P((void *b, size_t c));
138 void *copy_of __P((char *s));
139 void usage __P((void));
140 void logf __P((const char *str));
141 void logflush __P((void));
142 void fatal __P((const char *msg));
143 void sysfatal __P((const char *msg));
144 SIGTYPE sigalrm __P((int signo));
145 SIGTYPE sigint __P((int signo));
146 SIGTYPE sigterm __P((int signo));
147 SIGTYPE sighup __P((int signo));
148 void unalarm __P((void));
149 void init __P((void));
150 void set_tty_parameters __P((void));
151 void echo_stderr __P((int));
152 void break_sequence __P((void));
153 void terminate __P((int status));
154 void do_file __P((char *chat_file));
155 int get_string __P((register char *string));
156 int put_string __P((register char *s));
157 int write_char __P((int c));
158 int put_char __P((int c));
159 int get_char __P((void));
160 void chat_send __P((register char *s));
161 char *character __P((int c));
162 void chat_expect __P((register char *s));
163 char *clean __P((register char *s, int sending));
164 void break_sequence __P((void));
165 void terminate __P((int status));
166 void die __P((void));
167 char *expect_strtok __P((char *, char *));
169 int main __P((int, char *[]));
175 void *ans = malloc (c);
178 fatal ("memory error!\n");
187 return dup_mem (s, strlen (s) + 1);
191 * chat [ -v ] [ -t timeout ] [ -f chat-file ] [ -r report-file ] \
192 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
194 * Perform a UUCP-dialer-like chat script on stdin and stdout.
204 program_name = *argv;
207 while ((option = OPTION(argc, argv)) != 0)
224 if ((arg = OPTARG(argc, argv)) != NULL)
226 chat_file = copy_of(arg);
235 if ((arg = OPTARG(argc, argv)) != NULL)
246 arg = OPTARG (argc, argv);
249 if (report_fp != NULL)
253 report_file = copy_of (arg);
254 report_fp = fopen (report_file, "a");
255 if (report_fp != NULL)
259 fprintf (report_fp, "Opening \"%s\"...\n",
273 * Default the report file to the stderr location
275 if (report_fp == NULL)
281 openlog("chat", LOG_PID);
283 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
287 setlogmask(LOG_UPTO(LOG_INFO));
291 setlogmask(LOG_UPTO(LOG_WARNING));
297 if (chat_file != NULL)
299 arg = ARG(argc, argv);
311 while ((arg = ARG(argc, argv)) != NULL)
315 if ((arg = ARG(argc, argv)) != NULL)
327 * Process a chat script when read from a file.
330 void do_file (chat_file)
334 char *sp, *arg, quote;
338 cfp = fopen (chat_file, "r");
341 syslog (LOG_ERR, "%s -- open failed: %m", chat_file);
348 while (fgets(buf, STR_LEN, cfp) != NULL)
350 sp = strchr (buf, '\n');
360 if (*sp == ' ' || *sp == '\t')
366 if (*sp == '"' || *sp == '\'')
374 syslog (LOG_ERR, "unterminated quote (line %d)",
391 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
417 * We got an error parsing the command line.
422 Usage: %s [-e] [-v] [-t timeout] [-r report-file] {-f chat-file | chat-script}\n",
433 int l = strlen(line);
435 if (l + strlen(str) >= sizeof(line)) {
436 syslog(LOG_INFO, "%s", line);
439 strcpy(line + l, str);
441 if (str[strlen(str)-1] == '\n') {
442 syslog (LOG_INFO, "%s", line);
451 syslog(LOG_INFO, "%s", line);
457 * Terminate with an error.
465 * Print an error message and terminate.
471 syslog(LOG_ERR, "%s", msg);
476 * Print an error message along with the system error message and
483 syslog(LOG_ERR, "%s: %m", msg);
489 SIGTYPE sigalrm(signo)
495 alarmed = 1; /* Reset alarm to avoid race window */
496 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
499 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
501 sysfatal("Can't get file mode flags on stdin");
505 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
507 sysfatal("Can't set file mode flags on stdin");
513 syslog(LOG_INFO, "alarm");
521 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
523 sysfatal("Can't get file mode flags on stdin");
527 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
529 sysfatal("Can't set file mode flags on stdin");
534 SIGTYPE sigint(signo)
540 SIGTYPE sigterm(signo)
546 SIGTYPE sighup(signo)
554 signal(SIGINT, sigint);
555 signal(SIGTERM, sigterm);
556 signal(SIGHUP, sighup);
558 set_tty_parameters();
559 signal(SIGALRM, sigalrm);
564 void set_tty_parameters()
566 #if defined(get_term_param)
569 if (get_term_param (&t) < 0)
571 sysfatal("Can't get terminal parameters");
574 saved_tty_parameters = t;
575 have_tty_parameters = 1;
577 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
585 if (set_term_param (&t) < 0)
587 sysfatal("Can't set terminal parameters");
592 void break_sequence()
599 void terminate(status)
603 if (report_file != (char *) 0 && report_fp != (FILE *) NULL)
606 * Allow the last of the report string to be gathered before we terminate.
608 if (report_gathering) {
611 rep_len = strlen(report_buffer);
612 while (rep_len + 1 <= sizeof(report_buffer)) {
616 if (c < 0 || iscntrl(c))
618 report_buffer[rep_len] = c;
621 report_buffer[rep_len] = 0;
622 fprintf (report_fp, "chat: %s\n", report_buffer);
626 fprintf (report_fp, "Closing \"%s\".\n", report_file);
629 report_fp = (FILE *) NULL;
632 #if defined(get_term_param)
633 if (have_tty_parameters)
635 if (set_term_param (&saved_tty_parameters) < 0)
637 syslog(LOG_ERR, "Can't restore terminal parameters: %m");
647 * 'Clean up' this string.
649 char *clean(s, sending)
653 char temp[STR_LEN], cur_chr;
655 int add_return = sending;
656 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
702 if (sending && *s == '\0')
757 if (isoctal (cur_chr))
763 cur_chr |= *s++ - '0';
767 cur_chr |= *s++ - '0';
771 if (cur_chr != 0 || sending)
773 if (sending && (cur_chr == '\\' || cur_chr == 0))
796 *s1++ = '\0'; /* guarantee closure */
797 *s1++ = '\0'; /* terminate the string */
798 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
802 * A modified version of 'strtok'. This version skips \ sequences.
805 char *expect_strtok (s, term)
808 static char *str = "";
812 * If a string was specified then do initial processing.
819 * If this is the escape flag then reset it and ignore the character.
846 * If this is not in the termination string, continue.
848 if (strchr (term, *str) == (char *) 0)
854 * This is the terminator. Mark the end of the string and stop.
863 * Process the expect string
872 if (strcmp(s, "ABORT") == 0)
878 if (strcmp(s, "REPORT") == 0)
884 if (strcmp(s, "TIMEOUT") == 0)
890 if (strcmp(s, "ECHO") == 0)
896 * Fetch the expect and reply string.
900 expect = expect_strtok (s, "-");
903 if (expect == (char *) 0)
908 reply = expect_strtok (s, "-");
910 * Handle the expect string. If successful then exit.
912 if (get_string (expect))
917 * If there is a sub-reply string then send it. Otherwise any condition
920 if (reply == (char *) 0 || exit_code != 3)
928 * The expectation did not occur. This is terminal.
932 syslog(LOG_INFO, "Failed (%s)", fail_reason);
936 syslog(LOG_INFO, "Failed");
938 terminate(exit_code);
942 * Translate the input character to the appropriate string for printing
949 static char string[10];
952 meta = (c & 0x80) ? "M-" : "";
957 sprintf(string, "%s^%c", meta, (int)c + '@');
963 sprintf(string, "%s^?", meta);
967 sprintf(string, "%s%c", meta, c);
975 * process the reply string
983 echo = (strcmp(s, "ON") == 0);
992 if (n_aborts >= MAX_ABORTS)
994 fatal("Too many ABORT strings");
999 if (strlen(s1) > strlen(s)
1000 || strlen(s1) + 1 > sizeof(fail_buffer))
1002 syslog(LOG_WARNING, "Illegal or too-long ABORT string ('%s')", s);
1006 abort_string[n_aborts++] = s1;
1012 for (s1 = s; *s1; ++s1)
1014 logf(character(*s1));
1027 if (n_reports >= MAX_REPORTS)
1029 fatal("Too many REPORT strings");
1034 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1036 syslog(LOG_WARNING, "Illegal or too-long REPORT string ('%s')", s);
1040 report_string[n_reports++] = s1;
1048 logf(character(*s1));
1063 timeout = DEFAULT_CHAT_TIMEOUT;
1068 syslog(LOG_INFO, "timeout set to %d seconds", timeout);
1073 if (strcmp(s, "EOT") == 0)
1079 if (strcmp(s, "BREAK") == 0)
1087 syslog(LOG_INFO, "Failed");
1097 status = read(0, &c, 1);
1102 return ((int)c & 0x7F);
1105 syslog(LOG_WARNING, "warning: read() on stdin returned %d",
1109 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1111 sysfatal("Can't get file mode flags on stdin");
1115 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1117 sysfatal("Can't set file mode flags on stdin");
1131 usleep(10000); /* inter-character typing delay (?) */
1133 status = write(1, &ch, 1);
1141 syslog(LOG_WARNING, "warning: write() on stdout returned %d",
1145 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1147 sysfatal("Can't get file mode flags on stdin");
1151 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1153 sysfatal("Can't set file mode flags on stdin");
1164 if (alarmed || put_char(c) < 0)
1173 if (errno == EINTR || errno == EWOULDBLOCK)
1175 syslog(LOG_INFO, " -- write timed out");
1179 syslog(LOG_INFO, " -- write failed: %m");
1203 register char *s1 = s;
1205 for (s1 = s; *s1; ++s1)
1207 logf(character(*s1));
1214 alarm(timeout); alarmed = 0;
1218 register char c = *s++;
1222 if (!write_char (c))
1241 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1245 if (!write_char (c))
1257 * Echo a character to stderr.
1258 * When called with -1, a '\n' character is generated when
1259 * the cursor is not at the beginning of a line.
1269 case '\r': /* ignore '\r' */
1281 write(2, s, strlen(s));
1288 * 'Wait for' this string to appear on this file descriptor.
1290 int get_string(string)
1291 register char *string;
1294 int c, printed = 0, len, minlen;
1295 register char *s = temp, *end = s + STR_LEN;
1297 fail_reason = (char *)0;
1298 string = clean(string, 0);
1299 len = strlen(string);
1300 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1308 for (s1 = string; *s1; ++s1)
1310 logf(character(*s1));
1318 syslog(LOG_INFO, "expect string is too long");
1327 syslog(LOG_INFO, "got it");
1336 while ( ! alarmed && (c = get_char()) >= 0)
1338 int n, abort_len, report_len;
1357 if (c == '\n') fputc( '\n', stderr );
1358 else if (c != '\r') fprintf( stderr, "%s", character(c) );
1363 if (!report_gathering)
1365 for (n = 0; n < n_reports; ++n)
1367 if ((report_string[n] != (char*) NULL) &&
1368 s - temp >= (report_len = strlen(report_string[n])) &&
1369 strncmp(s - report_len, report_string[n], report_len) == 0)
1371 time_t time_now = time ((time_t*) NULL);
1372 struct tm* tm_now = localtime (&time_now);
1374 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1375 strcat (report_buffer, report_string[n]);
1377 report_string[n] = (char *) NULL;
1378 report_gathering = 1;
1387 int rep_len = strlen (report_buffer);
1388 report_buffer[rep_len] = c;
1389 report_buffer[rep_len + 1] = '\0';
1393 report_gathering = 0;
1394 fprintf (report_fp, "chat: %s\n", report_buffer);
1398 if (s - temp >= len &&
1399 c == string[len - 1] &&
1400 strncmp(s - len, string, len) == 0)
1404 logf(" -- got it\n");
1412 for (n = 0; n < n_aborts; ++n)
1414 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1415 strncmp(s - abort_len, abort_string[n], abort_len) == 0)
1419 logf(" -- failed\n");
1425 strcpy(fail_reason = fail_buffer, abort_string[n]);
1432 strncpy (temp, s - minlen, minlen);
1436 if (alarmed && verbose)
1438 syslog(LOG_WARNING, "warning: alarm synchronization problem");
1444 if (verbose && printed)
1448 logf(" -- read timed out\n");
1453 syslog(LOG_INFO, " -- read failed: %m");
1463 #include <sys/types.h>
1464 #include <sys/time.h>
1467 usleep -- support routine for 4.2BSD system call emulations
1468 last edit: 29-Oct-1984 D A Gwyn
1471 extern int select();
1474 usleep( usec ) /* returns 0 if ok, else -1 */
1475 long usec; /* delay in microseconds */
1477 static struct /* `timeval' */
1479 long tv_sec; /* seconds */
1480 long tv_usec; /* microsecs */
1481 } delay; /* _select() timeout */
1483 delay.tv_sec = usec / 1000000L;
1484 delay.tv_usec = usec % 1000000L;
1486 return select( 0, (long *)0, (long *)0, (long *)0, &delay );