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 * The original author is:
26 * Karl Fox <karl@MorningStar.Com>
27 * Morning Star Technologies, Inc.
34 static char rcsid[] = "$Id: chat.c,v 1.10 1995/12/18 03:32:46 paulus Exp $";
43 #include <sys/types.h>
74 #define O_NONBLOCK O_NDELAY
77 /*************** Micro getopt() *********************************************/
78 #define OPTION(c,v) (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
79 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
80 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
81 #define OPTARG(c,v) (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
82 (_O=4,(char*)0):(char*)0)
83 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
84 #define ARG(c,v) (c?(--c,*v++):(char*)0)
86 static int _O = 0; /* Internal state */
87 /*************** Micro getopt() *********************************************/
92 #define MAX_REPORTS 50
93 #define DEFAULT_CHAT_TIMEOUT 45
100 FILE* report_fp = (FILE *) 0;
101 char *report_file = (char *) 0;
102 char *chat_file = (char *) 0;
103 int timeout = DEFAULT_CHAT_TIMEOUT;
105 int have_tty_parameters = 0;
108 #define term_parms struct termio
109 #define get_term_param(param) ioctl(0, TCGETA, param)
110 #define set_term_param(param) ioctl(0, TCSETA, param)
111 struct termio saved_tty_parameters;
115 #define term_parms struct termios
116 #define get_term_param(param) tcgetattr(0, param)
117 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
118 struct termios saved_tty_parameters;
121 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
123 int n_aborts = 0, abort_next = 0, timeout_next = 0;
125 char *report_string[MAX_REPORTS] ;
126 char report_buffer[50] ;
127 int n_reports = 0, report_next = 0, report_gathering = 0 ;
129 void *dup_mem __P((void *b, size_t c));
130 void *copy_of __P((char *s));
131 void usage __P((void));
132 void logf __P((const char *str));
133 void logflush __P((void));
134 void fatal __P((const char *msg));
135 void sysfatal __P((const char *msg));
136 SIGTYPE sigalrm __P((int signo));
137 SIGTYPE sigint __P((int signo));
138 SIGTYPE sigterm __P((int signo));
139 SIGTYPE sighup __P((int signo));
140 void unalarm __P((void));
141 void init __P((void));
142 void set_tty_parameters __P((void));
143 void break_sequence __P((void));
144 void terminate __P((int status));
145 void do_file __P((char *chat_file));
146 int get_string __P((register char *string));
147 int put_string __P((register char *s));
148 int write_char __P((int c));
149 int put_char __P((int c));
150 int get_char __P((void));
151 void chat_send __P((register char *s));
152 char *character __P((int c));
153 void chat_expect __P((register char *s));
154 char *clean __P((register char *s, int sending));
155 void break_sequence __P((void));
156 void terminate __P((int status));
157 void die __P((void));
163 void *ans = malloc (c);
166 fatal ("memory error!\n");
175 return dup_mem (s, strlen (s) + 1);
179 * chat [ -v ] [ -t timeout ] [ -f chat-file ] [ -r report-file ] \
180 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
182 * Perform a UUCP-dialer-like chat script on stdin and stdout.
192 program_name = *argv;
195 while (option = OPTION(argc, argv))
208 if (arg = OPTARG(argc, argv))
210 chat_file = copy_of(arg);
219 if (arg = OPTARG(argc, argv))
230 arg = OPTARG (argc, argv);
233 if (report_fp != NULL)
237 report_file = copy_of (arg);
238 report_fp = fopen (report_file, "a");
239 if (report_fp != NULL)
243 fprintf (report_fp, "Opening \"%s\"...\n",
257 * Default the report file to the stderr location
259 if (report_fp == NULL)
265 openlog("chat", LOG_PID);
267 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
271 setlogmask(LOG_UPTO(LOG_INFO));
275 setlogmask(LOG_UPTO(LOG_WARNING));
281 if (chat_file != NULL)
283 arg = ARG(argc, argv);
295 while (arg = ARG(argc, argv))
299 if (arg = ARG(argc, argv))
310 * Process a chat script when read from a file.
313 void do_file (chat_file)
316 int linect, len, sendflg;
317 char *sp, *arg, quote;
321 cfp = fopen (chat_file, "r");
324 syslog (LOG_ERR, "%s -- open failed: %m", chat_file);
331 while (fgets(buf, STR_LEN, cfp) != NULL)
333 sp = strchr (buf, '\n');
343 if (*sp == ' ' || *sp == '\t')
349 if (*sp == '"' || *sp == '\'')
357 syslog (LOG_ERR, "unterminated quote (line %d)",
374 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
400 * We got an error parsing the command line.
405 Usage: %s [-v] [-t timeout] [-r report-file] {-f chat-file | chat-script}\n",
416 p = line + strlen(line);
419 if (str[strlen(str)-1] == '\n')
421 syslog (LOG_INFO, "%s", line);
430 syslog(LOG_INFO, "%s", line);
436 * Terminate with an error.
444 * Print an error message and terminate.
450 syslog(LOG_ERR, "%s", msg);
455 * Print an error message along with the system error message and
462 syslog(LOG_ERR, "%s: %m", msg);
468 SIGTYPE sigalrm(signo)
474 alarmed = 1; /* Reset alarm to avoid race window */
475 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
478 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
480 sysfatal("Can't get file mode flags on stdin");
484 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
486 sysfatal("Can't set file mode flags on stdin");
492 syslog(LOG_INFO, "alarm");
500 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
502 sysfatal("Can't get file mode flags on stdin");
506 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
508 sysfatal("Can't set file mode flags on stdin");
513 SIGTYPE sigint(signo)
519 SIGTYPE sigterm(signo)
525 SIGTYPE sighup(signo)
533 signal(SIGINT, sigint);
534 signal(SIGTERM, sigterm);
535 signal(SIGHUP, sighup);
537 set_tty_parameters();
538 signal(SIGALRM, sigalrm);
543 void set_tty_parameters()
545 #if defined(get_term_param)
548 if (get_term_param (&t) < 0)
550 sysfatal("Can't get terminal parameters");
553 saved_tty_parameters = t;
554 have_tty_parameters = 1;
556 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
564 if (set_term_param (&t) < 0)
566 sysfatal("Can't set terminal parameters");
571 void break_sequence()
578 void terminate(status)
581 if (report_file != (char *) 0 && report_fp != (FILE *) NULL)
585 fprintf (report_fp, "Closing \"%s\".\n", report_file);
588 report_fp = (FILE *) NULL;
591 #if defined(get_term_param)
592 if (have_tty_parameters)
594 if (set_term_param (&saved_tty_parameters) < 0)
596 syslog(LOG_ERR, "Can't restore terminal parameters: %m");
606 * 'Clean up' this string.
608 char *clean(s, sending)
612 char temp[STR_LEN], cur_chr;
614 int add_return = sending;
615 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
661 if (sending && *s == '\0')
716 if (isoctal (cur_chr))
722 cur_chr |= *s++ - '0';
726 cur_chr |= *s++ - '0';
730 if (cur_chr != 0 || sending)
732 if (sending && (cur_chr == '\\' || cur_chr == 0))
755 *s1++ = '\0'; /* guarantee closure */
756 *s1++ = '\0'; /* terminate the string */
757 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
761 * A modified version of 'strtok'. This version skips \ sequences.
764 char *expect_strtok (s, term)
767 static char *str = "";
768 static int escape_flag = 0;
771 * If a string was specified then do initial processing.
783 * Look for the terminator sequence.
784 * If the escape flag is set then this character is not the terminator.
785 * We assume that term does not contain the backslash character.
787 if (escape_flag || strchr (term, *str) == (char *) 0)
789 if (result == (char *) 0)
794 if (escape_flag || *str == '\\')
796 escape_flag = !escape_flag;
803 * This is the terminator. If we have a string then this is the end of the
816 * Process the expect string
825 if (strcmp(s, "ABORT") == 0)
831 if (strcmp(s, "REPORT") == 0)
837 if (strcmp(s, "TIMEOUT") == 0)
843 * Fetch the expect and reply string.
847 expect = expect_strtok (s, "-");
850 if (expect == (char *) 0)
855 reply = expect_strtok (s, "-");
857 * Handle the expect string. If successful then exit.
859 if (get_string (expect))
864 * If there is a sub-reply string then send it. Otherwise any condition
867 if (reply == (char *) 0 || exit_code != 3)
875 * The expectation did not occur. This is terminal.
879 syslog(LOG_INFO, "Failed (%s)", fail_reason);
883 syslog(LOG_INFO, "Failed");
885 terminate(exit_code);
889 * Translate the input character to the appropriate string for printing
896 static char string[10];
899 meta = (c & 0x80) ? "M-" : "";
904 sprintf(string, "%s^%c", meta, (int)c + '@');
910 sprintf(string, "%s^?", meta);
914 sprintf(string, "%s%c", meta, c);
922 * process the reply string
933 if (n_aborts >= MAX_ABORTS)
935 fatal("Too many ABORT strings");
940 if (strlen(s1) > strlen(s)
941 || strlen(s1) + 1 > sizeof(fail_buffer))
943 syslog(LOG_WARNING, "Illegal or too-long ABORT string ('%s')", s);
947 abort_string[n_aborts++] = s1;
953 for (s1 = s; *s1; ++s1)
955 logf(character(*s1));
968 if (n_reports >= MAX_REPORTS)
970 fatal("Too many REPORT strings");
975 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
977 syslog(LOG_WARNING, "Illegal or too-long REPORT string ('%s')", s);
981 report_string[n_reports++] = s1;
989 logf(character(*s1));
1004 timeout = DEFAULT_CHAT_TIMEOUT;
1009 syslog(LOG_INFO, "timeout set to %d seconds", timeout);
1014 if (strcmp(s, "EOT") == 0)
1020 if (strcmp(s, "BREAK") == 0)
1028 syslog(LOG_INFO, "Failed");
1038 status = read(0, &c, 1);
1043 return ((int)c & 0x7F);
1046 syslog(LOG_WARNING, "warning: read() on stdin returned %d",
1050 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1052 sysfatal("Can't get file mode flags on stdin");
1056 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1058 sysfatal("Can't set file mode flags on stdin");
1072 usleep(10000); /* inter-character typing delay (?) */
1074 status = write(1, &ch, 1);
1082 syslog(LOG_WARNING, "warning: write() on stdout returned %d",
1086 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1088 sysfatal("Can't get file mode flags on stdin");
1092 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1094 sysfatal("Can't set file mode flags on stdin");
1105 if (alarmed || put_char(c) < 0)
1114 if (errno == EINTR || errno == EWOULDBLOCK)
1116 syslog(LOG_INFO, " -- write timed out");
1120 syslog(LOG_INFO, " -- write failed: %m");
1143 register char *s1 = s;
1145 for (s1 = s; *s1; ++s1)
1147 logf(character(*s1));
1154 alarm(timeout); alarmed = 0;
1158 register char c = *s++;
1162 if (!write_char (c))
1181 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1185 if (!write_char (c))
1197 * 'Wait for' this string to appear on this file descriptor.
1199 int get_string(string)
1200 register char *string;
1203 int c, printed = 0, len, minlen;
1204 register char *s = temp, *end = s + STR_LEN;
1206 fail_reason = (char *)0;
1207 string = clean(string, 0);
1208 len = strlen(string);
1209 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1217 for (s1 = string; *s1; ++s1)
1219 logf(character(*s1));
1227 syslog(LOG_INFO, "expect string is too long");
1236 syslog(LOG_INFO, "got it");
1245 while ( ! alarmed && (c = get_char()) >= 0)
1247 int n, abort_len, report_len;
1262 if (c == '\n') fputc( '\n', stderr );
1263 else if (c != '\r') fprintf( stderr, "%s", character(c) );
1268 if (s - temp >= len &&
1269 c == string[len - 1] &&
1270 strncmp(s - len, string, len) == 0)
1274 logf(" -- got it\n");
1282 for (n = 0; n < n_aborts; ++n)
1284 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1285 strncmp(s - abort_len, abort_string[n], abort_len) == 0)
1289 logf(" -- failed\n");
1295 strcpy(fail_reason = fail_buffer, abort_string[n]);
1300 if (!report_gathering)
1302 for (n = 0; n < n_reports; ++n)
1304 if ((report_string[n] != (char*) NULL) &&
1305 s - temp >= (report_len = strlen(report_string[n])) &&
1306 strncmp(s - report_len, report_string[n], report_len) == 0)
1308 time_t time_now = time ((time_t*) NULL);
1309 struct tm* tm_now = localtime (&time_now);
1311 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1312 strcat (report_buffer, report_string[n]);
1314 report_string[n] = (char *) NULL;
1315 report_gathering = 1;
1324 int rep_len = strlen (report_buffer);
1325 report_buffer[rep_len] = c;
1326 report_buffer[rep_len + 1] = '\0';
1330 report_gathering = 0;
1331 fprintf (report_fp, "chat: %s\n", report_buffer);
1337 strncpy (temp, s - minlen, minlen);
1341 if (alarmed && verbose)
1343 syslog(LOG_WARNING, "warning: alarm synchronization problem");
1349 if (verbose && printed)
1353 logf(" -- read timed out\n");
1358 syslog(LOG_INFO, " -- read failed: %m");
1368 #include <sys/types.h>
1369 #include <sys/time.h>
1372 usleep -- support routine for 4.2BSD system call emulations
1373 last edit: 29-Oct-1984 D A Gwyn
1376 extern int select();
1379 usleep( usec ) /* returns 0 if ok, else -1 */
1380 long usec; /* delay in microseconds */
1382 static struct /* `timeval' */
1384 long tv_sec; /* seconds */
1385 long tv_usec; /* microsecs */
1386 } delay; /* _select() timeout */
1388 delay.tv_sec = usec / 1000000L;
1389 delay.tv_usec = usec % 1000000L;
1391 return select( 0, (long *)0, (long *)0, (long *)0, &delay );