dmake: do not set MAKEFLAGS=k
[unleashed/tickless.git] / usr / src / cmd / cmd-inet / usr.bin / chat / chat.c
blob8da8c877d3b5fce333884e3f79f3dfe49bcf699e
1 /*
2 * Copyright 2000 Sun Microsystems, Inc. All rights reserved.
3 * Use is subject to license terms.
4 */
5 /*
6 * Chat -- a program for automatic session establishment (i.e. dial
7 * the phone and log in).
9 * Standard termination codes:
10 * 0 - successful completion of the script
11 * 1 - invalid argument, expect string too large, etc.
12 * 2 - error on an I/O operation or fatal error condition.
13 * 3 - timeout waiting for a simple string.
14 * 4 - the first string declared as "ABORT"
15 * 5 - the second string declared as "ABORT"
16 * 6 - ... and so on for successive ABORT strings.
18 * This software is in the public domain.
20 * -----------------
21 * 22-May-99 added environment substitutuion, enabled with -E switch.
22 * Andreas Arens <andras@cityweb.de>.
24 * 12-May-99 added a feature to read data to be sent from a file,
25 * if the send string starts with @. Idea from gpk <gpk@onramp.net>.
27 * added -T and -U option and \T and \U substitution to pass a phone
28 * number into chat script. Two are needed for some ISDN TA applications.
29 * Keith Dart <kdart@cisco.com>
32 * Added SAY keyword to send output to stderr.
33 * This allows to turn ECHO OFF and to output specific, user selected,
34 * text to give progress messages. This best works when stderr
35 * exists (i.e.: pppd in nodetach mode).
37 * Added HANGUP directives to allow for us to be called
38 * back. When HANGUP is set to NO, chat will not hangup at HUP signal.
39 * We rely on timeouts in that case.
41 * Added CLR_ABORT to clear previously set ABORT string. This has been
42 * dictated by the HANGUP above as "NO CARRIER" (for example) must be
43 * an ABORT condition until we know the other host is going to close
44 * the connection for call back. As soon as we have completed the
45 * first stage of the call back sequence, "NO CARRIER" is a valid, non
46 * fatal string. As soon as we got called back (probably get "CONNECT"),
47 * we should re-arm the ABORT "NO CARRIER". Hence the CLR_ABORT command.
48 * Note that CLR_ABORT packs the abort_strings[] array so that we do not
49 * have unused entries not being reclaimed.
51 * In the same vein as above, added CLR_REPORT keyword.
53 * Allow for comments. Line starting with '#' are comments and are
54 * ignored. If a '#' is to be expected as the first character, the
55 * expect string must be quoted.
58 * Francis Demierre <Francis@SwissMail.Com>
59 * Thu May 15 17:15:40 MET DST 1997
62 * Added -r "report file" switch & REPORT keyword.
63 * Robert Geer <bgeer@xmission.com>
65 * Added -s "use stderr" and -S "don't use syslog" switches.
66 * June 18, 1997
67 * Karl O. Pinc <kop@meme.com>
70 * Added -e "echo" switch & ECHO keyword
71 * Dick Streefland <dicks@tasking.nl>
74 * Considerable updates and modifications by
75 * Al Longyear <longyear@pobox.com>
76 * Paul Mackerras <paulus@cs.anu.edu.au>
79 * The original author is:
81 * Karl Fox <karl@MorningStar.Com>
82 * Morning Star Technologies, Inc.
83 * 1760 Zollinger Road
84 * Columbus, OH 43221
85 * (614)451-1883
89 #ifndef __STDC__
90 #define const
91 #endif
93 #pragma ident "%Z%%M% %I% %E% SMI"
95 static const char rcsid[] = "$Id: chat.c,v 1.26 1999/12/23 01:39:54 paulus Exp $";
97 #include <stdio.h>
98 #include <ctype.h>
99 #include <time.h>
100 #include <fcntl.h>
101 #include <signal.h>
102 #include <errno.h>
103 #include <string.h>
104 #include <stdlib.h>
105 #include <unistd.h>
106 #include <sys/types.h>
107 #include <sys/stat.h>
108 #include <syslog.h>
110 #ifndef TERMIO
111 #undef TERMIOS
112 #define TERMIOS
113 #endif
115 #ifdef TERMIO
116 #include <termio.h>
117 #endif
118 #ifdef TERMIOS
119 #include <termios.h>
120 #endif
122 #define STR_LEN 1024
124 #ifndef SIGTYPE
125 #define SIGTYPE void
126 #endif
128 #undef __P
129 #undef __V
131 #ifdef __STDC__
132 #include <stdarg.h>
133 #define __V(x) x
134 #define __P(x) x
135 #else
136 #include <varargs.h>
137 #define __V(x) (va_alist) va_dcl
138 #define __P(x) ()
139 #define const
140 #endif
142 #ifndef O_NONBLOCK
143 #define O_NONBLOCK O_NDELAY
144 #endif
146 #ifdef SUNOS
147 extern int sys_nerr;
148 extern char *sys_errlist[];
149 #define memmove(to, from, n) bcopy(from, to, n)
150 #define strerror(n) ((unsigned)(n) < sys_nerr? sys_errlist[(n)] :\
151 "unknown error")
152 #endif
154 /*************** Micro getopt() *********************************************/
155 #define OPTION(c,v) (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
156 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
157 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
158 #define OPTARG(c,v) (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
159 (_O=4,(char*)0):(char*)0)
160 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
161 #define ARG(c,v) (c?(--c,*v++):(char*)0)
163 static int _O = 0; /* Internal state */
164 /*************** Micro getopt() *********************************************/
166 char *program_name;
168 #define MAX_ABORTS 50
169 #define MAX_REPORTS 50
170 #define DEFAULT_CHAT_TIMEOUT 45
172 int echo = 0;
173 int verbose = 0;
174 int to_log = 1;
175 int to_stderr = 0;
176 int Verbose = 0;
177 int quiet = 0;
178 int report = 0;
179 int use_env = 0;
180 int exit_code = 0;
181 FILE *report_fp = NULL;
182 char *report_file = NULL;
183 char *chat_file = NULL;
184 char *phone_num = NULL;
185 char *phone_num2 = NULL;
186 int timeout = DEFAULT_CHAT_TIMEOUT;
188 int have_tty_parameters = 0;
190 #ifdef TERMIO
191 #define term_parms struct termio
192 #define get_term_param(param) ioctl(0, TCGETA, param)
193 #define set_term_param(param) ioctl(0, TCSETA, param)
194 struct termio saved_tty_parameters;
195 #endif
197 #ifdef TERMIOS
198 #define term_parms struct termios
199 #define get_term_param(param) tcgetattr(0, param)
200 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
201 struct termios saved_tty_parameters;
202 #endif
204 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
205 fail_buffer[50];
206 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
207 int clear_abort_next = 0;
209 char *report_string[MAX_REPORTS] ;
210 char report_buffer[50] ;
211 int n_reports = 0, report_next = 0, report_gathering = 0 ;
212 int clear_report_next = 0;
214 int say_next = 0, hup_next = 0;
216 void *dup_mem __P((void *b, size_t c));
217 void *copy_of __P((char *s));
218 void usage __P((void));
219 void logf __P((const char *fmt, ...));
220 void fatal __P((int code, const char *fmt, ...));
221 SIGTYPE sigalrm __P((int signo));
222 SIGTYPE sigint __P((int signo));
223 SIGTYPE sigterm __P((int signo));
224 SIGTYPE sighup __P((int signo));
225 void unalarm __P((void));
226 void init __P((void));
227 void set_tty_parameters __P((void));
228 void echo_stderr __P((int));
229 void break_sequence __P((void));
230 void terminate __P((int status));
231 void do_file __P((char *chat_file));
232 int get_string __P((register char *string));
233 int put_string __P((register char *s));
234 int write_char __P((int c));
235 int put_char __P((int c));
236 int get_char __P((void));
237 void chat_send __P((register char *s));
238 char *character __P((int c));
239 void chat_expect __P((register char *s));
240 char *clean __P((register char *s, int sending));
241 void break_sequence __P((void));
242 void terminate __P((int status));
243 void pack_array __P((char **array, int end));
244 char *expect_strtok __P((char *, char *));
245 int vfmtmsg __P((char *, int, const char *, va_list)); /* vsprintf++ */
247 int main __P((int, char *[]));
249 void *dup_mem(b, c)
250 void *b;
251 size_t c;
253 void *ans = malloc (c);
254 if (!ans)
255 fatal(2, "memory error!");
257 memcpy (ans, b, c);
258 return ans;
261 void *copy_of (s)
262 char *s;
264 return dup_mem (s, strlen (s) + 1);
268 * chat [ -v ] [ -E ] [ -T number ] [ -U number ] [ -t timeout ] [ -f chat-file ] \
269 * [ -r report-file ] \
270 * [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
272 * Perform a UUCP-dialer-like chat script on stdin and stdout.
275 main(argc, argv)
276 int argc;
277 char **argv;
279 int option;
280 char *arg;
282 program_name = *argv;
283 tzset();
285 while ((option = OPTION(argc, argv)) != 0) {
286 switch (option) {
287 case 'e':
288 ++echo;
289 break;
291 case 'E':
292 ++use_env;
293 break;
295 case 'v':
296 ++verbose;
297 break;
299 case 'V':
300 ++Verbose;
301 break;
303 case 's':
304 ++to_stderr;
305 break;
307 case 'S':
308 to_log = 0;
309 break;
311 case 'f':
312 if ((arg = OPTARG(argc, argv)) != NULL)
313 chat_file = copy_of(arg);
314 else
315 usage();
316 break;
318 case 't':
319 if ((arg = OPTARG(argc, argv)) != NULL)
320 timeout = atoi(arg);
321 else
322 usage();
323 break;
325 case 'r':
326 arg = OPTARG (argc, argv);
327 if (arg) {
328 if (report_fp != NULL)
329 fclose (report_fp);
330 report_file = copy_of (arg);
331 report_fp = fopen (report_file, "a");
332 if (report_fp != NULL) {
333 if (verbose)
334 fprintf (report_fp, "Opening \"%s\"...\n",
335 report_file);
336 report = 1;
339 break;
341 case 'T':
342 if ((arg = OPTARG(argc, argv)) != NULL)
343 phone_num = copy_of(arg);
344 else
345 usage();
346 break;
348 case 'U':
349 if ((arg = OPTARG(argc, argv)) != NULL)
350 phone_num2 = copy_of(arg);
351 else
352 usage();
353 break;
355 default:
356 usage();
357 break;
361 * Default the report file to the stderr location
363 if (report_fp == NULL)
364 report_fp = stderr;
366 if (to_log) {
367 #ifdef ultrix
368 openlog("chat", LOG_PID);
369 #else
370 openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
372 if (verbose)
373 setlogmask(LOG_UPTO(LOG_INFO));
374 else
375 setlogmask(LOG_UPTO(LOG_WARNING));
376 #endif
379 init();
381 if (chat_file != NULL) {
382 arg = ARG(argc, argv);
383 if (arg != NULL)
384 usage();
385 else
386 do_file (chat_file);
387 } else {
388 while ((arg = ARG(argc, argv)) != NULL) {
389 chat_expect(arg);
391 if ((arg = ARG(argc, argv)) != NULL)
392 chat_send(arg);
396 terminate(0);
397 return 0;
401 * Process a chat script when read from a file.
404 void do_file (chat_file)
405 char *chat_file;
407 int linect, sendflg;
408 char *sp, *arg, quote;
409 char buf [STR_LEN];
410 FILE *cfp;
412 cfp = fopen (chat_file, "r");
413 if (cfp == NULL)
414 fatal(1, "%s -- open failed: %m", chat_file);
416 linect = 0;
417 sendflg = 0;
419 while (fgets(buf, STR_LEN, cfp) != NULL) {
420 sp = strchr (buf, '\n');
421 if (sp)
422 *sp = '\0';
424 linect++;
425 sp = buf;
427 /* lines starting with '#' are comments. If a real '#'
428 is to be expected, it should be quoted .... */
429 if ( *sp == '#' )
430 continue;
432 while (*sp != '\0') {
433 if (*sp == ' ' || *sp == '\t') {
434 ++sp;
435 continue;
438 if (*sp == '"' || *sp == '\'') {
439 quote = *sp++;
440 arg = sp;
441 while (*sp != quote) {
442 if (*sp == '\0')
443 fatal(1, "unterminated quote (line %d)", linect);
445 if (*sp++ == '\\') {
446 if (*sp != '\0')
447 ++sp;
451 else {
452 arg = sp;
453 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
454 ++sp;
457 if (*sp != '\0')
458 *sp++ = '\0';
460 if (sendflg)
461 chat_send (arg);
462 else
463 chat_expect (arg);
464 sendflg = !sendflg;
467 fclose (cfp);
471 * We got an error parsing the command line.
473 void usage()
475 fprintf(stderr, "\
476 Usage: %s [-e] [-E] [-v] [-V] [-t timeout] [-r report-file]\n\
477 [-T phone-number] [-U phone-number2] {-f chat-file | chat-script}\n", program_name);
478 exit(1);
481 char line[1024];
484 * Send a message to syslog and/or stderr.
486 void logf __V((const char *fmt, ...))
488 va_list args;
490 #ifdef __STDC__
491 va_start(args, fmt);
492 #else
493 char *fmt;
494 va_start(args);
495 fmt = va_arg(args, char *);
496 #endif
498 vfmtmsg(line, sizeof(line), fmt, args);
499 if (to_log)
500 syslog(LOG_INFO, "%s", line);
501 if (to_stderr)
502 fprintf(stderr, "%s\n", line);
506 * Print an error message and terminate.
509 void fatal __V((int code, const char *fmt, ...))
511 va_list args;
513 #ifdef __STDC__
514 va_start(args, fmt);
515 #else
516 int code;
517 char *fmt;
518 va_start(args);
519 code = va_arg(args, int);
520 fmt = va_arg(args, char *);
521 #endif
523 vfmtmsg(line, sizeof(line), fmt, args);
524 if (to_log)
525 syslog(LOG_ERR, "%s", line);
526 if (to_stderr)
527 fprintf(stderr, "%s\n", line);
528 terminate(code);
531 int alarmed = 0;
533 SIGTYPE sigalrm(signo)
534 int signo;
536 int flags;
538 alarm(1);
539 alarmed = 1; /* Reset alarm to avoid race window */
540 signal(SIGALRM, sigalrm); /* that can cause hanging in read() */
542 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
543 fatal(2, "Can't get file mode flags on stdin: %m");
545 if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
546 fatal(2, "Can't set file mode flags on stdin: %m");
548 if (verbose)
549 logf("alarm");
552 void unalarm()
554 int flags;
556 if ((flags = fcntl(0, F_GETFL, 0)) == -1)
557 fatal(2, "Can't get file mode flags on stdin: %m");
559 if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
560 fatal(2, "Can't set file mode flags on stdin: %m");
563 SIGTYPE sigint(signo)
564 int signo;
566 fatal(2, "SIGINT");
569 SIGTYPE sigterm(signo)
570 int signo;
572 fatal(2, "SIGTERM");
575 SIGTYPE sighup(signo)
576 int signo;
578 fatal(2, "SIGHUP");
581 void init()
583 signal(SIGINT, sigint);
584 signal(SIGTERM, sigterm);
585 signal(SIGHUP, sighup);
587 set_tty_parameters();
588 signal(SIGALRM, sigalrm);
589 alarm(0);
590 alarmed = 0;
593 void set_tty_parameters()
595 #if defined(get_term_param)
596 term_parms t;
598 if (get_term_param (&t) < 0)
599 fatal(2, "Can't get terminal parameters: %m");
601 saved_tty_parameters = t;
602 have_tty_parameters = 1;
604 t.c_iflag |= IGNBRK | ISTRIP | IGNPAR;
605 t.c_oflag = 0;
606 t.c_lflag = 0;
607 t.c_cc[VERASE] =
608 t.c_cc[VKILL] = 0;
609 t.c_cc[VMIN] = 1;
610 t.c_cc[VTIME] = 0;
612 if (set_term_param (&t) < 0)
613 fatal(2, "Can't set terminal parameters: %m");
614 #endif
617 void break_sequence()
619 #ifdef TERMIOS
620 tcsendbreak (0, 0);
621 #endif
624 void terminate(status)
625 int status;
627 static int terminating = 0;
629 if (terminating)
630 exit(status);
631 terminating = 1;
632 echo_stderr(-1);
634 * Allow the last of the report string to be gathered before we terminate.
636 if (report_gathering) {
637 int c, rep_len;
639 rep_len = strlen(report_buffer);
640 while (rep_len + 1 <= sizeof(report_buffer)) {
641 alarm(1);
642 c = get_char();
643 alarm(0);
644 if (c < 0 || iscntrl(c))
645 break;
646 report_buffer[rep_len] = c;
647 ++rep_len;
649 report_buffer[rep_len] = 0;
650 fprintf (report_fp, "chat: %s\n", report_buffer);
652 if (report_file != NULL && report_fp != (FILE *) NULL) {
653 if (verbose)
654 fprintf (report_fp, "Closing \"%s\".\n", report_file);
655 fclose (report_fp);
656 report_fp = (FILE *) NULL;
659 #if defined(get_term_param)
660 if (have_tty_parameters) {
661 if (set_term_param (&saved_tty_parameters) < 0)
662 fatal(2, "Can't restore terminal parameters: %m");
664 #endif
666 exit(status);
670 * 'Clean up' this string.
672 char *clean(s, sending)
673 register char *s;
674 int sending; /* set to 1 when sending (putting) this string. */
676 char temp[STR_LEN], env_str[STR_LEN], cur_chr;
677 register char *s1, *phchar;
678 int add_return = sending;
679 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
680 #define isalnumx(chr) ((((chr) >= '0') && ((chr) <= '9')) \
681 || (((chr) >= 'a') && ((chr) <= 'z')) \
682 || (((chr) >= 'A') && ((chr) <= 'Z')) \
683 || (chr) == '_')
685 s1 = temp;
686 while (*s) {
687 cur_chr = *s++;
688 if (cur_chr == '^') {
689 cur_chr = *s++;
690 if (cur_chr == '\0') {
691 *s1++ = '^';
692 break;
694 cur_chr &= 0x1F;
695 if (cur_chr != 0) {
696 *s1++ = cur_chr;
698 continue;
701 if (use_env && cur_chr == '$') { /* ARI */
702 phchar = env_str;
703 while (isalnumx(*s))
704 *phchar++ = *s++;
705 *phchar = '\0';
706 phchar = getenv(env_str);
707 if (phchar)
708 while (*phchar)
709 *s1++ = *phchar++;
710 continue;
713 if (cur_chr != '\\') {
714 *s1++ = cur_chr;
715 continue;
718 cur_chr = *s++;
719 if (cur_chr == '\0') {
720 if (sending) {
721 *s1++ = '\\';
722 *s1++ = '\\';
724 break;
727 switch (cur_chr) {
728 case 'b':
729 *s1++ = '\b';
730 break;
732 case 'c':
733 if (sending && *s == '\0')
734 add_return = 0;
735 else
736 *s1++ = cur_chr;
737 break;
739 case '\\':
740 case 'K':
741 case 'p':
742 case 'd':
743 if (sending)
744 *s1++ = '\\';
745 *s1++ = cur_chr;
746 break;
748 case 'T':
749 if (sending && phone_num) {
750 for (phchar = phone_num; *phchar != '\0'; phchar++)
751 *s1++ = *phchar;
753 else {
754 *s1++ = '\\';
755 *s1++ = 'T';
757 break;
759 case 'U':
760 if (sending && phone_num2) {
761 for (phchar = phone_num2; *phchar != '\0'; phchar++)
762 *s1++ = *phchar;
764 else {
765 *s1++ = '\\';
766 *s1++ = 'U';
768 break;
770 case 'q':
771 quiet = 1;
772 break;
774 case 'r':
775 *s1++ = '\r';
776 break;
778 case 'n':
779 *s1++ = '\n';
780 break;
782 case 's':
783 *s1++ = ' ';
784 break;
786 case 't':
787 *s1++ = '\t';
788 break;
790 case 'N':
791 if (sending) {
792 *s1++ = '\\';
793 *s1++ = '\0';
795 else
796 *s1++ = 'N';
797 break;
799 case '$': /* ARI */
800 if (use_env) {
801 *s1++ = cur_chr;
802 break;
804 /* FALL THROUGH */
806 default:
807 if (isoctal (cur_chr)) {
808 cur_chr &= 0x07;
809 if (isoctal (*s)) {
810 cur_chr <<= 3;
811 cur_chr |= *s++ - '0';
812 if (isoctal (*s)) {
813 cur_chr <<= 3;
814 cur_chr |= *s++ - '0';
818 if (cur_chr != 0 || sending) {
819 if (sending && (cur_chr == '\\' || cur_chr == 0))
820 *s1++ = '\\';
821 *s1++ = cur_chr;
823 break;
826 if (sending)
827 *s1++ = '\\';
828 *s1++ = cur_chr;
829 break;
833 if (add_return)
834 *s1++ = '\r';
836 *s1++ = '\0'; /* guarantee closure */
837 *s1++ = '\0'; /* terminate the string */
838 return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
842 * A modified version of 'strtok'. This version skips \ sequences.
845 char *expect_strtok (s, term)
846 char *s, *term;
848 static char *str = "";
849 int escape_flag = 0;
850 char *result;
853 * If a string was specified then do initial processing.
855 if (s)
856 str = s;
859 * If this is the escape flag then reset it and ignore the character.
861 if (*str)
862 result = str;
863 else
864 result = NULL;
866 while (*str) {
867 if (escape_flag) {
868 escape_flag = 0;
869 ++str;
870 continue;
873 if (*str == '\\') {
874 ++str;
875 escape_flag = 1;
876 continue;
880 * If this is not in the termination string, continue.
882 if (strchr(term, *str) == NULL) {
883 ++str;
884 continue;
888 * This is the terminator. Mark the end of the string and stop.
890 *str++ = '\0';
891 break;
893 return (result);
897 * Process the expect string
900 void chat_expect (s)
901 char *s;
903 char *expect;
904 char *reply;
906 if (strcmp(s, "HANGUP") == 0) {
907 ++hup_next;
908 return;
911 if (strcmp(s, "ABORT") == 0) {
912 ++abort_next;
913 return;
916 if (strcmp(s, "CLR_ABORT") == 0) {
917 ++clear_abort_next;
918 return;
921 if (strcmp(s, "REPORT") == 0) {
922 ++report_next;
923 return;
926 if (strcmp(s, "CLR_REPORT") == 0) {
927 ++clear_report_next;
928 return;
931 if (strcmp(s, "TIMEOUT") == 0) {
932 ++timeout_next;
933 return;
936 if (strcmp(s, "ECHO") == 0) {
937 ++echo_next;
938 return;
941 if (strcmp(s, "SAY") == 0) {
942 ++say_next;
943 return;
947 * Fetch the expect and reply string.
949 for (;;) {
950 expect = expect_strtok (s, "-");
951 s = NULL;
953 if (expect == NULL)
954 return;
956 reply = expect_strtok (s, "-");
959 * Handle the expect string. If successful then exit.
961 if (get_string (expect))
962 return;
965 * If there is a sub-reply string then send it. Otherwise any condition
966 * is terminal.
968 if (reply == NULL || exit_code != 3)
969 break;
971 chat_send (reply);
975 * The expectation did not occur. This is terminal.
977 if (fail_reason)
978 logf("Failed (%s)", fail_reason);
979 else
980 logf("Failed");
981 terminate(exit_code);
985 * Translate the input character to the appropriate string for printing
986 * the data.
989 char *character(c)
990 int c;
992 static char string[10];
993 char *meta;
995 meta = (c & 0x80) ? "M-" : "";
996 c &= 0x7F;
998 if (c < 32)
999 sprintf(string, "%s^%c", meta, (int)c + '@');
1000 else if (c == 127)
1001 sprintf(string, "%s^?", meta);
1002 else
1003 sprintf(string, "%s%c", meta, c);
1005 return (string);
1009 * process the reply string
1011 void chat_send (s)
1012 register char *s;
1014 char file_data[STR_LEN];
1016 if (say_next) {
1017 say_next = 0;
1018 s = clean(s, 1);
1019 write(2, s, strlen(s));
1020 free(s);
1021 return;
1024 if (hup_next) {
1025 hup_next = 0;
1026 if (strcmp(s, "OFF") == 0)
1027 signal(SIGHUP, SIG_IGN);
1028 else
1029 signal(SIGHUP, sighup);
1030 return;
1033 if (echo_next) {
1034 echo_next = 0;
1035 echo = (strcmp(s, "ON") == 0);
1036 return;
1039 if (abort_next) {
1040 char *s1;
1042 abort_next = 0;
1044 if (n_aborts >= MAX_ABORTS)
1045 fatal(2, "Too many ABORT strings");
1047 s1 = clean(s, 0);
1049 if (strlen(s1) > strlen(s)
1050 || strlen(s1) + 1 > sizeof(fail_buffer))
1051 fatal(1, "Illegal or too-long ABORT string ('%v')", s);
1053 abort_string[n_aborts++] = s1;
1055 if (verbose)
1056 logf("abort on (%v)", s);
1057 return;
1060 if (clear_abort_next) {
1061 char *s1;
1062 int i;
1063 int old_max;
1064 int pack = 0;
1066 clear_abort_next = 0;
1068 s1 = clean(s, 0);
1070 if (strlen(s1) > strlen(s)
1071 || strlen(s1) + 1 > sizeof(fail_buffer))
1072 fatal(1, "Illegal or too-long CLR_ABORT string ('%v')", s);
1074 old_max = n_aborts;
1075 for (i=0; i < n_aborts; i++) {
1076 if ( strcmp(s1,abort_string[i]) == 0 ) {
1077 free(abort_string[i]);
1078 abort_string[i] = NULL;
1079 pack++;
1080 n_aborts--;
1081 if (verbose)
1082 logf("clear abort on (%v)", s);
1085 free(s1);
1086 if (pack)
1087 pack_array(abort_string,old_max);
1088 return;
1091 if (report_next) {
1092 char *s1;
1094 report_next = 0;
1095 if (n_reports >= MAX_REPORTS)
1096 fatal(2, "Too many REPORT strings");
1098 s1 = clean(s, 0);
1100 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1101 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1103 report_string[n_reports++] = s1;
1105 if (verbose)
1106 logf("report (%v)", s);
1107 return;
1110 if (clear_report_next) {
1111 char *s1;
1112 int i;
1113 int old_max;
1114 int pack = 0;
1116 clear_report_next = 0;
1118 s1 = clean(s, 0);
1120 if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1121 fatal(1, "Illegal or too-long REPORT string ('%v')", s);
1123 old_max = n_reports;
1124 for (i=0; i < n_reports; i++) {
1125 if ( strcmp(s1,report_string[i]) == 0 ) {
1126 free(report_string[i]);
1127 report_string[i] = NULL;
1128 pack++;
1129 n_reports--;
1130 if (verbose)
1131 logf("clear report (%v)", s);
1134 free(s1);
1135 if (pack)
1136 pack_array(report_string,old_max);
1138 return;
1141 if (timeout_next) {
1142 timeout_next = 0;
1143 timeout = atoi(s);
1145 if (timeout <= 0)
1146 timeout = DEFAULT_CHAT_TIMEOUT;
1148 if (verbose)
1149 logf("timeout set to %d seconds", timeout);
1151 return;
1155 * The syntax @filename means read the string to send from the
1156 * file `filename'.
1158 if (s[0] == '@') {
1159 /* skip the @ and any following white-space */
1160 char *fn = s;
1161 while (*++fn == ' ' || *fn == '\t')
1164 if (*fn != 0) {
1165 FILE *f;
1166 int n = 0;
1168 /* open the file and read until STR_LEN-1 bytes or end-of-file */
1169 f = fopen(fn, "r");
1170 if (f == NULL)
1171 fatal(1, "%s -- open failed: %m", fn);
1172 while (n < STR_LEN - 1) {
1173 int nr = fread(&file_data[n], 1, STR_LEN - 1 - n, f);
1174 if (nr < 0)
1175 fatal(1, "%s -- read error", fn);
1176 if (nr == 0)
1177 break;
1178 n += nr;
1180 fclose(f);
1182 /* use the string we got as the string to send,
1183 but trim off the final newline if any. */
1184 if (n > 0 && file_data[n-1] == '\n')
1185 --n;
1186 file_data[n] = 0;
1187 s = file_data;
1191 if (strcmp(s, "EOT") == 0)
1192 s = "^D\\c";
1193 else if (strcmp(s, "BREAK") == 0)
1194 s = "\\K\\c";
1196 if (!put_string(s))
1197 fatal(1, "Failed");
1200 int get_char()
1202 int status;
1203 char c;
1205 status = read(0, &c, 1);
1207 switch (status) {
1208 case 1:
1209 return ((int)c & 0x7F);
1211 default:
1212 logf("warning: read() on stdin returned %d", status);
1214 case -1:
1215 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1216 fatal(2, "Can't get file mode flags on stdin: %m");
1218 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1219 fatal(2, "Can't set file mode flags on stdin: %m");
1221 return (-1);
1225 int put_char(c)
1226 int c;
1228 int status;
1229 char ch = c;
1231 usleep(10000); /* inter-character typing delay (?) */
1233 status = write(1, &ch, 1);
1235 switch (status) {
1236 case 1:
1237 return (0);
1239 default:
1240 logf("warning: write() on stdout returned %d", status);
1242 case -1:
1243 if ((status = fcntl(0, F_GETFL, 0)) == -1)
1244 fatal(2, "Can't get file mode flags on stdin, %m");
1246 if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1247 fatal(2, "Can't set file mode flags on stdin: %m");
1249 return (-1);
1253 int write_char (c)
1254 int c;
1256 if (alarmed || put_char(c) < 0) {
1257 alarm(0);
1258 alarmed = 0;
1260 if (verbose) {
1261 if (errno == EINTR || errno == EWOULDBLOCK)
1262 logf(" -- write timed out");
1263 else
1264 logf(" -- write failed: %m");
1266 return (0);
1268 return (1);
1271 int put_string (s)
1272 register char *s;
1274 quiet = 0;
1275 s = clean(s, 1);
1277 if (verbose) {
1278 if (quiet)
1279 logf("send (??????)");
1280 else
1281 logf("send (%v)", s);
1284 alarm(timeout); alarmed = 0;
1286 while (*s) {
1287 register char c = *s++;
1289 if (c != '\\') {
1290 if (!write_char (c))
1291 return 0;
1292 continue;
1295 c = *s++;
1296 switch (c) {
1297 case 'd':
1298 sleep(1);
1299 break;
1301 case 'K':
1302 break_sequence();
1303 break;
1305 case 'p':
1306 usleep(10000); /* 1/100th of a second (arg is microseconds) */
1307 break;
1309 default:
1310 if (!write_char (c))
1311 return 0;
1312 break;
1316 alarm(0);
1317 alarmed = 0;
1318 return (1);
1322 * Echo a character to stderr.
1323 * When called with -1, a '\n' character is generated when
1324 * the cursor is not at the beginning of a line.
1326 void echo_stderr(n)
1327 int n;
1329 static int need_lf;
1330 char *s;
1332 switch (n) {
1333 case '\r': /* ignore '\r' */
1334 break;
1335 case -1:
1336 if (need_lf == 0)
1337 break;
1338 /* fall through */
1339 case '\n':
1340 write(2, "\n", 1);
1341 need_lf = 0;
1342 break;
1343 default:
1344 s = character(n);
1345 write(2, s, strlen(s));
1346 need_lf = 1;
1347 break;
1352 * 'Wait for' this string to appear on this file descriptor.
1354 int get_string(string)
1355 register char *string;
1357 char temp[STR_LEN];
1358 int c, printed = 0, len, minlen;
1359 register char *s = temp, *end = s + STR_LEN;
1360 char *logged = temp;
1362 fail_reason = NULL;
1363 string = clean(string, 0);
1364 len = strlen(string);
1365 minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1367 if (verbose)
1368 logf("expect (%v)", string);
1370 if (len > STR_LEN) {
1371 logf("expect string is too long");
1372 exit_code = 1;
1373 return 0;
1376 if (len == 0) {
1377 if (verbose)
1378 logf("got it");
1379 return (1);
1382 alarm(timeout);
1383 alarmed = 0;
1385 while ( ! alarmed && (c = get_char()) >= 0) {
1386 int n, abort_len, report_len;
1388 if (echo)
1389 echo_stderr(c);
1390 if (verbose && c == '\n') {
1391 if (s == logged)
1392 logf(""); /* blank line */
1393 else
1394 logf("%0.*v", s - logged, logged);
1395 logged = s + 1;
1398 *s++ = c;
1400 if (verbose && s >= logged + 80) {
1401 logf("%0.*v", s - logged, logged);
1402 logged = s;
1405 if (Verbose) {
1406 if (c == '\n')
1407 fputc( '\n', stderr );
1408 else if (c != '\r')
1409 fprintf( stderr, "%s", character(c) );
1412 if (!report_gathering) {
1413 for (n = 0; n < n_reports; ++n) {
1414 if ((report_string[n] != (char*) NULL) &&
1415 s - temp >= (report_len = strlen(report_string[n])) &&
1416 strncmp(s - report_len, report_string[n], report_len) == 0) {
1417 time_t time_now = time ((time_t*) NULL);
1418 struct tm* tm_now = localtime (&time_now);
1420 strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1421 strcat (report_buffer, report_string[n]);
1423 report_string[n] = (char *) NULL;
1424 report_gathering = 1;
1425 break;
1429 else {
1430 if (!iscntrl (c)) {
1431 int rep_len = strlen (report_buffer);
1432 report_buffer[rep_len] = c;
1433 report_buffer[rep_len + 1] = '\0';
1435 else {
1436 report_gathering = 0;
1437 fprintf (report_fp, "chat: %s\n", report_buffer);
1441 if (s - temp >= len &&
1442 c == string[len - 1] &&
1443 strncmp(s - len, string, len) == 0) {
1444 if (verbose) {
1445 if (s > logged)
1446 logf("%0.*v", s - logged, logged);
1447 logf(" -- got it\n");
1450 alarm(0);
1451 alarmed = 0;
1452 return (1);
1455 for (n = 0; n < n_aborts; ++n) {
1456 if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1457 strncmp(s - abort_len, abort_string[n], abort_len) == 0) {
1458 if (verbose) {
1459 if (s > logged)
1460 logf("%0.*v", s - logged, logged);
1461 logf(" -- failed");
1464 alarm(0);
1465 alarmed = 0;
1466 exit_code = n + 4;
1467 strcpy(fail_reason = fail_buffer, abort_string[n]);
1468 return (0);
1472 if (s >= end) {
1473 if (logged < s - minlen) {
1474 if (verbose)
1475 logf("%0.*v", s - logged, logged);
1476 logged = s;
1478 s -= minlen;
1479 memmove(temp, s, minlen);
1480 logged = temp + (logged - s);
1481 s = temp + minlen;
1484 if (alarmed && verbose)
1485 logf("warning: alarm synchronization problem");
1488 alarm(0);
1490 if (verbose && printed) {
1491 if (alarmed)
1492 logf(" -- read timed out");
1493 else
1494 logf(" -- read failed: %m");
1497 exit_code = 3;
1498 alarmed = 0;
1499 return (0);
1503 * Gross kludge to handle Solaris versions >= 2.6 having usleep.
1505 #ifdef SOL2
1506 #include <sys/param.h>
1507 #if MAXUID > 65536 /* then this is Solaris 2.6 or later */
1508 #undef NO_USLEEP
1509 #endif
1510 #endif /* SOL2 */
1512 #ifdef NO_USLEEP
1513 #include <sys/types.h>
1514 #include <sys/time.h>
1517 usleep -- support routine for 4.2BSD system call emulations
1518 last edit: 29-Oct-1984 D A Gwyn
1521 extern int select();
1524 usleep( usec ) /* returns 0 if ok, else -1 */
1525 long usec; /* delay in microseconds */
1527 static struct { /* `timeval' */
1528 long tv_sec; /* seconds */
1529 long tv_usec; /* microsecs */
1530 } delay; /* _select() timeout */
1532 delay.tv_sec = usec / 1000000L;
1533 delay.tv_usec = usec % 1000000L;
1535 return select(0, (long *)0, (long *)0, (long *)0, &delay);
1537 #endif
1539 void
1540 pack_array (array, end)
1541 char **array; /* The address of the array of string pointers */
1542 int end; /* The index of the next free entry before CLR_ */
1544 int i, j;
1546 for (i = 0; i < end; i++) {
1547 if (array[i] == NULL) {
1548 for (j = i+1; j < end; ++j)
1549 if (array[j] != NULL)
1550 array[i++] = array[j];
1551 for (; i < end; ++i)
1552 array[i] = NULL;
1553 break;
1559 * vfmtmsg - format a message into a buffer. Like vsprintf except we
1560 * also specify the length of the output buffer, and we handle the
1561 * %m (error message) format.
1562 * Doesn't do floating-point formats.
1563 * Returns the number of chars put into buf.
1565 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1568 vfmtmsg(buf, buflen, fmt, args)
1569 char *buf;
1570 int buflen;
1571 const char *fmt;
1572 va_list args;
1574 int c, i, n;
1575 int width, prec, fillch;
1576 int base, len, neg, quoted;
1577 unsigned long val = 0;
1578 char *str, *buf0;
1579 const char *f;
1580 unsigned char *p;
1581 char num[32];
1582 static char hexchars[] = "0123456789abcdef";
1584 buf0 = buf;
1585 --buflen;
1586 while (buflen > 0) {
1587 for (f = fmt; *f != '%' && *f != 0; ++f)
1589 if (f > fmt) {
1590 len = f - fmt;
1591 if (len > buflen)
1592 len = buflen;
1593 memcpy(buf, fmt, len);
1594 buf += len;
1595 buflen -= len;
1596 fmt = f;
1598 if (*fmt == 0)
1599 break;
1600 c = *++fmt;
1601 width = prec = 0;
1602 fillch = ' ';
1603 if (c == '0') {
1604 fillch = '0';
1605 c = *++fmt;
1607 if (c == '*') {
1608 width = va_arg(args, int);
1609 c = *++fmt;
1610 } else {
1611 while (isdigit(c)) {
1612 width = width * 10 + c - '0';
1613 c = *++fmt;
1616 if (c == '.') {
1617 c = *++fmt;
1618 if (c == '*') {
1619 prec = va_arg(args, int);
1620 c = *++fmt;
1621 } else {
1622 while (isdigit(c)) {
1623 prec = prec * 10 + c - '0';
1624 c = *++fmt;
1628 str = 0;
1629 base = 0;
1630 neg = 0;
1631 ++fmt;
1632 switch (c) {
1633 case 'd':
1634 i = va_arg(args, int);
1635 if (i < 0) {
1636 neg = 1;
1637 val = -i;
1638 } else
1639 val = i;
1640 base = 10;
1641 break;
1642 case 'o':
1643 val = va_arg(args, unsigned int);
1644 base = 8;
1645 break;
1646 case 'x':
1647 val = va_arg(args, unsigned int);
1648 base = 16;
1649 break;
1650 case 'p':
1651 val = (unsigned long) va_arg(args, void *);
1652 base = 16;
1653 neg = 2;
1654 break;
1655 case 's':
1656 str = va_arg(args, char *);
1657 break;
1658 case 'c':
1659 num[0] = va_arg(args, int);
1660 num[1] = 0;
1661 str = num;
1662 break;
1663 case 'm':
1664 str = strerror(errno);
1665 break;
1666 case 'v': /* "visible" string */
1667 case 'q': /* quoted string */
1668 quoted = c == 'q';
1669 p = va_arg(args, unsigned char *);
1670 if (fillch == '0' && prec > 0) {
1671 n = prec;
1672 } else {
1673 n = strlen((char *)p);
1674 if (prec > 0 && prec < n)
1675 n = prec;
1677 while (n > 0 && buflen > 0) {
1678 c = *p++;
1679 --n;
1680 if (!quoted && c >= 0x80) {
1681 OUTCHAR('M');
1682 OUTCHAR('-');
1683 c -= 0x80;
1685 if (quoted && (c == '"' || c == '\\'))
1686 OUTCHAR('\\');
1687 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1688 if (quoted) {
1689 OUTCHAR('\\');
1690 switch (c) {
1691 case '\t': OUTCHAR('t'); break;
1692 case '\n': OUTCHAR('n'); break;
1693 case '\b': OUTCHAR('b'); break;
1694 case '\f': OUTCHAR('f'); break;
1695 default:
1696 OUTCHAR('x');
1697 OUTCHAR(hexchars[c >> 4]);
1698 OUTCHAR(hexchars[c & 0xf]);
1700 } else {
1701 if (c == '\t')
1702 OUTCHAR(c);
1703 else {
1704 OUTCHAR('^');
1705 OUTCHAR(c ^ 0x40);
1708 } else
1709 OUTCHAR(c);
1711 continue;
1712 default:
1713 *buf++ = '%';
1714 if (c != '%')
1715 --fmt; /* so %z outputs %z etc. */
1716 --buflen;
1717 continue;
1719 if (base != 0) {
1720 str = num + sizeof(num);
1721 *--str = 0;
1722 while (str > num + neg) {
1723 *--str = hexchars[val % base];
1724 val = val / base;
1725 if (--prec <= 0 && val == 0)
1726 break;
1728 switch (neg) {
1729 case 1:
1730 *--str = '-';
1731 break;
1732 case 2:
1733 *--str = 'x';
1734 *--str = '0';
1735 break;
1737 len = num + sizeof(num) - 1 - str;
1738 } else {
1739 len = strlen(str);
1740 if (prec > 0 && len > prec)
1741 len = prec;
1743 if (width > 0) {
1744 if (width > buflen)
1745 width = buflen;
1746 if ((n = width - len) > 0) {
1747 buflen -= n;
1748 for (; n > 0; --n)
1749 *buf++ = fillch;
1752 if (len > buflen)
1753 len = buflen;
1754 memcpy(buf, str, len);
1755 buf += len;
1756 buflen -= len;
1758 *buf = 0;
1759 return buf - buf0;