]> git.ozlabs.org Git - ppp.git/blob - chat/chat.c
declare alloca for SINIX
[ppp.git] / chat / chat.c
1 /*
2  *      Chat -- a program for automatic session establishment (i.e. dial
3  *              the phone and log in).
4  *
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.
13  *
14  *      This software is in the public domain.
15  *
16  *      Please send all bug reports, requests for information, etc. to:
17  *
18  *              Al Longyear (longyear@netcom.com)
19  *              (I was the last person to change this code.)
20  *
21  *      Added -r "report file" switch & REPORT keyword.
22  *              Robert Geer <bgeer@xmission.com>
23  *
24  *      Added -e "echo" switch & ECHO keyword
25  *              Dick Streefland <dicks@tasking.nl>
26  *
27  *      The original author is:
28  *
29  *              Karl Fox <karl@MorningStar.Com>
30  *              Morning Star Technologies, Inc.
31  *              1760 Zollinger Road
32  *              Columbus, OH  43221
33  *              (614)451-1883
34  *
35  */
36
37 static char rcsid[] = "$Id: chat.c,v 1.12 1996/06/26 00:51:06 paulus Exp $";
38
39 #include <stdio.h>
40 #include <time.h>
41 #include <fcntl.h>
42 #include <signal.h>
43 #include <errno.h>
44 #include <string.h>
45 #include <stdlib.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <syslog.h>
49
50 #ifndef TERMIO
51 #undef  TERMIOS
52 #define TERMIOS
53 #endif
54
55 #ifdef TERMIO
56 #include <termio.h>
57 #endif
58 #ifdef TERMIOS
59 #include <termios.h>
60 #endif
61
62 #define STR_LEN 1024
63
64 #ifndef SIGTYPE
65 #define SIGTYPE void
66 #endif
67
68 #ifdef __STDC__
69 #undef __P
70 #define __P(x)  x
71 #else
72 #define __P(x)  ()
73 #define const
74 #endif
75
76 #ifndef O_NONBLOCK
77 #define O_NONBLOCK      O_NDELAY
78 #endif
79
80 /*************** Micro getopt() *********************************************/
81 #define OPTION(c,v)     (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
82                                 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
83                                 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
84 #define OPTARG(c,v)     (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
85                                 (_O=4,(char*)0):(char*)0)
86 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
87 #define ARG(c,v)        (c?(--c,*v++):(char*)0)
88
89 static int _O = 0;              /* Internal state */
90 /*************** Micro getopt() *********************************************/
91
92 char *program_name;
93
94 #define MAX_ABORTS              50
95 #define MAX_REPORTS             50
96 #define DEFAULT_CHAT_TIMEOUT    45
97
98 int echo          = 0;
99 int verbose       = 0;
100 int Verbose       = 0;
101 int quiet         = 0;
102 int report        = 0;
103 int exit_code     = 0;
104 FILE* report_fp   = (FILE *) 0;
105 char *report_file = (char *) 0;
106 char *chat_file   = (char *) 0;
107 int timeout       = DEFAULT_CHAT_TIMEOUT;
108
109 int have_tty_parameters = 0;
110
111 #ifdef TERMIO
112 #define term_parms struct termio
113 #define get_term_param(param) ioctl(0, TCGETA, param)
114 #define set_term_param(param) ioctl(0, TCSETA, param)
115 struct termio saved_tty_parameters;
116 #endif
117
118 #ifdef TERMIOS
119 #define term_parms struct termios
120 #define get_term_param(param) tcgetattr(0, param)
121 #define set_term_param(param) tcsetattr(0, TCSANOW, param)
122 struct termios saved_tty_parameters;
123 #endif
124
125 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
126         fail_buffer[50];
127 int n_aborts = 0, abort_next = 0, timeout_next = 0, echo_next = 0;
128
129 char *report_string[MAX_REPORTS] ;
130 char  report_buffer[50] ;
131 int n_reports = 0, report_next = 0, report_gathering = 0 ; 
132
133 void *dup_mem __P((void *b, size_t c));
134 void *copy_of __P((char *s));
135 void usage __P((void));
136 void logf __P((const char *str));
137 void logflush __P((void));
138 void fatal __P((const char *msg));
139 void sysfatal __P((const char *msg));
140 SIGTYPE sigalrm __P((int signo));
141 SIGTYPE sigint __P((int signo));
142 SIGTYPE sigterm __P((int signo));
143 SIGTYPE sighup __P((int signo));
144 void unalarm __P((void));
145 void init __P((void));
146 void set_tty_parameters __P((void));
147 void echo_stderr __P((int));
148 void break_sequence __P((void));
149 void terminate __P((int status));
150 void do_file __P((char *chat_file));
151 int  get_string __P((register char *string));
152 int  put_string __P((register char *s));
153 int  write_char __P((int c));
154 int  put_char __P((int c));
155 int  get_char __P((void));
156 void chat_send __P((register char *s));
157 char *character __P((int c));
158 void chat_expect __P((register char *s));
159 char *clean __P((register char *s, int sending));
160 void break_sequence __P((void));
161 void terminate __P((int status));
162 void die __P((void));
163
164 void *dup_mem(b, c)
165 void *b;
166 size_t c;
167     {
168     void *ans = malloc (c);
169     if (!ans)
170         {
171         fatal ("memory error!\n");
172         }
173     memcpy (ans, b, c);
174     return ans;
175     }
176
177 void *copy_of (s)
178 char *s;
179     {
180     return dup_mem (s, strlen (s) + 1);
181     }
182
183 /*
184  *      chat [ -v ] [ -t timeout ] [ -f chat-file ] [ -r report-file ] \
185  *              [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
186  *
187  *      Perform a UUCP-dialer-like chat script on stdin and stdout.
188  */
189 int
190 main(argc, argv)
191 int argc;
192 char **argv;
193     {
194     int option;
195     char *arg;
196
197     program_name = *argv;
198     tzset();
199
200     while (option = OPTION(argc, argv))
201         {
202         switch (option)
203             {
204             case 'e':
205                 ++echo;
206                 break;
207
208             case 'v':
209                 ++verbose;
210                 break;
211
212             case 'V':
213                 ++Verbose;
214                 break;
215
216             case 'f':
217                 if (arg = OPTARG(argc, argv))
218                     {
219                     chat_file = copy_of(arg);
220                     }
221                 else
222                     {
223                     usage();
224                     }
225                 break;
226
227             case 't':
228                 if (arg = OPTARG(argc, argv))
229                     {
230                     timeout = atoi(arg);
231                     }
232                 else
233                     {
234                     usage();
235                     }
236                 break;
237
238             case 'r':
239                 arg = OPTARG (argc, argv);
240                 if (arg)
241                     {
242                     if (report_fp != NULL)
243                         {
244                         fclose (report_fp);
245                         }
246                     report_file = copy_of (arg);
247                     report_fp   = fopen (report_file, "a");
248                     if (report_fp != NULL)
249                         {
250                         if (verbose)
251                             {
252                             fprintf (report_fp, "Opening \"%s\"...\n",
253                                      report_file);
254                             }
255                         report = 1;
256                         }
257                     }
258                 break;
259
260             default:
261                 usage();
262                 break;
263             }
264       }
265 /*
266  * Default the report file to the stderr location
267  */
268     if (report_fp == NULL)
269         {
270         report_fp = stderr;
271         }
272
273 #ifdef ultrix
274     openlog("chat", LOG_PID);
275 #else
276     openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
277
278     if (verbose)
279         {
280         setlogmask(LOG_UPTO(LOG_INFO));
281         }
282     else
283         {
284         setlogmask(LOG_UPTO(LOG_WARNING));
285         }
286 #endif
287
288     init();
289     
290     if (chat_file != NULL)
291         {
292         arg = ARG(argc, argv);
293         if (arg != NULL)
294             {
295             usage();
296             }
297         else
298             {
299             do_file (chat_file);
300             }
301         }
302     else
303         {
304         while (arg = ARG(argc, argv))
305             {
306             chat_expect(arg);
307
308             if (arg = ARG(argc, argv))
309                 {
310                 chat_send(arg);
311                 }
312             }
313         }
314 /*
315  * Allow the last of the report string to be gathered before we terminate.
316  */
317     while (report_gathering)
318         {
319         int c;
320         c = get_char();
321         if (!iscntrl (c))
322             {
323             int rep_len = strlen (report_buffer);
324             report_buffer[rep_len]     = c;
325             report_buffer[rep_len + 1] = '\0';
326             }
327         else
328             {
329             report_gathering = 0;
330             fprintf (report_fp, "chat:  %s\n", report_buffer);
331             }
332         }
333
334     terminate(0);
335     }
336
337 /*
338  *  Process a chat script when read from a file.
339  */
340
341 void do_file (chat_file)
342 char *chat_file;
343     {
344     int linect, len, sendflg;
345     char *sp, *arg, quote;
346     char buf [STR_LEN];
347     FILE *cfp;
348
349     cfp = fopen (chat_file, "r");
350     if (cfp == NULL)
351         {
352         syslog (LOG_ERR, "%s -- open failed: %m", chat_file);
353         terminate (1);
354         }
355
356     linect = 0;
357     sendflg = 0;
358
359     while (fgets(buf, STR_LEN, cfp) != NULL)
360         {
361         sp = strchr (buf, '\n');
362         if (sp)
363             {
364             *sp = '\0';
365             }
366
367         linect++;
368         sp = buf;
369         while (*sp != '\0')
370             {
371             if (*sp == ' ' || *sp == '\t')
372                 {
373                 ++sp;
374                 continue;
375                 }
376
377             if (*sp == '"' || *sp == '\'')
378                 {
379                 quote = *sp++;
380                 arg = sp;
381                 while (*sp != quote)
382                     {
383                     if (*sp == '\0')
384                         {
385                         syslog (LOG_ERR, "unterminated quote (line %d)",
386                                 linect);
387                         terminate (1);
388                         }
389                     
390                     if (*sp++ == '\\')
391                         {
392                         if (*sp != '\0')
393                             {
394                             ++sp;
395                             }
396                         }
397                     }
398                 }
399             else
400                 {
401                 arg = sp;
402                 while (*sp != '\0' && *sp != ' ' && *sp != '\t')
403                     {
404                     ++sp;
405                     }
406                 }
407
408             if (*sp != '\0')
409                 {
410                 *sp++ = '\0';
411                 }
412
413             if (sendflg)
414                 {
415                 chat_send (arg);
416                 }
417             else
418                 {
419                 chat_expect (arg);
420                 }
421             sendflg = !sendflg;
422             }
423         }
424     fclose (cfp);
425     }
426
427 /*
428  *      We got an error parsing the command line.
429  */
430 void usage()
431     {
432     fprintf(stderr, "\
433 Usage: %s [-e] [-v] [-t timeout] [-r report-file] {-f chat-file | chat-script}\n",
434             program_name);
435     exit(1);
436     }
437
438 char line[256];
439 char *p;
440
441 void logf (str)
442 const char *str;
443     {
444     p = line + strlen(line);
445     strcat (p, str);
446
447     if (str[strlen(str)-1] == '\n')
448         {
449         syslog (LOG_INFO, "%s", line);
450         line[0] = 0;
451         }
452     }
453
454 void logflush()
455     {
456     if (line[0] != 0)
457         {
458         syslog(LOG_INFO, "%s", line);
459         line[0] = 0;
460         }
461     }
462
463 /*
464  *      Terminate with an error.
465  */
466 void die()
467     {
468     terminate(1);
469     }
470
471 /*
472  *      Print an error message and terminate.
473  */
474
475 void fatal (msg)
476 const char *msg;
477     {
478     syslog(LOG_ERR, "%s", msg);
479     terminate(2);
480     }
481
482 /*
483  *      Print an error message along with the system error message and
484  *      terminate.
485  */
486
487 void sysfatal (msg)
488 const char *msg;
489     {
490     syslog(LOG_ERR, "%s: %m", msg);
491     terminate(2);
492     }
493
494 int alarmed = 0;
495
496 SIGTYPE sigalrm(signo)
497 int signo;
498     {
499     int flags;
500
501     alarm(1);
502     alarmed = 1;                /* Reset alarm to avoid race window */
503     signal(SIGALRM, sigalrm);   /* that can cause hanging in read() */
504
505     logflush();
506     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
507         {
508         sysfatal("Can't get file mode flags on stdin");
509         }
510     else
511         {
512         if (fcntl(0, F_SETFL, flags | O_NONBLOCK) == -1)
513             {
514             sysfatal("Can't set file mode flags on stdin");
515             }
516         }
517
518     if (verbose)
519         {
520         syslog(LOG_INFO, "alarm");
521         }
522     }
523
524 void unalarm()
525     {
526     int flags;
527
528     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
529         {
530         sysfatal("Can't get file mode flags on stdin");
531         }
532     else
533         {
534         if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) == -1)
535             {
536             sysfatal("Can't set file mode flags on stdin");
537             }
538         }
539     }
540
541 SIGTYPE sigint(signo)
542 int signo;
543     {
544     fatal("SIGINT");
545     }
546
547 SIGTYPE sigterm(signo)
548 int signo;
549     {
550     fatal("SIGTERM");
551     }
552
553 SIGTYPE sighup(signo)
554 int signo;
555     {
556     fatal("SIGHUP");
557     }
558
559 void init()
560     {
561     signal(SIGINT, sigint);
562     signal(SIGTERM, sigterm);
563     signal(SIGHUP, sighup);
564
565     set_tty_parameters();
566     signal(SIGALRM, sigalrm);
567     alarm(0);
568     alarmed = 0;
569     }
570
571 void set_tty_parameters()
572     {
573 #if defined(get_term_param)
574     term_parms t;
575
576     if (get_term_param (&t) < 0)
577         {
578         sysfatal("Can't get terminal parameters");
579         }
580
581     saved_tty_parameters = t;
582     have_tty_parameters  = 1;
583
584     t.c_iflag     |= IGNBRK | ISTRIP | IGNPAR;
585     t.c_oflag      = 0;
586     t.c_lflag      = 0;
587     t.c_cc[VERASE] =
588     t.c_cc[VKILL]  = 0;
589     t.c_cc[VMIN]   = 1;
590     t.c_cc[VTIME]  = 0;
591
592     if (set_term_param (&t) < 0)
593         {
594         sysfatal("Can't set terminal parameters");
595         }
596 #endif
597     }
598
599 void break_sequence()
600     {
601 #ifdef TERMIOS
602     tcsendbreak (0, 0);
603 #endif
604     }
605
606 void terminate(status)
607 int status;
608     {
609     echo_stderr(-1);
610     if (report_file != (char *) 0 && report_fp != (FILE *) NULL)
611         {
612         if (verbose)
613             {
614             fprintf (report_fp, "Closing \"%s\".\n", report_file);
615             }
616         fclose (report_fp);
617         report_fp = (FILE *) NULL;
618         }
619
620 #if defined(get_term_param)
621     if (have_tty_parameters)
622         {
623         if (set_term_param (&saved_tty_parameters) < 0)
624             {
625             syslog(LOG_ERR, "Can't restore terminal parameters: %m");
626             exit(1);
627             }
628         }
629 #endif
630
631     exit(status);
632     }
633
634 /*
635  *      'Clean up' this string.
636  */
637 char *clean(s, sending)
638 register char *s;
639 int sending;
640     {
641     char temp[STR_LEN], cur_chr;
642     register char *s1;
643     int add_return = sending;
644 #define isoctal(chr) (((chr) >= '0') && ((chr) <= '7'))
645
646     s1 = temp;
647     while (*s)
648         {
649         cur_chr = *s++;
650         if (cur_chr == '^')
651             {
652             cur_chr = *s++;
653             if (cur_chr == '\0')
654                 {
655                 *s1++ = '^';
656                 break;
657                 }
658             cur_chr &= 0x1F;
659             if (cur_chr != 0)
660                 {
661                 *s1++ = cur_chr;
662                 }
663             continue;
664             }
665
666         if (cur_chr != '\\')
667             {
668             *s1++ = cur_chr;
669             continue;
670             }
671
672         cur_chr = *s++;
673         if (cur_chr == '\0')
674             {
675             if (sending)
676                 {
677                 *s1++ = '\\';
678                 *s1++ = '\\';
679                 }
680             break;
681             }
682
683         switch (cur_chr)
684             {
685         case 'b':
686             *s1++ = '\b';
687             break;
688
689         case 'c':
690             if (sending && *s == '\0')
691                 {
692                 add_return = 0;
693                 }
694             else
695                 {
696                 *s1++ = cur_chr;
697                 }
698             break;
699
700         case '\\':
701         case 'K':
702         case 'p':
703         case 'd':
704             if (sending)
705                 {
706                 *s1++ = '\\';
707                 }
708
709             *s1++ = cur_chr;
710             break;
711
712         case 'q':
713             quiet = ! quiet;
714             break;
715
716         case 'r':
717             *s1++ = '\r';
718             break;
719
720         case 'n':
721             *s1++ = '\n';
722             break;
723
724         case 's':
725             *s1++ = ' ';
726             break;
727
728         case 't':
729             *s1++ = '\t';
730             break;
731
732         case 'N':
733             if (sending)
734                 {
735                 *s1++ = '\\';
736                 *s1++ = '\0';
737                 }
738             else
739                 {
740                 *s1++ = 'N';
741                 }
742             break;
743             
744         default:
745             if (isoctal (cur_chr))
746                 {
747                 cur_chr &= 0x07;
748                 if (isoctal (*s))
749                     {
750                     cur_chr <<= 3;
751                     cur_chr |= *s++ - '0';
752                     if (isoctal (*s))
753                         {
754                         cur_chr <<= 3;
755                         cur_chr |= *s++ - '0';
756                         }
757                     }
758
759                 if (cur_chr != 0 || sending)
760                     {
761                     if (sending && (cur_chr == '\\' || cur_chr == 0))
762                         {
763                         *s1++ = '\\';
764                         }
765                     *s1++ = cur_chr;
766                     }
767                 break;
768                 }
769
770             if (sending)
771                 {
772                 *s1++ = '\\';
773                 }
774             *s1++ = cur_chr;
775             break;
776             }
777         }
778
779     if (add_return)
780         {
781         *s1++ = '\r';
782         }
783
784     *s1++ = '\0'; /* guarantee closure */
785     *s1++ = '\0'; /* terminate the string */
786     return dup_mem (temp, (size_t) (s1 - temp)); /* may have embedded nuls */
787     }
788
789 /*
790  * A modified version of 'strtok'. This version skips \ sequences.
791  */
792
793 char *expect_strtok (s, term)
794 char *s, *term;
795     {
796     static  char *str   = "";
797     int     escape_flag = 0;
798     char   *result;
799 /*
800  * If a string was specified then do initial processing.
801  */
802     if (s)
803         {
804         str = s;
805         }
806 /*
807  * If this is the escape flag then reset it and ignore the character.
808  */
809     if (*str)
810         {
811         result = str;
812         }
813     else
814         {
815         result = (char *) 0;
816         }
817
818     while (*str)
819         {
820         if (escape_flag)
821             {
822             escape_flag = 0;
823             ++str;
824             continue;
825             }
826
827         if (*str == '\\')
828             {
829             ++str;
830             escape_flag = 1;
831             continue;
832             }
833 /*
834  * If this is not in the termination string, continue.
835  */
836         if (strchr (term, *str) == (char *) 0)
837             {
838             ++str;
839             continue;
840             }
841 /*
842  * This is the terminator. Mark the end of the string and stop.
843  */
844         *str++ = '\0';
845         break;
846         }
847     return (result);
848     }
849
850 /*
851  * Process the expect string
852  */
853
854 void chat_expect (s)
855 char *s;
856     {
857     char *expect;
858     char *reply;
859
860     if (strcmp(s, "ABORT") == 0)
861         {
862         ++abort_next;
863         return;
864         }
865
866     if (strcmp(s, "REPORT") == 0)
867         {
868         ++report_next;
869         return;
870         }
871
872     if (strcmp(s, "TIMEOUT") == 0)
873         {
874         ++timeout_next;
875         return;
876         }
877
878     if (strcmp(s, "ECHO") == 0)
879         {
880         ++echo_next;
881         return;
882         }
883 /*
884  * Fetch the expect and reply string.
885  */
886     for (;;)
887         {
888         expect = expect_strtok (s, "-");
889         s      = (char *) 0;
890
891         if (expect == (char *) 0)
892             {
893             return;
894             }
895
896         reply = expect_strtok (s, "-");
897 /*
898  * Handle the expect string. If successful then exit.
899  */
900         if (get_string (expect))
901             {
902             return;
903             }
904 /*
905  * If there is a sub-reply string then send it. Otherwise any condition
906  * is terminal.
907  */
908         if (reply == (char *) 0 || exit_code != 3)
909             {
910             break;
911             }
912
913         chat_send (reply);
914         }
915 /*
916  * The expectation did not occur. This is terminal.
917  */
918     if (fail_reason)
919         {
920         syslog(LOG_INFO, "Failed (%s)", fail_reason);
921         }
922     else
923         {
924         syslog(LOG_INFO, "Failed");
925         }
926     terminate(exit_code);
927     }
928
929 /*
930  * Translate the input character to the appropriate string for printing
931  * the data.
932  */
933
934 char *character(c)
935 int c;
936     {
937     static char string[10];
938     char *meta;
939
940     meta = (c & 0x80) ? "M-" : "";
941     c &= 0x7F;
942
943     if (c < 32)
944         {
945         sprintf(string, "%s^%c", meta, (int)c + '@');
946         }
947     else
948         {
949         if (c == 127)
950             {
951             sprintf(string, "%s^?", meta);
952             }
953         else
954             {
955             sprintf(string, "%s%c", meta, c);
956             }
957         }
958
959     return (string);
960     }
961
962 /*
963  *  process the reply string
964  */
965 void chat_send (s)
966 register char *s;
967     {
968     if (echo_next)
969         {
970         echo_next = 0;
971         echo = (strcmp(s, "ON") == 0);
972         return;
973         }
974     if (abort_next)
975         {
976         char *s1;
977         
978         abort_next = 0;
979         
980         if (n_aborts >= MAX_ABORTS)
981             {
982             fatal("Too many ABORT strings");
983             }
984         
985         s1 = clean(s, 0);
986         
987         if (strlen(s1) > strlen(s)
988             || strlen(s1) + 1 > sizeof(fail_buffer))
989             {
990             syslog(LOG_WARNING, "Illegal or too-long ABORT string ('%s')", s);
991             die();
992             }
993
994         abort_string[n_aborts++] = s1;
995
996         if (verbose)
997             {
998             logf("abort on (");
999
1000             for (s1 = s; *s1; ++s1)
1001                 {
1002                 logf(character(*s1));
1003                 }
1004
1005             logf(")\n");
1006             }
1007         return;
1008         }
1009
1010     if (report_next)
1011         {
1012         char *s1;
1013         
1014         report_next = 0;
1015         if (n_reports >= MAX_REPORTS)
1016             {
1017             fatal("Too many REPORT strings");
1018             }
1019         
1020         s1 = clean(s, 0);
1021         
1022         if (strlen(s1) > strlen(s) || strlen(s1) > sizeof fail_buffer - 1)
1023             {
1024             syslog(LOG_WARNING, "Illegal or too-long REPORT string ('%s')", s);
1025             die();
1026             }
1027         
1028         report_string[n_reports++] = s1;
1029         
1030         if (verbose)
1031             {
1032             logf("report (");
1033             s1 = s;
1034             while (*s1)
1035                 {
1036                 logf(character(*s1));
1037                 ++s1;
1038                 }
1039             logf(")\n");
1040             }
1041         return;
1042         }
1043
1044     if (timeout_next)
1045         {
1046         timeout_next = 0;
1047         timeout = atoi(s);
1048         
1049         if (timeout <= 0)
1050             {
1051             timeout = DEFAULT_CHAT_TIMEOUT;
1052             }
1053
1054         if (verbose)
1055             {
1056             syslog(LOG_INFO, "timeout set to %d seconds", timeout);
1057             }
1058         return;
1059         }
1060
1061     if (strcmp(s, "EOT") == 0)
1062         {
1063         s = "^D\\c";
1064         }
1065     else
1066         {
1067         if (strcmp(s, "BREAK") == 0)
1068             {
1069             s = "\\K\\c";
1070             }
1071         }
1072
1073     if (!put_string(s))
1074         {
1075         syslog(LOG_INFO, "Failed");
1076         terminate(1);
1077         }
1078     }
1079
1080 int get_char()
1081     {
1082     int status;
1083     char c;
1084
1085     status = read(0, &c, 1);
1086
1087     switch (status)
1088         {
1089     case 1:
1090         return ((int)c & 0x7F);
1091
1092     default:
1093         syslog(LOG_WARNING, "warning: read() on stdin returned %d",
1094                status);
1095
1096     case -1:
1097         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1098             {
1099             sysfatal("Can't get file mode flags on stdin");
1100             }
1101         else
1102             {
1103             if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1104                 {
1105                 sysfatal("Can't set file mode flags on stdin");
1106                 }
1107             }
1108         
1109         return (-1);
1110         }
1111     }
1112
1113 int put_char(c)
1114 int c;
1115     {
1116     int status;
1117     char ch = c;
1118
1119     usleep(10000);              /* inter-character typing delay (?) */
1120
1121     status = write(1, &ch, 1);
1122
1123     switch (status)
1124         {
1125     case 1:
1126         return (0);
1127         
1128     default:
1129         syslog(LOG_WARNING, "warning: write() on stdout returned %d",
1130                status);
1131         
1132     case -1:
1133         if ((status = fcntl(0, F_GETFL, 0)) == -1)
1134             {
1135             sysfatal("Can't get file mode flags on stdin");
1136             }
1137         else
1138             {
1139             if (fcntl(0, F_SETFL, status & ~O_NONBLOCK) == -1)
1140                 {
1141                 sysfatal("Can't set file mode flags on stdin");
1142                 }
1143             }
1144         
1145         return (-1);
1146         }
1147     }
1148
1149 int write_char (c)
1150 int c;
1151     {
1152     if (alarmed || put_char(c) < 0)
1153         {
1154         extern int errno;
1155
1156         alarm(0);
1157         alarmed = 0;
1158
1159         if (verbose)
1160             {
1161             if (errno == EINTR || errno == EWOULDBLOCK)
1162                 {
1163                 syslog(LOG_INFO, " -- write timed out");
1164                 }
1165             else
1166                 {
1167                 syslog(LOG_INFO, " -- write failed: %m");
1168                 }
1169             }
1170         return (0);
1171         }
1172     return (1);
1173     }
1174
1175 int put_string (s)
1176 register char *s;
1177     {
1178     s = clean(s, 1);
1179
1180     if (verbose)
1181         {
1182         logf("send (");
1183
1184         if (quiet)
1185             {
1186             logf("??????");
1187             }
1188         else
1189             {
1190             register char *s1 = s;
1191
1192             for (s1 = s; *s1; ++s1)
1193                 {
1194                 logf(character(*s1));
1195                 }
1196             }
1197
1198         logf(")\n");
1199         }
1200
1201     alarm(timeout); alarmed = 0;
1202
1203     while (*s)
1204         {
1205         register char c = *s++;
1206
1207         if (c != '\\')
1208             {
1209             if (!write_char (c))
1210                 {
1211                 return 0;
1212                 }
1213             continue;
1214             }
1215
1216         c = *s++;
1217         switch (c)
1218             {
1219         case 'd':
1220             sleep(1);
1221             break;
1222
1223         case 'K':
1224             break_sequence();
1225             break;
1226
1227         case 'p':
1228             usleep(10000);      /* 1/100th of a second (arg is microseconds) */
1229             break;
1230
1231         default:
1232             if (!write_char (c))
1233                 return 0;
1234             break;
1235             }
1236         }
1237
1238     alarm(0);
1239     alarmed = 0;
1240     return (1);
1241     }
1242
1243 /*
1244  *      Echo a character to stderr.
1245  *      When called with -1, a '\n' character is generated when
1246  *      the cursor is not at the beginning of a line.
1247  */
1248 void echo_stderr(n)
1249 int n;
1250     {
1251         static int need_lf;
1252         char *s;
1253
1254         switch (n)
1255             {
1256         case '\r':              /* ignore '\r' */
1257             break;
1258         case -1:
1259             if (need_lf == 0)
1260                 break;
1261             /* fall through */
1262         case '\n':
1263             write(2, "\n", 1);
1264             need_lf = 0;
1265             break;
1266         default:
1267             s = character(n);
1268             write(2, s, strlen(s));
1269             need_lf = 1;
1270             break;
1271             }
1272     }
1273
1274 /*
1275  *      'Wait for' this string to appear on this file descriptor.
1276  */
1277 int get_string(string)
1278 register char *string;
1279     {
1280     char temp[STR_LEN];
1281     int c, printed = 0, len, minlen;
1282     register char *s = temp, *end = s + STR_LEN;
1283
1284     fail_reason = (char *)0;
1285     string = clean(string, 0);
1286     len = strlen(string);
1287     minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
1288
1289     if (verbose)
1290         {
1291         register char *s1;
1292
1293         logf("expect (");
1294
1295         for (s1 = string; *s1; ++s1)
1296             {
1297             logf(character(*s1));
1298             }
1299
1300         logf(")\n");
1301         }
1302
1303     if (len > STR_LEN)
1304         {
1305         syslog(LOG_INFO, "expect string is too long");
1306         exit_code = 1;
1307         return 0;
1308         }
1309
1310     if (len == 0)
1311         {
1312         if (verbose)
1313             {
1314             syslog(LOG_INFO, "got it");
1315             }
1316
1317         return (1);
1318         }
1319
1320     alarm(timeout);
1321     alarmed = 0;
1322
1323     while ( ! alarmed && (c = get_char()) >= 0)
1324         {
1325         int n, abort_len, report_len;
1326
1327         if (echo)
1328             {
1329             echo_stderr(c);
1330             }
1331         if (verbose)
1332             {
1333             if (c == '\n')
1334                 {
1335                 logf("\n");
1336                 }
1337             else
1338                 {
1339                 logf(character(c));
1340                 }
1341             }
1342
1343         if (Verbose) {
1344            if (c == '\n')      fputc( '\n', stderr );
1345            else if (c != '\r') fprintf( stderr, "%s", character(c) );
1346         }
1347
1348         *s++ = c;
1349
1350         if (!report_gathering)
1351             {
1352             for (n = 0; n < n_reports; ++n)
1353                 {
1354                 if ((report_string[n] != (char*) NULL) &&
1355                     s - temp >= (report_len = strlen(report_string[n])) &&
1356                     strncmp(s - report_len, report_string[n], report_len) == 0)
1357                     {
1358                     time_t time_now   = time ((time_t*) NULL);
1359                     struct tm* tm_now = localtime (&time_now);
1360
1361                     strftime (report_buffer, 20, "%b %d %H:%M:%S ", tm_now);
1362                     strcat (report_buffer, report_string[n]);
1363
1364                     report_string[n] = (char *) NULL;
1365                     report_gathering = 1;
1366                     break;
1367                     }
1368                 }
1369             }
1370         else
1371             {
1372             if (!iscntrl (c))
1373                 {
1374                 int rep_len = strlen (report_buffer);
1375                 report_buffer[rep_len]     = c;
1376                 report_buffer[rep_len + 1] = '\0';
1377                 }
1378             else
1379                 {
1380                 report_gathering = 0;
1381                 fprintf (report_fp, "chat:  %s\n", report_buffer);
1382                 }
1383             }
1384
1385         if (s - temp >= len &&
1386             c == string[len - 1] &&
1387             strncmp(s - len, string, len) == 0)
1388             {
1389             if (verbose)
1390                 {
1391                 logf(" -- got it\n");
1392                 }
1393
1394             alarm(0);
1395             alarmed = 0;
1396             return (1);
1397             }
1398
1399         for (n = 0; n < n_aborts; ++n)
1400             {
1401             if (s - temp >= (abort_len = strlen(abort_string[n])) &&
1402                 strncmp(s - abort_len, abort_string[n], abort_len) == 0)
1403                 {
1404                 if (verbose)
1405                     {
1406                     logf(" -- failed\n");
1407                     }
1408                 
1409                 alarm(0);
1410                 alarmed = 0;
1411                 exit_code = n + 4;
1412                 strcpy(fail_reason = fail_buffer, abort_string[n]);
1413                 return (0);
1414                 }
1415             }
1416
1417         if (s >= end)
1418             {
1419             strncpy (temp, s - minlen, minlen);
1420             s = temp + minlen;
1421             }
1422
1423         if (alarmed && verbose)
1424             {
1425             syslog(LOG_WARNING, "warning: alarm synchronization problem");
1426             }
1427         }
1428
1429     alarm(0);
1430     
1431     if (verbose && printed)
1432         {
1433         if (alarmed)
1434             {
1435             logf(" -- read timed out\n");
1436             }
1437         else
1438             {
1439             logflush();
1440             syslog(LOG_INFO, " -- read failed: %m");
1441             }
1442         }
1443
1444     exit_code = 3;
1445     alarmed   = 0;
1446     return (0);
1447     }
1448
1449 #ifdef NO_USLEEP
1450 #include <sys/types.h>
1451 #include <sys/time.h>
1452
1453 /*
1454   usleep -- support routine for 4.2BSD system call emulations
1455   last edit:  29-Oct-1984     D A Gwyn
1456   */
1457
1458 extern int        select();
1459
1460 int
1461 usleep( usec )                            /* returns 0 if ok, else -1 */
1462     long                usec;           /* delay in microseconds */
1463 {
1464     static struct                       /* `timeval' */
1465         {
1466         long    tv_sec;         /* seconds */
1467         long    tv_usec;        /* microsecs */
1468         } delay;            /* _select() timeout */
1469
1470     delay.tv_sec  = usec / 1000000L;
1471     delay.tv_usec = usec % 1000000L;
1472
1473     return select( 0, (long *)0, (long *)0, (long *)0, &delay );
1474 }
1475 #endif