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.12 1996/06/26 00:51:06 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))
315 * Allow the last of the report string to be gathered before we terminate.
317 while (report_gathering)
323 int rep_len = strlen (report_buffer);
324 report_buffer[rep_len] = c;
325 report_buffer[rep_len + 1] = '\0';
329 report_gathering = 0;
330 fprintf (report_fp, "chat: %s\n", report_buffer);
338 * Process a chat script when read from a file.
341 void do_file (chat_file)
344 int linect, len, sendflg;
345 char *sp, *arg, quote;
349 cfp = fopen (chat_file, "r");
352 syslog (LOG_ERR, "%s -- open failed: %m", chat_file);
359 while (fgets(buf, STR_LEN, cfp) != NULL)
361 sp = strchr (buf, '\n');
371 if (*sp == ' ' || *sp == '\t')
377 if (*sp == '"' || *sp == '\'')
385 syslog (LOG_ERR, "unterminated quote (line %d)",
402 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
428 * We got an error parsing the command line.
433 Usage: %s [-e] [-v] [-t timeout] [-r report-file] {-f chat-file | chat-script}\n",
444 p = line + strlen(line);
447 if (str[strlen(str)-1] == '\n')
449 syslog (LOG_INFO, "%s", line);
458 syslog(LOG_INFO, "%s", line);
464 * Terminate with an error.
472 * Print an error message and terminate.
478 syslog(LOG_ERR, "%s", msg);
483 * Print an error message along with the system error message and
490 syslog(LOG_ERR, "%s: %m", msg);
496 SIGTYPE sigalrm(signo)
502 alarmed = 1; /* Reset alarm to avoid race window */
503 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
506 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
508 sysfatal("Can't get file mode flags on stdin");
512 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
514 sysfatal("Can't set file mode flags on stdin");
520 syslog(LOG_INFO, "alarm");
528 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
530 sysfatal("Can't get file mode flags on stdin");
534 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
536 sysfatal("Can't set file mode flags on stdin");
541 SIGTYPE sigint(signo)
547 SIGTYPE sigterm(signo)
553 SIGTYPE sighup(signo)
561 signal(SIGINT, sigint);
562 signal(SIGTERM, sigterm);
563 signal(SIGHUP, sighup);
565 set_tty_parameters();
566 signal(SIGALRM, sigalrm);
571 void set_tty_parameters()
573 #if defined(get_term_param)
576 if (get_term_param (&t) < 0)
578 sysfatal("Can't get terminal parameters");
581 saved_tty_parameters = t;
582 have_tty_parameters = 1;
584 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
592 if (set_term_param (&t) < 0)
594 sysfatal("Can't set terminal parameters");
599 void break_sequence()
606 void terminate(status)
610 if (report_file != (char *) 0 && report_fp != (FILE *) NULL)
614 fprintf (report_fp, "Closing \"%s\".\n", report_file);
617 report_fp = (FILE *) NULL;
620 #if defined(get_term_param)
621 if (have_tty_parameters)
623 if (set_term_param (&saved_tty_parameters) < 0)
625 syslog(LOG_ERR, "Can't restore terminal parameters: %m");
635 * 'Clean up' this string.
637 char *clean(s, sending)
641 char temp[STR_LEN], cur_chr;
643 int add_return = sending;
644 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
690 if (sending && *s == '\0')
745 if (isoctal (cur_chr))
751 cur_chr |= *s++ - '0';
755 cur_chr |= *s++ - '0';
759 if (cur_chr != 0 || sending)
761 if (sending && (cur_chr == '\\' || cur_chr == 0))
784 *s1++ = '\0'; /* guarantee closure */
785 *s1++ = '\0'; /* terminate the string */
786 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
790 * A modified version of 'strtok'. This version skips \ sequences.
793 char *expect_strtok (s, term)
796 static char *str = "";
800 * If a string was specified then do initial processing.
807 * If this is the escape flag then reset it and ignore the character.
834 * If this is not in the termination string, continue.
836 if (strchr (term, *str) == (char *) 0)
842 * This is the terminator. Mark the end of the string and stop.
851 * Process the expect string
860 if (strcmp(s, "ABORT") == 0)
866 if (strcmp(s, "REPORT") == 0)
872 if (strcmp(s, "TIMEOUT") == 0)
878 if (strcmp(s, "ECHO") == 0)
884 * Fetch the expect and reply string.
888 expect = expect_strtok (s, "-");
891 if (expect == (char *) 0)
896 reply = expect_strtok (s, "-");
898 * Handle the expect string. If successful then exit.
900 if (get_string (expect))
905 * If there is a sub-reply string then send it. Otherwise any condition
908 if (reply == (char *) 0 || exit_code != 3)
916 * The expectation did not occur. This is terminal.
920 syslog(LOG_INFO, "Failed (%s)", fail_reason);
924 syslog(LOG_INFO, "Failed");
926 terminate(exit_code);
930 * Translate the input character to the appropriate string for printing
937 static char string[10];
940 meta = (c & 0x80) ? "M-" : "";
945 sprintf(string, "%s^%c", meta, (int)c + '@');
951 sprintf(string, "%s^?", meta);
955 sprintf(string, "%s%c", meta, c);
963 * process the reply string
971 echo = (strcmp(s, "ON") == 0);
980 if (n_aborts >= MAX_ABORTS)
982 fatal("Too many ABORT strings");
987 if (strlen(s1) > strlen(s)
988 || strlen(s1) + 1 > sizeof(fail_buffer))
990 syslog(LOG_WARNING, "Illegal or too-long ABORT string ('%s')", s);
994 abort_string[n_aborts++] = s1;
1000 for (s1 = s; *s1; ++s1)
1002 logf(character(*s1));
1015 if (n_reports >= MAX_REPORTS)
1017 fatal("Too many REPORT strings");
1022 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1024 syslog(LOG_WARNING, "Illegal or too-long REPORT string ('%s')", s);
1028 report_string[n_reports++] = s1;
1036 logf(character(*s1));
1051 timeout = DEFAULT_CHAT_TIMEOUT;
1056 syslog(LOG_INFO, "timeout set to %d seconds", timeout);
1061 if (strcmp(s, "EOT") == 0)
1067 if (strcmp(s, "BREAK") == 0)
1075 syslog(LOG_INFO, "Failed");
1085 status = read(0, &c, 1);
1090 return ((int)c & 0x7F);
1093 syslog(LOG_WARNING, "warning: read() on stdin returned %d",
1097 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1099 sysfatal("Can't get file mode flags on stdin");
1103 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1105 sysfatal("Can't set file mode flags on stdin");
1119 usleep(10000); /* inter-character typing delay (?) */
1121 status = write(1, &ch, 1);
1129 syslog(LOG_WARNING, "warning: write() on stdout returned %d",
1133 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1135 sysfatal("Can't get file mode flags on stdin");
1139 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1141 sysfatal("Can't set file mode flags on stdin");
1152 if (alarmed || put_char(c) < 0)
1161 if (errno == EINTR || errno == EWOULDBLOCK)
1163 syslog(LOG_INFO, " -- write timed out");
1167 syslog(LOG_INFO, " -- write failed: %m");
1190 register char *s1 = s;
1192 for (s1 = s; *s1; ++s1)
1194 logf(character(*s1));
1201 alarm(timeout); alarmed = 0;
1205 register char c = *s++;
1209 if (!write_char (c))
1228 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1232 if (!write_char (c))
1244 * Echo a character to stderr.
1245 * When called with -1, a '\n' character is generated when
1246 * the cursor is not at the beginning of a line.
1256 case '\r': /* ignore '\r' */
1268 write(2, s, strlen(s));
1275 * 'Wait for' this string to appear on this file descriptor.
1277 int get_string(string)
1278 register char *string;
1281 int c, printed = 0, len, minlen;
1282 register char *s = temp, *end = s + STR_LEN;
1284 fail_reason = (char *)0;
1285 string = clean(string, 0);
1286 len = strlen(string);
1287 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1295 for (s1 = string; *s1; ++s1)
1297 logf(character(*s1));
1305 syslog(LOG_INFO, "expect string is too long");
1314 syslog(LOG_INFO, "got it");
1323 while ( ! alarmed && (c = get_char()) >= 0)
1325 int n, abort_len, report_len;
1344 if (c == '\n') fputc( '\n', stderr );
1345 else if (c != '\r') fprintf( stderr, "%s", character(c) );
1350 if (!report_gathering)
1352 for (n = 0; n < n_reports; ++n)
1354 if ((report_string[n] != (char*) NULL) &&
1355 s - temp >= (report_len = strlen(report_string[n])) &&
1356 strncmp(s - report_len, report_string[n], report_len) == 0)
1358 time_t time_now = time ((time_t*) NULL);
1359 struct tm* tm_now = localtime (&time_now);
1361 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1362 strcat (report_buffer, report_string[n]);
1364 report_string[n] = (char *) NULL;
1365 report_gathering = 1;
1374 int rep_len = strlen (report_buffer);
1375 report_buffer[rep_len] = c;
1376 report_buffer[rep_len + 1] = '\0';
1380 report_gathering = 0;
1381 fprintf (report_fp, "chat: %s\n", report_buffer);
1385 if (s - temp >= len &&
1386 c == string[len - 1] &&
1387 strncmp(s - len, string, len) == 0)
1391 logf(" -- got it\n");
1399 for (n = 0; n < n_aborts; ++n)
1401 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1402 strncmp(s - abort_len, abort_string[n], abort_len) == 0)
1406 logf(" -- failed\n");
1412 strcpy(fail_reason = fail_buffer, abort_string[n]);
1419 strncpy (temp, s - minlen, minlen);
1423 if (alarmed && verbose)
1425 syslog(LOG_WARNING, "warning: alarm synchronization problem");
1431 if (verbose && printed)
1435 logf(" -- read timed out\n");
1440 syslog(LOG_INFO, " -- read failed: %m");
1450 #include <sys/types.h>
1451 #include <sys/time.h>
1454 usleep -- support routine for 4.2BSD system call emulations
1455 last edit: 29-Oct-1984 D A Gwyn
1458 extern int select();
1461 usleep( usec ) /* returns 0 if ok, else -1 */
1462 long usec; /* delay in microseconds */
1464 static struct /* `timeval' */
1466 long tv_sec; /* seconds */
1467 long tv_usec; /* microsecs */
1468 } delay; /* _select() timeout */
1470 delay.tv_sec = usec / 1000000L;
1471 delay.tv_usec = usec % 1000000L;
1473 return select( 0, (long *)0, (long *)0, (long *)0, &delay );