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 condition.
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.
17 * added -T and -U option and \T and \U substitution to pass a phone
18 * number into chat script. Two are needed for some ISDN TA applications.
19 * Keith Dart <kdart@cisco.com>
22 * Added SAY keyword to send output to stderr.
23 * This allows to turn ECHO OFF and to output specific, user selected,
24 * text to give progress messages. This best works when stderr
25 * exists (i.e.: pppd in nodetach mode).
27 * Added HANGUP directives to allow for us to be called
28 * back. When HANGUP is set to NO, chat will not hangup at HUP signal.
29 * We rely on timeouts in that case.
31 * Added CLR_ABORT to clear previously set ABORT string. This has been
32 * dictated by the HANGUP above as "NO CARRIER" (for example) must be
33 * an ABORT condition until we know the other host is going to close
34 * the connection for call back. As soon as we have completed the
35 * first stage of the call back sequence, "NO CARRIER" is a valid, non
36 * fatal string. As soon as we got called back (probably get "CONNECT"),
37 * we should re-arm the ABORT "NO CARRIER". Hence the CLR_ABORT command.
38 * Note that CLR_ABORT packs the abort_strings[] array so that we do not
39 * have unused entries not being reclaimed.
41 * In the same vein as above, added CLR_REPORT keyword.
43 * Allow for comments. Line starting with '#' are comments and are
44 * ignored. If a '#' is to be expected as the first character, the
45 * expect string must be quoted.
48 * Francis Demierre <Francis@SwissMail.Com>
49 * Thu May 15 17:15:40 MET DST 1997
52 * Added -r "report file" switch & REPORT keyword.
53 * Robert Geer <bgeer@xmission.com>
55 * Added -s "use stderr" and -S "don't use syslog" switches.
57 * Karl O. Pinc <kop@meme.com>
60 * Added -e "echo" switch & ECHO keyword
61 * Dick Streefland <dicks@tasking.nl>
64 * Considerable updates and modifications by
65 * Al Longyear <longyear@pobox.com>
66 * Paul Mackerras <paulus@cs.anu.edu.au>
69 * The original author is:
71 * Karl Fox <karl@MorningStar.Com>
72 * Morning Star Technologies, Inc.
78 * $FreeBSD: src/usr.bin/chat/chat.c,v 1.21 2003/10/31 06:22:03 kientzle Exp $
79 * $DragonFly: src/usr.bin/chat/chat.c,v 1.11 2005/01/01 01:13:49 cpressey Exp $
82 #include <sys/cdefs.h>
83 #include <sys/types.h>
105 #define O_NONBLOCK O_NDELAY
108 #define MAX_ABORTS 50
109 #define MAX_REPORTS 50
110 #define DEFAULT_CHAT_TIMEOUT 45
119 FILE* report_fp
= (FILE *) 0;
120 char *report_file
= (char *) 0;
121 char *chat_file
= (char *) 0;
122 char *phone_num
= (char *) 0;
123 char *phone_num2
= (char *) 0;
124 int timeout
= DEFAULT_CHAT_TIMEOUT
;
126 static char blank
[] = "";
128 int have_tty_parameters
= 0;
130 #define term_parms struct termios
131 #define get_term_param(param) tcgetattr(0, param)
132 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
133 struct termios saved_tty_parameters
;
135 char *abort_string
[MAX_ABORTS
], *fail_reason
= (char *)0,
137 int n_aborts
= 0, abort_next
= 0, timeout_next
= 0, echo_next
= 0;
138 int clear_abort_next
= 0;
140 char *report_string
[MAX_REPORTS
] ;
141 char report_buffer
[50] ;
142 int n_reports
= 0, report_next
= 0, report_gathering
= 0 ;
143 int clear_report_next
= 0;
145 int say_next
= 0, hup_next
= 0;
147 void *dup_mem(void *b
, size_t c
);
148 void *copy_of(char *s
);
149 static void usage(void);
150 void chat_logf(const char *fmt
, ...);
151 void fatal(int code
, const char *fmt
, ...);
152 SIGTYPE
sigalrm(int signo
);
153 SIGTYPE
sigint(int signo
);
154 SIGTYPE
sigterm(int signo
);
155 SIGTYPE
sighup(int signo
);
157 void set_tty_parameters(void);
158 void echo_stderr(int);
159 void break_sequence(void);
160 void terminate(int status
);
161 void do_file(char *chatfile
);
162 int get_string(char *string
);
163 int put_string(char *s
);
164 int write_char(int c
);
167 void chat_send(char *s
);
168 char *character(int c
);
169 void chat_expect(char *s
);
170 char *clean(char *s
, int sending
);
171 void pack_array(char **array
, int end
);
172 char *expect_strtok(char *, const char *);
173 int vfmtmsg(char *, int, const char *, va_list); /* vsprintf++ */
176 dup_mem(void *b
, size_t c
)
178 void *ans
= malloc (c
);
180 fatal(2, "memory error!");
189 return dup_mem (s
, strlen (s
) + 1);
193 * chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]
194 * [-T phone-number] [-U phone-number2] [chat-script]
195 * where chat-script has the form:
196 * [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]
198 * Perform a UUCP-dialer-like chat script on stdin and stdout.
201 main(int argc
, char *argv
[])
207 while ((option
= getopt(argc
, argv
, "ef:r:sSt:T:U:vV")) != -1) {
214 if (chat_file
!= NULL
)
216 chat_file
= copy_of(optarg
);
220 if (report_fp
!= NULL
)
222 if (report_file
!= NULL
)
224 report_file
= copy_of(optarg
);
225 report_fp
= fopen(report_file
, "a");
226 if (report_fp
!= NULL
) {
228 fprintf(report_fp
, "Opening \"%s\"...\n", report_file
);
230 fatal(2, "cannot open \"%s\" for appending", report_file
);
242 timeout
= atoi(optarg
);
246 if (phone_num
!= NULL
)
248 phone_num
= copy_of(optarg
);
252 if (phone_num2
!= NULL
)
254 phone_num2
= copy_of(optarg
);
275 * Default the report file to the stderr location
277 if (report_fp
== NULL
)
281 openlog("chat", LOG_PID
| LOG_NDELAY
, LOG_LOCAL2
);
284 setlogmask(LOG_UPTO(LOG_INFO
));
286 setlogmask(LOG_UPTO(LOG_WARNING
));
289 if (chat_file
!= NULL
) {
298 while (*argv
!= NULL
&& argc
> 0) {
303 if (*argv
!= NULL
&& argc
> 0) {
316 * Process a chat script when read from a file.
320 do_file(char *chatfile
)
323 char *sp
, *arg
, quote
;
327 cfp
= fopen (chatfile
, "r");
329 fatal(1, "%s -- open failed: %m", chatfile
);
334 while (fgets(buf
, STR_LEN
, cfp
) != NULL
) {
335 sp
= strchr (buf
, '\n');
342 /* lines starting with '#' are comments. If a real '#'
343 is to be expected, it should be quoted .... */
347 while (*sp
!= '\0') {
348 if (*sp
== ' ' || *sp
== '\t') {
353 if (*sp
== '"' || *sp
== '\'') {
356 while (*sp
!= quote
) {
358 fatal(1, "unterminated quote (line %d)", linect
);
368 while (*sp
!= '\0' && *sp
!= ' ' && *sp
!= '\t')
386 * We got an error parsing the command line.
392 "Usage: chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]\n"
393 " [-T phone-number] [-U phone-number2] [chat-script]\n"
394 "where chat-script has the form:\n"
395 " [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]\n");
402 * Send a message to syslog and/or stderr.
405 chat_logf(const char *fmt
, ...)
410 vfmtmsg(line
, sizeof(line
), fmt
, args
);
412 syslog(LOG_INFO
, "%s", line
);
414 fprintf(stderr
, "%s\n", line
);
418 * Print an error message and terminate.
422 fatal(int code
, const char *fmt
, ...)
427 vfmtmsg(line
, sizeof(line
), fmt
, args
);
429 syslog(LOG_ERR
, "%s", line
);
431 fprintf(stderr
, "%s\n", line
);
437 SIGTYPE
sigalrm(int signo __unused
)
442 alarmed
= 1; /* Reset alarm to avoid race window */
443 signal(SIGALRM
, sigalrm
); /* that can cause hanging in read() */
445 if ((flags
= fcntl(0, F_GETFL
, 0)) == -1)
446 fatal(2, "Can't get file mode flags on stdin: %m");
448 if (fcntl(0, F_SETFL
, flags
| O_NONBLOCK
) == -1)
449 fatal(2, "Can't set file mode flags on stdin: %m");
455 SIGTYPE
sigint(int signo __unused
)
460 SIGTYPE
sigterm(int signo __unused
)
465 SIGTYPE
sighup(int signo __unused
)
472 signal(SIGINT
, sigint
);
473 signal(SIGTERM
, sigterm
);
474 signal(SIGHUP
, sighup
);
476 set_tty_parameters();
477 signal(SIGALRM
, sigalrm
);
482 void set_tty_parameters(void)
484 #if defined(get_term_param)
487 if (get_term_param (&t
) < 0)
488 fatal(2, "Can't get terminal parameters: %m");
490 saved_tty_parameters
= t
;
491 have_tty_parameters
= 1;
493 t
.c_iflag
|= IGNBRK
| ISTRIP
| IGNPAR
;
501 if (set_term_param (&t
) < 0)
502 fatal(2, "Can't set terminal parameters: %m");
506 void break_sequence(void)
511 void terminate(int status
)
514 if (report_file
!= (char *) 0 && report_fp
!= (FILE *) NULL
) {
516 * Allow the last of the report string to be gathered before we terminate.
518 if (report_gathering
) {
522 rep_len
= strlen(report_buffer
);
523 while (rep_len
+ 1 <= sizeof(report_buffer
)) {
527 if (c
< 0 || iscntrl(c
))
529 report_buffer
[rep_len
] = c
;
532 report_buffer
[rep_len
] = 0;
533 fprintf (report_fp
, "chat: %s\n", report_buffer
);
536 fprintf (report_fp
, "Closing \"%s\".\n", report_file
);
538 report_fp
= (FILE *) NULL
;
541 #if defined(get_term_param)
542 if (have_tty_parameters
) {
543 if (set_term_param (&saved_tty_parameters
) < 0)
544 fatal(2, "Can't restore terminal parameters: %m");
552 * 'Clean up' this string.
555 clean(char *s
, int sending
)
557 char temp
[STR_LEN
], cur_chr
;
559 int add_return
= sending
;
560 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
563 /* Don't overflow buffer, leave room for chars we append later */
564 while (*s
&& s1
- temp
< (off_t
)(sizeof(temp
) - 2 - add_return
)) {
566 if (cur_chr
== '^') {
568 if (cur_chr
== '\0') {
579 if (cur_chr
!= '\\') {
585 if (cur_chr
== '\0') {
599 if (sending
&& *s
== '\0')
616 if (sending
&& phone_num
) {
617 for ( phchar
= phone_num
; *phchar
!= '\0'; phchar
++)
627 if (sending
&& phone_num2
) {
628 for ( phchar
= phone_num2
; *phchar
!= '\0'; phchar
++)
667 if (isoctal (cur_chr
)) {
671 cur_chr
|= *s
++ - '0';
674 cur_chr
|= *s
++ - '0';
678 if (cur_chr
!= 0 || sending
) {
679 if (sending
&& (cur_chr
== '\\' || cur_chr
== 0))
696 *s1
++ = '\0'; /* guarantee closure */
697 *s1
++ = '\0'; /* terminate the string */
698 return dup_mem (temp
, (size_t) (s1
- temp
)); /* may have embedded nuls */
702 * A modified version of 'strtok'. This version skips \ sequences.
706 expect_strtok (char *s
, const char *term
)
708 static char *str
= blank
;
713 * If a string was specified then do initial processing.
719 * If this is the escape flag then reset it and ignore the character.
740 * If this is not in the termination string, continue.
742 if (strchr (term
, *str
) == (char *) 0) {
748 * This is the terminator. Mark the end of the string and stop.
757 * Process the expect string
766 if (strcmp(s
, "HANGUP") == 0) {
771 if (strcmp(s
, "ABORT") == 0) {
776 if (strcmp(s
, "CLR_ABORT") == 0) {
781 if (strcmp(s
, "REPORT") == 0) {
786 if (strcmp(s
, "CLR_REPORT") == 0) {
791 if (strcmp(s
, "TIMEOUT") == 0) {
796 if (strcmp(s
, "ECHO") == 0) {
801 if (strcmp(s
, "SAY") == 0) {
807 * Fetch the expect and reply string.
810 expect
= expect_strtok (s
, "-");
813 if (expect
== (char *) 0)
816 reply
= expect_strtok (s
, "-");
819 * Handle the expect string. If successful then exit.
821 if (get_string (expect
))
825 * If there is a sub-reply string then send it. Otherwise any condition
828 if (reply
== (char *) 0 || exit_code
!= 3)
835 * The expectation did not occur. This is terminal.
838 chat_logf("Failed (%s)", fail_reason
);
841 terminate(exit_code
);
845 * Translate the input character to the appropriate string for printing
852 static char string
[10];
855 meta
= (c
& 0x80) ? "M-" : "";
859 sprintf(string
, "%s^%c", meta
, (int)c
+ '@');
861 sprintf(string
, "%s^?", meta
);
863 sprintf(string
, "%s%c", meta
, c
);
869 * process the reply string
877 write(STDERR_FILENO
, s
, strlen(s
));
884 if (strcmp(s
, "OFF") == 0)
885 signal(SIGHUP
, SIG_IGN
);
887 signal(SIGHUP
, sighup
);
893 echo
= (strcmp(s
, "ON") == 0);
902 if (n_aborts
>= MAX_ABORTS
)
903 fatal(2, "Too many ABORT strings");
907 if (strlen(s1
) > strlen(s
)
908 || strlen(s1
) + 1 > sizeof(fail_buffer
))
909 fatal(1, "Illegal or too-long ABORT string ('%v')", s
);
911 abort_string
[n_aborts
++] = s1
;
914 chat_logf("abort on (%v)", s
);
918 if (clear_abort_next
) {
924 clear_abort_next
= 0;
928 if (strlen(s1
) > strlen(s
)
929 || strlen(s1
) + 1 > sizeof(fail_buffer
))
930 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s
);
933 for (i
=0; i
< n_aborts
; i
++) {
934 if ( strcmp(s1
,abort_string
[i
]) == 0 ) {
935 free(abort_string
[i
]);
936 abort_string
[i
] = NULL
;
940 chat_logf("clear abort on (%v)", s
);
945 pack_array(abort_string
,old_max
);
953 if (n_reports
>= MAX_REPORTS
)
954 fatal(2, "Too many REPORT strings");
958 if (strlen(s1
) > strlen(s
) || strlen(s1
) > sizeof fail_buffer
- 1)
959 fatal(1, "Illegal or too-long REPORT string ('%v')", s
);
961 report_string
[n_reports
++] = s1
;
964 chat_logf("report (%v)", s
);
968 if (clear_report_next
) {
974 clear_report_next
= 0;
978 if (strlen(s1
) > strlen(s
) || strlen(s1
) > sizeof fail_buffer
- 1)
979 fatal(1, "Illegal or too-long REPORT string ('%v')", s
);
982 for (i
=0; i
< n_reports
; i
++) {
983 if ( strcmp(s1
,report_string
[i
]) == 0 ) {
984 free(report_string
[i
]);
985 report_string
[i
] = NULL
;
989 chat_logf("clear report (%v)", s
);
994 pack_array(report_string
,old_max
);
1004 timeout
= DEFAULT_CHAT_TIMEOUT
;
1007 chat_logf("timeout set to %d seconds", timeout
);
1012 if (strcmp(s
, "EOT") == 0)
1013 s
= strdup("^D\\c");
1014 else if (strcmp(s
, "BREAK") == 0)
1015 s
= strdup("\\K\\c");
1027 status
= read(STDIN_FILENO
, &c
, 1);
1031 return ((int)c
& 0x7F);
1034 chat_logf("warning: read() on stdin returned %d", status
);
1037 if ((status
= fcntl(0, F_GETFL
, 0)) == -1)
1038 fatal(2, "Can't get file mode flags on stdin: %m");
1040 if (fcntl(0, F_SETFL
, status
& ~O_NONBLOCK
) == -1)
1041 fatal(2, "Can't set file mode flags on stdin: %m");
1052 usleep(10000); /* inter-character typing delay (?) */
1054 status
= write(STDOUT_FILENO
, &ch
, 1);
1061 chat_logf("warning: write() on stdout returned %d", status
);
1064 if ((status
= fcntl(0, F_GETFL
, 0)) == -1)
1065 fatal(2, "Can't get file mode flags on stdin, %m");
1067 if (fcntl(0, F_SETFL
, status
& ~O_NONBLOCK
) == -1)
1068 fatal(2, "Can't set file mode flags on stdin: %m");
1077 if (alarmed
|| put_char(c
) < 0) {
1082 if (errno
== EINTR
|| errno
== EWOULDBLOCK
)
1083 chat_logf(" -- write timed out");
1085 chat_logf(" -- write failed: %m");
1099 chat_logf("send (%v)", quiet
? "??????" : s
);
1101 alarm(timeout
); alarmed
= 0;
1107 if (!write_char (c
))
1123 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1127 if (!write_char (c
))
1139 * Echo a character to stderr.
1140 * When called with -1, a '\n' character is generated when
1141 * the cursor is not at the beginning of a line.
1150 case '\r': /* ignore '\r' */
1157 write(STDERR_FILENO
, "\n", 1);
1162 write(STDERR_FILENO
, s
, strlen(s
));
1169 * 'Wait for' this string to appear on this file descriptor.
1172 get_string(char *string
)
1177 char *s
= temp
, *end
= s
+ STR_LEN
;
1178 char *logged
= temp
;
1180 fail_reason
= (char *)0;
1182 if (strlen(string
) > STR_LEN
) {
1183 chat_logf("expect string is too long");
1188 string
= clean(string
, 0);
1189 len
= strlen(string
);
1190 minlen
= (len
> sizeof(fail_buffer
)? len
: sizeof(fail_buffer
)) - 1;
1193 chat_logf("expect (%v)", string
);
1197 chat_logf("got it");
1204 while ( ! alarmed
&& (c
= get_char()) >= 0) {
1205 int n
, abort_len
, report_len
;
1209 if (verbose
&& c
== '\n') {
1211 chat_logf(""); /* blank line */
1213 chat_logf("%0.*v", s
- logged
, logged
);
1219 if (verbose
&& s
>= logged
+ 80) {
1220 chat_logf("%0.*v", s
- logged
, logged
);
1226 fputc( '\n', stderr
);
1228 fprintf( stderr
, "%s", character(c
) );
1231 if (!report_gathering
) {
1232 for (n
= 0; n
< n_reports
; ++n
) {
1233 if ((report_string
[n
] != (char*) NULL
) &&
1234 s
- temp
>= (report_len
= strlen(report_string
[n
])) &&
1235 strncmp(s
- report_len
, report_string
[n
], report_len
) == 0) {
1236 time_t time_now
= time ((time_t*) NULL
);
1237 struct tm
* tm_now
= localtime (&time_now
);
1239 strftime (report_buffer
, 20, "%b %d %H:%M:%S ", tm_now
);
1240 strcat (report_buffer
, report_string
[n
]);
1242 report_string
[n
] = (char *) NULL
;
1243 report_gathering
= 1;
1250 int rep_len
= strlen (report_buffer
);
1251 report_buffer
[rep_len
] = c
;
1252 report_buffer
[rep_len
+ 1] = '\0';
1255 report_gathering
= 0;
1256 fprintf (report_fp
, "chat: %s\n", report_buffer
);
1260 if ((size_t)(s
- temp
) >= len
&&
1261 c
== string
[len
- 1] &&
1262 strncmp(s
- len
, string
, len
) == 0) {
1265 chat_logf("%0.*v", s
- logged
, logged
);
1266 chat_logf(" -- got it\n");
1274 for (n
= 0; n
< n_aborts
; ++n
) {
1275 if (s
- temp
>= (abort_len
= strlen(abort_string
[n
])) &&
1276 strncmp(s
- abort_len
, abort_string
[n
], abort_len
) == 0) {
1279 chat_logf("%0.*v", s
- logged
, logged
);
1280 chat_logf(" -- failed");
1286 strcpy(fail_reason
= fail_buffer
, abort_string
[n
]);
1292 if (logged
< s
- minlen
) {
1293 chat_logf("%0.*v", s
- logged
, logged
);
1297 memmove(temp
, s
, minlen
);
1298 logged
= temp
+ (logged
- s
);
1302 if (alarmed
&& verbose
)
1303 chat_logf("warning: alarm synchronization problem");
1308 if (verbose
&& printed
) {
1310 chat_logf(" -- read timed out");
1312 chat_logf(" -- read failed: %m");
1321 pack_array(char **array
, int end
)
1325 for (i
= 0; i
< end
; i
++) {
1326 if (array
[i
] == NULL
) {
1327 for (j
= i
+1; j
< end
; ++j
)
1328 if (array
[j
] != NULL
)
1329 array
[i
++] = array
[j
];
1330 for (; i
< end
; ++i
)
1338 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1339 * also specify the length of the output buffer, and we handle the
1340 * %m (error message) format.
1341 * Doesn't do floating-point formats.
1342 * Returns the number of chars put into buf.
1344 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1347 vfmtmsg(char *buf
, int buflen
, const char *fmt
, va_list args
)
1350 int width
, prec
, fillch
;
1351 int base
, len
, neg
, quoted
;
1352 unsigned long val
= 0;
1357 static char hexchars
[] = "0123456789abcdef";
1361 while (buflen
> 0) {
1362 for (f
= fmt
; *f
!= '%' && *f
!= 0; ++f
)
1368 memcpy(buf
, fmt
, len
);
1383 width
= va_arg(args
, int);
1386 while (isdigit(c
)) {
1387 width
= width
* 10 + c
- '0';
1394 prec
= va_arg(args
, int);
1397 while (isdigit(c
)) {
1398 prec
= prec
* 10 + c
- '0';
1409 i
= va_arg(args
, int);
1418 val
= va_arg(args
, unsigned int);
1422 val
= va_arg(args
, unsigned int);
1426 val
= (unsigned long) va_arg(args
, void *);
1431 str
= va_arg(args
, char *);
1434 num
[0] = va_arg(args
, int);
1439 str
= strerror(errno
);
1441 case 'v': /* "visible" string */
1442 case 'q': /* quoted string */
1444 p
= va_arg(args
, unsigned char *);
1445 if (fillch
== '0' && prec
> 0) {
1448 n
= strlen((char *)p
);
1449 if (prec
> 0 && prec
< n
)
1452 while (n
> 0 && buflen
> 0) {
1455 if (!quoted
&& c
>= 0x80) {
1460 if (quoted
&& (c
== '"' || c
== '\\'))
1462 if (c
< 0x20 || (0x7f <= c
&& c
< 0xa0)) {
1466 case '\t': OUTCHAR('t'); break;
1467 case '\n': OUTCHAR('n'); break;
1468 case '\b': OUTCHAR('b'); break;
1469 case '\f': OUTCHAR('f'); break;
1472 OUTCHAR(hexchars
[c
>> 4]);
1473 OUTCHAR(hexchars
[c
& 0xf]);
1490 --fmt
; /* so %z outputs %z etc. */
1495 str
= num
+ sizeof(num
);
1497 while (str
> num
+ neg
) {
1498 *--str
= hexchars
[val
% base
];
1500 if (--prec
<= 0 && val
== 0)
1512 len
= num
+ sizeof(num
) - 1 - str
;
1515 if (prec
> 0 && len
> prec
)
1521 if ((n
= width
- len
) > 0) {
1529 memcpy(buf
, str
, len
);