<net/if_poll.h>: Add license. It was based on sys/net/if_poll.c.
[dragonfly.git] / usr.bin / chat / chat.c
blob8a3ad9b159d43f94a5fde9a8a2fe1b8b93e97d56
1 /*
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.
16 * -----------------
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.
56 * June 18, 1997
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.
73 * 1760 Zollinger Road
74 * Columbus, OH 43221
75 * (614)451-1883
78 * $FreeBSD: src/usr.bin/chat/chat.c,v 1.21 2003/10/31 06:22:03 kientzle Exp $
81 #include <sys/types.h>
82 #include <sys/stat.h>
83 #include <ctype.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <signal.h>
87 #include <stdarg.h>
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <syslog.h>
92 #include <termios.h>
93 #include <time.h>
94 #include <unistd.h>
96 #define STR_LEN 1024
98 #ifndef SIGTYPE
99 #define SIGTYPE void
100 #endif
102 #ifndef O_NONBLOCK
103 #define O_NONBLOCK O_NDELAY
104 #endif
106 #define MAX_ABORTS 50
107 #define MAX_REPORTS 50
108 #define DEFAULT_CHAT_TIMEOUT 45
110 static int echo = 0;
111 static int verbose = 0;
112 static int to_log = 1;
113 static int to_stderr = 0;
114 static int Verbose = 0;
115 static int quiet = 0;
116 static int exit_code = 0;
117 static FILE* report_fp = NULL;
118 static char *report_file = NULL;
119 static char *chat_file = NULL;
120 static char *phone_num = NULL;
121 static char *phone_num2 = NULL;
122 static int timeout = DEFAULT_CHAT_TIMEOUT;
124 static char blank[] = "";
126 static int have_tty_parameters = 0;
128 #define term_parms struct termios
129 #define get_term_param(param) tcgetattr(0, param)
130 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
131 static struct termios saved_tty_parameters;
133 static char *abort_string[MAX_ABORTS], *fail_reason = NULL,
134 fail_buffer[50];
135 static int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
136 static int clear_abort_next = 0;
138 static char *report_string[MAX_REPORTS] ;
139 static char report_buffer[50] ;
140 static int n_reports = 0, report_next = 0, report_gathering = 0 ;
141 static int clear_report_next = 0;
143 static int say_next = 0, hup_next = 0;
145 static void *dup_mem(void *b, size_t c);
146 static void *copy_of(char *s);
147 static void usage(void);
148 static void chat_logf(const char *fmt, ...);
149 static void fatal(int code, const char *fmt, ...) __dead2;
150 static SIGTYPE sigalrm(int signo);
151 static SIGTYPE sigint(int signo) __dead2;
152 static SIGTYPE sigterm(int signo) __dead2;
153 static SIGTYPE sighup(int signo) __dead2;
154 static void init(void);
155 static void set_tty_parameters(void);
156 static void echo_stderr(int);
157 static void break_sequence(void);
158 static void terminate(int status) __dead2;
159 static void do_file(char *chatfile);
160 static int get_string(char *string);
161 static int put_string(char *s);
162 static int write_char(int c);
163 static int put_char(int c);
164 static int get_char(void);
165 static void chat_send(char *s);
166 static char *character(int c);
167 static void chat_expect(char *s);
168 static char *clean(char *s, int sending);
169 static void pack_array(char **array, int end);
170 static char *expect_strtok(char *, const char *);
171 static int vfmtmsg(char *, int, const char *, va_list); /* vsprintf++ */
173 static void *
174 dup_mem(void *b, size_t c)
176 void *ans = malloc (c);
177 if (!ans)
178 fatal(2, "memory error!");
180 memcpy (ans, b, c);
181 return ans;
184 static void *
185 copy_of(char *s)
187 return dup_mem (s, strlen (s) + 1);
191 * chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]
192 * [-T phone-number] [-U phone-number2] [chat-script]
193 * where chat-script has the form:
194 * [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]
196 * Perform a UUCP-dialer-like chat script on stdin and stdout.
199 main(int argc, char *argv[])
201 int option;
203 tzset();
205 while ((option = getopt(argc, argv, "ef:r:sSt:T:U:vV")) != -1) {
206 switch (option) {
207 case 'e':
208 ++echo;
209 break;
211 case 'f':
212 if (chat_file != NULL)
213 free(chat_file);
214 chat_file = copy_of(optarg);
215 break;
217 case 'r':
218 if (report_fp != NULL)
219 fclose(report_fp);
220 if (report_file != NULL)
221 free(report_file);
222 report_file = copy_of(optarg);
223 report_fp = fopen(report_file, "a");
224 if (report_fp != NULL) {
225 if (verbose)
226 fprintf(report_fp, "Opening \"%s\"...\n", report_file);
227 } else
228 fatal(2, "cannot open \"%s\" for appending", report_file);
229 break;
231 case 's':
232 ++to_stderr;
233 break;
235 case 'S':
236 to_log = 0;
237 break;
239 case 't':
240 timeout = atoi(optarg);
241 break;
243 case 'T':
244 if (phone_num != NULL)
245 free(phone_num);
246 phone_num = copy_of(optarg);
247 break;
249 case 'U':
250 if (phone_num2 != NULL)
251 free(phone_num2);
252 phone_num2 = copy_of(optarg);
253 break;
255 case 'v':
256 ++verbose;
257 break;
259 case 'V':
260 ++Verbose;
261 break;
263 default:
264 usage();
265 break;
269 argc -= optind;
270 argv += optind;
273 * Default the report file to the stderr location
275 if (report_fp == NULL)
276 report_fp = stderr;
278 if (to_log) {
279 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
281 if (verbose)
282 setlogmask(LOG_UPTO(LOG_INFO));
283 else
284 setlogmask(LOG_UPTO(LOG_WARNING));
287 if (chat_file != NULL) {
288 if (*argv != NULL)
289 usage();
290 else {
291 init();
292 do_file(chat_file);
294 } else {
295 init();
296 while (*argv != NULL && argc > 0) {
297 chat_expect(*argv);
298 argv++;
299 argc--;
301 if (*argv != NULL && argc > 0) {
302 chat_send(*argv);
303 argv++;
304 argc--;
309 terminate(0);
310 return 0;
314 * Process a chat script when read from a file.
317 static void
318 do_file(char *chatfile)
320 int linect, sendflg;
321 char *sp, *arg, quote;
322 char buf [STR_LEN];
323 FILE *cfp;
325 cfp = fopen (chatfile, "r");
326 if (cfp == NULL)
327 fatal(1, "%s -- open failed: %m", chatfile);
329 linect = 0;
330 sendflg = 0;
332 while (fgets(buf, STR_LEN, cfp) != NULL) {
333 sp = strchr (buf, '\n');
334 if (sp)
335 *sp = '\0';
337 linect++;
338 sp = buf;
340 /* lines starting with '#' are comments. If a real '#'
341 is to be expected, it should be quoted .... */
342 if ( *sp == '#' )
343 continue;
345 while (*sp != '\0') {
346 if (*sp == ' ' || *sp == '\t') {
347 ++sp;
348 continue;
351 if (*sp == '"' || *sp == '\'') {
352 quote = *sp++;
353 arg = sp;
354 while (*sp != quote) {
355 if (*sp == '\0')
356 fatal(1, "unterminated quote (line %d)", linect);
358 if (*sp++ == '\\') {
359 if (*sp != '\0')
360 ++sp;
364 else {
365 arg = sp;
366 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
367 ++sp;
370 if (*sp != '\0')
371 *sp++ = '\0';
373 if (sendflg)
374 chat_send (arg);
375 else
376 chat_expect (arg);
377 sendflg = !sendflg;
380 fclose (cfp);
384 * We got an error parsing the command line.
386 static void
387 usage(void)
389 fprintf(stderr,
390 "Usage: chat [-esSvV] [-f chat-file] [-r report-file] [-t timeout]\n"
391 " [-T phone-number] [-U phone-number2] [chat-script]\n"
392 "where chat-script has the form:\n"
393 " [...[[expect[-send[-expect...]] send expect[-send[-expect]] ...]]]\n");
394 exit(1);
397 static char line[1024];
400 * Send a message to syslog and/or stderr.
402 static void
403 chat_logf(const char *fmt, ...)
405 va_list args;
407 va_start(args, fmt);
408 vfmtmsg(line, sizeof(line), fmt, args);
409 if (to_log)
410 syslog(LOG_INFO, "%s", line);
411 if (to_stderr)
412 fprintf(stderr, "%s\n", line);
416 * Print an error message and terminate.
419 static void
420 fatal(int code, const char *fmt, ...)
422 va_list args;
424 va_start(args, fmt);
425 vfmtmsg(line, sizeof(line), fmt, args);
426 if (to_log)
427 syslog(LOG_ERR, "%s", line);
428 if (to_stderr)
429 fprintf(stderr, "%s\n", line);
430 terminate(code);
433 static int alarmed = 0;
435 static SIGTYPE sigalrm(int signo __unused)
437 int flags;
439 alarm(1);
440 alarmed = 1; /* Reset alarm to avoid race window */
441 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
443 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
444 fatal(2, "Can't get file mode flags on stdin: %m");
446 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
447 fatal(2, "Can't set file mode flags on stdin: %m");
449 if (verbose)
450 chat_logf("alarm");
453 static SIGTYPE sigint(int signo __unused)
455 fatal(2, "SIGINT");
458 static SIGTYPE sigterm(int signo __unused)
460 fatal(2, "SIGTERM");
463 static SIGTYPE sighup(int signo __unused)
465 fatal(2, "SIGHUP");
468 static void init(void)
470 signal(SIGINT, sigint);
471 signal(SIGTERM, sigterm);
472 signal(SIGHUP, sighup);
474 set_tty_parameters();
475 signal(SIGALRM, sigalrm);
476 alarm(0);
477 alarmed = 0;
480 static void set_tty_parameters(void)
482 #if defined(get_term_param)
483 term_parms t;
485 if (get_term_param (&t) < 0)
486 fatal(2, "Can't get terminal parameters: %m");
488 saved_tty_parameters = t;
489 have_tty_parameters = 1;
491 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
492 t.c_oflag = 0;
493 t.c_lflag = 0;
494 t.c_cc[VERASE] =
495 t.c_cc[VKILL] = 0;
496 t.c_cc[VMIN] = 1;
497 t.c_cc[VTIME] = 0;
499 if (set_term_param (&t) < 0)
500 fatal(2, "Can't set terminal parameters: %m");
501 #endif
504 static void break_sequence(void)
506 tcsendbreak (0, 0);
509 static void terminate(int status)
511 echo_stderr(-1);
512 if (report_file != NULL && report_fp != NULL) {
514 * Allow the last of the report string to be gathered before we terminate.
516 if (report_gathering) {
517 int c;
518 size_t rep_len;
520 rep_len = strlen(report_buffer);
521 while (rep_len + 1 <= sizeof(report_buffer)) {
522 alarm(1);
523 c = get_char();
524 alarm(0);
525 if (c < 0 || iscntrl(c))
526 break;
527 report_buffer[rep_len] = c;
528 ++rep_len;
530 report_buffer[rep_len] = 0;
531 fprintf (report_fp, "chat: %s\n", report_buffer);
533 if (verbose)
534 fprintf (report_fp, "Closing \"%s\".\n", report_file);
535 fclose (report_fp);
536 report_fp = NULL;
539 #if defined(get_term_param)
540 if (have_tty_parameters) {
541 if (set_term_param (&saved_tty_parameters) < 0)
542 fatal(2, "Can't restore terminal parameters: %m");
544 #endif
546 exit(status);
550 * 'Clean up' this string.
552 static char *
553 clean(char *s, int sending)
555 char temp[STR_LEN], cur_chr;
556 char *s1, *phchar;
557 int add_return = sending;
558 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
560 s1 = temp;
561 /* Don't overflow buffer, leave room for chars we append later */
562 while (*s && s1 - temp < (off_t)(sizeof(temp) - 2 - add_return)) {
563 cur_chr = *s++;
564 if (cur_chr == '^') {
565 cur_chr = *s++;
566 if (cur_chr == '\0') {
567 *s1++ = '^';
568 break;
570 cur_chr &= 0x1F;
571 if (cur_chr != 0) {
572 *s1++ = cur_chr;
574 continue;
577 if (cur_chr != '\\') {
578 *s1++ = cur_chr;
579 continue;
582 cur_chr = *s++;
583 if (cur_chr == '\0') {
584 if (sending) {
585 *s1++ = '\\';
586 *s1++ = '\\';
588 break;
591 switch (cur_chr) {
592 case 'b':
593 *s1++ = '\b';
594 break;
596 case 'c':
597 if (sending && *s == '\0')
598 add_return = 0;
599 else
600 *s1++ = cur_chr;
601 break;
603 case '\\':
604 case 'K':
605 case 'p':
606 case 'd':
607 if (sending)
608 *s1++ = '\\';
610 *s1++ = cur_chr;
611 break;
613 case 'T':
614 if (sending && phone_num) {
615 for ( phchar = phone_num; *phchar != '\0'; phchar++)
616 *s1++ = *phchar;
618 else {
619 *s1++ = '\\';
620 *s1++ = 'T';
622 break;
624 case 'U':
625 if (sending && phone_num2) {
626 for ( phchar = phone_num2; *phchar != '\0'; phchar++)
627 *s1++ = *phchar;
629 else {
630 *s1++ = '\\';
631 *s1++ = 'U';
633 break;
635 case 'q':
636 quiet = 1;
637 break;
639 case 'r':
640 *s1++ = '\r';
641 break;
643 case 'n':
644 *s1++ = '\n';
645 break;
647 case 's':
648 *s1++ = ' ';
649 break;
651 case 't':
652 *s1++ = '\t';
653 break;
655 case 'N':
656 if (sending) {
657 *s1++ = '\\';
658 *s1++ = '\0';
660 else
661 *s1++ = 'N';
662 break;
664 default:
665 if (isoctal (cur_chr)) {
666 cur_chr &= 0x07;
667 if (isoctal (*s)) {
668 cur_chr <<= 3;
669 cur_chr |= *s++ - '0';
670 if (isoctal (*s)) {
671 cur_chr <<= 3;
672 cur_chr |= *s++ - '0';
676 if (cur_chr != 0 || sending) {
677 if (sending && (cur_chr == '\\' || cur_chr == 0))
678 *s1++ = '\\';
679 *s1++ = cur_chr;
681 break;
684 if (sending)
685 *s1++ = '\\';
686 *s1++ = cur_chr;
687 break;
691 if (add_return)
692 *s1++ = '\r';
694 *s1++ = '\0'; /* guarantee closure */
695 *s1++ = '\0'; /* terminate the string */
696 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
700 * A modified version of 'strtok'. This version skips \ sequences.
703 static char *
704 expect_strtok (char *s, const char *term)
706 static char *str = blank;
707 int escape_flag = 0;
708 char *result;
711 * If a string was specified then do initial processing.
713 if (s)
714 str = s;
717 * If this is the escape flag then reset it and ignore the character.
719 if (*str)
720 result = str;
721 else
722 result = NULL;
724 while (*str) {
725 if (escape_flag) {
726 escape_flag = 0;
727 ++str;
728 continue;
731 if (*str == '\\') {
732 ++str;
733 escape_flag = 1;
734 continue;
738 * If this is not in the termination string, continue.
740 if (strchr (term, *str) == NULL) {
741 ++str;
742 continue;
746 * This is the terminator. Mark the end of the string and stop.
748 *str++ = '\0';
749 break;
751 return (result);
755 * Process the expect string
758 static void
759 chat_expect(char *s)
761 char *expect;
762 char *reply;
764 if (strcmp(s, "HANGUP") == 0) {
765 ++hup_next;
766 return;
769 if (strcmp(s, "ABORT") == 0) {
770 ++abort_next;
771 return;
774 if (strcmp(s, "CLR_ABORT") == 0) {
775 ++clear_abort_next;
776 return;
779 if (strcmp(s, "REPORT") == 0) {
780 ++report_next;
781 return;
784 if (strcmp(s, "CLR_REPORT") == 0) {
785 ++clear_report_next;
786 return;
789 if (strcmp(s, "TIMEOUT") == 0) {
790 ++timeout_next;
791 return;
794 if (strcmp(s, "ECHO") == 0) {
795 ++echo_next;
796 return;
799 if (strcmp(s, "SAY") == 0) {
800 ++say_next;
801 return;
805 * Fetch the expect and reply string.
807 for (;;) {
808 expect = expect_strtok (s, "-");
809 s = NULL;
811 if (expect == NULL)
812 return;
814 reply = expect_strtok (s, "-");
817 * Handle the expect string. If successful then exit.
819 if (get_string (expect))
820 return;
823 * If there is a sub-reply string then send it. Otherwise any condition
824 * is terminal.
826 if (reply == NULL || exit_code != 3)
827 break;
829 chat_send (reply);
833 * The expectation did not occur. This is terminal.
835 if (fail_reason)
836 chat_logf("Failed (%s)", fail_reason);
837 else
838 chat_logf("Failed");
839 terminate(exit_code);
843 * Translate the input character to the appropriate string for printing
844 * the data.
847 static char *
848 character(int c)
850 static char string[10];
851 const char *meta;
853 meta = (c & 0x80) ? "M-" : "";
854 c &= 0x7F;
856 if (c < 32)
857 sprintf(string, "%s^%c", meta, (int)c + '@');
858 else if (c == 127)
859 sprintf(string, "%s^?", meta);
860 else
861 sprintf(string, "%s%c", meta, c);
863 return (string);
867 * process the reply string
869 static void
870 chat_send(char *s)
872 if (say_next) {
873 say_next = 0;
874 s = clean(s,0);
875 write(STDERR_FILENO, s, strlen(s));
876 free(s);
877 return;
880 if (hup_next) {
881 hup_next = 0;
882 if (strcmp(s, "OFF") == 0)
883 signal(SIGHUP, SIG_IGN);
884 else
885 signal(SIGHUP, sighup);
886 return;
889 if (echo_next) {
890 echo_next = 0;
891 echo = (strcmp(s, "ON") == 0);
892 return;
895 if (abort_next) {
896 char *s1;
898 abort_next = 0;
900 if (n_aborts >= MAX_ABORTS)
901 fatal(2, "Too many ABORT strings");
903 s1 = clean(s, 0);
905 if (strlen(s1) > strlen(s)
906 || strlen(s1) + 1 > sizeof(fail_buffer))
907 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
909 abort_string[n_aborts++] = s1;
911 if (verbose)
912 chat_logf("abort on (%v)", s);
913 return;
916 if (clear_abort_next) {
917 char *s1;
918 int i;
919 int old_max;
920 int pack = 0;
922 clear_abort_next = 0;
924 s1 = clean(s, 0);
926 if (strlen(s1) > strlen(s)
927 || strlen(s1) + 1 > sizeof(fail_buffer))
928 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
930 old_max = n_aborts;
931 for (i=0; i < n_aborts; i++) {
932 if ( strcmp(s1,abort_string[i]) == 0 ) {
933 free(abort_string[i]);
934 abort_string[i] = NULL;
935 pack++;
936 n_aborts--;
937 if (verbose)
938 chat_logf("clear abort on (%v)", s);
941 free(s1);
942 if (pack)
943 pack_array(abort_string,old_max);
944 return;
947 if (report_next) {
948 char *s1;
950 report_next = 0;
951 if (n_reports >= MAX_REPORTS)
952 fatal(2, "Too many REPORT strings");
954 s1 = clean(s, 0);
956 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
957 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
959 report_string[n_reports++] = s1;
961 if (verbose)
962 chat_logf("report (%v)", s);
963 return;
966 if (clear_report_next) {
967 char *s1;
968 int i;
969 int old_max;
970 int pack = 0;
972 clear_report_next = 0;
974 s1 = clean(s, 0);
976 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
977 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
979 old_max = n_reports;
980 for (i=0; i < n_reports; i++) {
981 if ( strcmp(s1,report_string[i]) == 0 ) {
982 free(report_string[i]);
983 report_string[i] = NULL;
984 pack++;
985 n_reports--;
986 if (verbose)
987 chat_logf("clear report (%v)", s);
990 free(s1);
991 if (pack)
992 pack_array(report_string,old_max);
994 return;
997 if (timeout_next) {
998 timeout_next = 0;
999 timeout = atoi(s);
1001 if (timeout <= 0)
1002 timeout = DEFAULT_CHAT_TIMEOUT;
1004 if (verbose)
1005 chat_logf("timeout set to %d seconds", timeout);
1007 return;
1010 if (strcmp(s, "EOT") == 0)
1011 s = strdup("^D\\c");
1012 else if (strcmp(s, "BREAK") == 0)
1013 s = strdup("\\K\\c");
1015 if (!put_string(s))
1016 fatal(1, "Failed");
1019 static int
1020 get_char(void)
1022 int status;
1023 char c;
1025 status = read(STDIN_FILENO, &c, 1);
1027 switch (status) {
1028 case 1:
1029 return ((int)c & 0x7F);
1031 default:
1032 chat_logf("warning: read() on stdin returned %d", status);
1033 /* FALLTHROUGH */
1035 case -1:
1036 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1037 fatal(2, "Can't get file mode flags on stdin: %m");
1039 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1040 fatal(2, "Can't set file mode flags on stdin: %m");
1042 return (-1);
1046 static int put_char(int c)
1048 int status;
1049 char ch = c;
1051 usleep(10000); /* inter-character typing delay (?) */
1053 status = write(STDOUT_FILENO, &ch, 1);
1055 switch (status) {
1056 case 1:
1057 return (0);
1059 default:
1060 chat_logf("warning: write() on stdout returned %d", status);
1061 /* FALLTHROUGH */
1063 case -1:
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");
1070 return (-1);
1074 static int
1075 write_char(int c)
1077 if (alarmed || put_char(c) < 0) {
1078 alarm(0);
1079 alarmed = 0;
1081 if (verbose) {
1082 if (errno == EINTR || errno == EWOULDBLOCK)
1083 chat_logf(" -- write timed out");
1084 else
1085 chat_logf(" -- write failed: %m");
1087 return (0);
1089 return (1);
1092 static int
1093 put_string(char *s)
1095 quiet = 0;
1096 s = clean(s, 1);
1098 if (verbose)
1099 chat_logf("send (%v)", quiet ? "??????" : s);
1101 alarm(timeout); alarmed = 0;
1103 while (*s) {
1104 char c = *s++;
1106 if (c != '\\') {
1107 if (!write_char (c))
1108 return 0;
1109 continue;
1112 c = *s++;
1113 switch (c) {
1114 case 'd':
1115 sleep(1);
1116 break;
1118 case 'K':
1119 break_sequence();
1120 break;
1122 case 'p':
1123 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1124 break;
1126 default:
1127 if (!write_char (c))
1128 return 0;
1129 break;
1133 alarm(0);
1134 alarmed = 0;
1135 return (1);
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.
1143 static void
1144 echo_stderr(int n)
1146 static int need_lf;
1147 char *s;
1149 switch (n) {
1150 case '\r': /* ignore '\r' */
1151 break;
1152 case -1:
1153 if (need_lf == 0)
1154 break;
1155 /* FALLTHROUGH */
1156 case '\n':
1157 write(STDERR_FILENO, "\n", 1);
1158 need_lf = 0;
1159 break;
1160 default:
1161 s = character(n);
1162 write(STDERR_FILENO, s, strlen(s));
1163 need_lf = 1;
1164 break;
1169 * 'Wait for' this string to appear on this file descriptor.
1171 static int
1172 get_string(char *string)
1174 char temp[STR_LEN];
1175 int c, printed = 0;
1176 size_t len, minlen;
1177 char *s = temp, *end = s + STR_LEN;
1178 char *logged = temp;
1180 fail_reason = NULL;
1182 if (strlen(string) > STR_LEN) {
1183 chat_logf("expect string is too long");
1184 exit_code = 1;
1185 return 0;
1188 string = clean(string, 0);
1189 len = strlen(string);
1190 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1192 if (verbose)
1193 chat_logf("expect (%v)", string);
1195 if (len == 0) {
1196 if (verbose)
1197 chat_logf("got it");
1198 return (1);
1201 alarm(timeout);
1202 alarmed = 0;
1204 while ( ! alarmed && (c = get_char()) >= 0) {
1205 int n, abort_len, report_len;
1207 if (echo)
1208 echo_stderr(c);
1209 if (verbose && c == '\n') {
1210 if (s == logged)
1211 chat_logf(""); /* blank line */
1212 else
1213 chat_logf("%0.*v", s - logged, logged);
1214 logged = s + 1;
1217 *s++ = c;
1219 if (verbose && s >= logged + 80) {
1220 chat_logf("%0.*v", s - logged, logged);
1221 logged = s;
1224 if (Verbose) {
1225 if (c == '\n')
1226 fputc( '\n', stderr );
1227 else if (c != '\r')
1228 fprintf( stderr, "%s", character(c) );
1231 if (!report_gathering) {
1232 for (n = 0; n < n_reports; ++n) {
1233 if ((report_string[n] != 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 (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] = NULL;
1243 report_gathering = 1;
1244 break;
1248 else {
1249 if (!iscntrl (c)) {
1250 int rep_len = strlen (report_buffer);
1251 report_buffer[rep_len] = c;
1252 report_buffer[rep_len + 1] = '\0';
1254 else {
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) {
1263 if (verbose) {
1264 if (s > logged)
1265 chat_logf("%0.*v", s - logged, logged);
1266 chat_logf(" -- got it\n");
1269 alarm(0);
1270 alarmed = 0;
1271 return (1);
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) {
1277 if (verbose) {
1278 if (s > logged)
1279 chat_logf("%0.*v", s - logged, logged);
1280 chat_logf(" -- failed");
1283 alarm(0);
1284 alarmed = 0;
1285 exit_code = n + 4;
1286 strcpy(fail_reason = fail_buffer, abort_string[n]);
1287 return (0);
1291 if (s >= end) {
1292 if (logged < s - minlen) {
1293 chat_logf("%0.*v", s - logged, logged);
1294 logged = s;
1296 s -= minlen;
1297 memmove(temp, s, minlen);
1298 logged = temp + (logged - s);
1299 s = temp + minlen;
1302 if (alarmed && verbose)
1303 chat_logf("warning: alarm synchronization problem");
1306 alarm(0);
1308 if (verbose && printed) {
1309 if (alarmed)
1310 chat_logf(" -- read timed out");
1311 else
1312 chat_logf(" -- read failed: %m");
1315 exit_code = 3;
1316 alarmed = 0;
1317 return (0);
1320 static void
1321 pack_array(char **array, int end)
1323 int i, j;
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)
1331 array[i] = NULL;
1332 break;
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)
1346 static int
1347 vfmtmsg(char *buf, int buflen, const char *fmt, va_list args)
1349 int c, i, n;
1350 int width, prec, fillch;
1351 int base, len, neg, quoted;
1352 unsigned long val = 0;
1353 char *str, *buf0;
1354 const char *f;
1355 unsigned char *p;
1356 char num[32];
1357 static char hexchars[] = "0123456789abcdef";
1359 buf0 = buf;
1360 --buflen;
1361 while (buflen > 0) {
1362 for (f = fmt; *f != '%' && *f != 0; ++f)
1364 if (f > fmt) {
1365 len = f - fmt;
1366 if (len > buflen)
1367 len = buflen;
1368 memcpy(buf, fmt, len);
1369 buf += len;
1370 buflen -= len;
1371 fmt = f;
1373 if (*fmt == 0)
1374 break;
1375 c = *++fmt;
1376 width = prec = 0;
1377 fillch = ' ';
1378 if (c == '0') {
1379 fillch = '0';
1380 c = *++fmt;
1382 if (c == '*') {
1383 width = va_arg(args, int);
1384 c = *++fmt;
1385 } else {
1386 while (isdigit(c)) {
1387 width = width * 10 + c - '0';
1388 c = *++fmt;
1391 if (c == '.') {
1392 c = *++fmt;
1393 if (c == '*') {
1394 prec = va_arg(args, int);
1395 c = *++fmt;
1396 } else {
1397 while (isdigit(c)) {
1398 prec = prec * 10 + c - '0';
1399 c = *++fmt;
1403 str = NULL;
1404 base = 0;
1405 neg = 0;
1406 ++fmt;
1407 switch (c) {
1408 case 'd':
1409 i = va_arg(args, int);
1410 if (i < 0) {
1411 neg = 1;
1412 val = -i;
1413 } else
1414 val = i;
1415 base = 10;
1416 break;
1417 case 'o':
1418 val = va_arg(args, unsigned int);
1419 base = 8;
1420 break;
1421 case 'x':
1422 val = va_arg(args, unsigned int);
1423 base = 16;
1424 break;
1425 case 'p':
1426 val = (unsigned long) va_arg(args, void *);
1427 base = 16;
1428 neg = 2;
1429 break;
1430 case 's':
1431 str = va_arg(args, char *);
1432 break;
1433 case 'c':
1434 num[0] = va_arg(args, int);
1435 num[1] = 0;
1436 str = num;
1437 break;
1438 case 'm':
1439 str = strerror(errno);
1440 break;
1441 case 'v': /* "visible" string */
1442 case 'q': /* quoted string */
1443 quoted = c == 'q';
1444 p = va_arg(args, unsigned char *);
1445 if (fillch == '0' && prec > 0) {
1446 n = prec;
1447 } else {
1448 n = strlen((char *)p);
1449 if (prec > 0 && prec < n)
1450 n = prec;
1452 while (n > 0 && buflen > 0) {
1453 c = *p++;
1454 --n;
1455 if (!quoted && c >= 0x80) {
1456 OUTCHAR('M');
1457 OUTCHAR('-');
1458 c -= 0x80;
1460 if (quoted && (c == '"' || c == '\\'))
1461 OUTCHAR('\\');
1462 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1463 if (quoted) {
1464 OUTCHAR('\\');
1465 switch (c) {
1466 case '\t': OUTCHAR('t'); break;
1467 case '\n': OUTCHAR('n'); break;
1468 case '\b': OUTCHAR('b'); break;
1469 case '\f': OUTCHAR('f'); break;
1470 default:
1471 OUTCHAR('x');
1472 OUTCHAR(hexchars[c >> 4]);
1473 OUTCHAR(hexchars[c & 0xf]);
1475 } else {
1476 if (c == '\t')
1477 OUTCHAR(c);
1478 else {
1479 OUTCHAR('^');
1480 OUTCHAR(c ^ 0x40);
1483 } else
1484 OUTCHAR(c);
1486 continue;
1487 default:
1488 *buf++ = '%';
1489 if (c != '%')
1490 --fmt; /* so %z outputs %z etc. */
1491 --buflen;
1492 continue;
1494 if (base != 0) {
1495 str = num + sizeof(num);
1496 *--str = 0;
1497 while (str > num + neg) {
1498 *--str = hexchars[val % base];
1499 val = val / base;
1500 if (--prec <= 0 && val == 0)
1501 break;
1503 switch (neg) {
1504 case 1:
1505 *--str = '-';
1506 break;
1507 case 2:
1508 *--str = 'x';
1509 *--str = '0';
1510 break;
1512 len = num + sizeof(num) - 1 - str;
1513 } else {
1514 len = strlen(str);
1515 if (prec > 0 && len > prec)
1516 len = prec;
1518 if (width > 0) {
1519 if (width > buflen)
1520 width = buflen;
1521 if ((n = width - len) > 0) {
1522 buflen -= n;
1523 for (; n > 0; --n)
1524 *buf++ = fillch;
1527 if (len > buflen)
1528 len = buflen;
1529 memcpy(buf, str, len);
1530 buf += len;
1531 buflen -= len;
1533 *buf = 0;
1534 return buf - buf0;