]> git.ozlabs.org Git - ppp.git/blob - chat/chat.c
incorporate logwtmp in here
[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  *      This software is in the public domain.
6  *
7  *      Please send all bug reports, requests for information, etc. to:
8  *
9  *              Karl Fox <karl@MorningStar.Com>
10  *              Morning Star Technologies, Inc.
11  *              1760 Zollinger Road
12  *              Columbus, OH  43221
13  *              (614)451-1883
14  */
15
16 /*static char sccs_id[] = "@(#)chat.c   1.7";*/
17 static char rcsid[] = "$Id: chat.c,v 1.1 1994/05/20 05:32:16 paulus Exp $";
18
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <errno.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <varargs.h>
26 #include <syslog.h>
27
28 #ifndef TERMIO
29 #define TERMIOS
30 #endif
31
32 #ifdef sun
33 # if defined(SUNOS) && SUNOS >= 41
34 # ifndef HDB
35 #  define       HDB
36 # endif
37 # endif
38 #endif
39
40 #ifdef ultrix
41 #define SIGHAND_TYPE    int (*)()
42 #endif
43
44 #ifdef TERMIO
45 #include <termio.h>
46 #endif
47 #ifdef TERMIOS
48 #include <termios.h>
49 #endif
50
51 #define STR_LEN 1024
52
53 #ifndef SIGTYPE
54 #define SIGTYPE void
55 #endif
56
57 /*************** Micro getopt() *********************************************/
58 #define OPTION(c,v)     (_O&2&&**v?*(*v)++:!c||_O&4?0:(!(_O&1)&& \
59                                 (--c,++v),_O=4,c&&**v=='-'&&v[0][1]?*++*v=='-'\
60                                 &&!v[0][1]?(--c,++v,0):(_O=2,*(*v)++):0))
61 #define OPTARG(c,v)     (_O&2?**v||(++v,--c)?(_O=1,--c,*v++): \
62                                 (_O=4,(char*)0):(char*)0)
63 #define OPTONLYARG(c,v) (_O&2&&**v?(_O=1,--c,*v++):(char*)0)
64 #define ARG(c,v)        (c?(--c,*v++):(char*)0)
65
66 static int _O = 0;              /* Internal state */
67 /*************** Micro getopt() *********************************************/
68
69 char *program_name;
70
71 extern char *strcpy(), *strcat(), *malloc();
72 extern int strlen();
73 #define copyof(s)       ((s) ? strcpy(malloc(strlen(s) + 1), s) : (s))
74
75 #ifndef LOCK_DIR
76 # ifdef __NetBSD__
77 # define        PIDSTRING
78 # define        LOCK_DIR        "/var/spool/lock"
79 # else
80 #  ifdef HDB
81 #   define      PIDSTRING
82 #   define      LOCK_DIR        "/usr/spool/locks"
83 #  else /* HDB */
84 #   define      LOCK_DIR        "/usr/spool/uucp"
85 #  endif /* HDB */
86 # endif
87 #endif /* LOCK_DIR */
88
89 #define MAX_ABORTS              50
90 #define DEFAULT_CHAT_TIMEOUT    45
91
92 int verbose = 0;
93 int quiet = 0;
94 char *lock_file = (char *)0;
95 int timeout = DEFAULT_CHAT_TIMEOUT;
96
97 int have_tty_parameters = 0;
98 #ifdef TERMIO
99 struct termio saved_tty_parameters;
100 #endif
101 #ifdef TERMIOS
102 struct termios saved_tty_parameters;
103 #endif
104
105 char *abort_string[MAX_ABORTS], *fail_reason = (char *)0,
106         fail_buffer[50];
107 int n_aborts = 0, abort_next = 0, timeout_next = 0;
108
109 /*
110  *      chat [ -v ] [ -t timeout ] [ -l lock-file ] \
111  *              [...[[expect[-say[-expect...]] say expect[-say[-expect]] ...]]]
112  *
113  *      Perform a UUCP-dialer-like chat script on stdin and stdout.
114  */
115 main(argc, argv)
116 int argc;
117 char **argv;
118     {
119     int option, n;
120     char *arg;
121
122     program_name = *argv;
123
124     while (option = OPTION(argc, argv))
125         switch (option)
126             {
127             case 'v':
128                 ++verbose;
129                 break;
130
131             case 'l':
132                 if (arg = OPTARG(argc, argv))
133                     lock_file = copyof(arg);
134                 else
135                     usage();
136
137                 break;
138
139             case 't':
140                 if (arg = OPTARG(argc, argv))
141                     timeout = atoi(arg);
142                 else
143                     usage();
144
145                 break;
146
147             default:
148                 usage();
149             }
150
151 #ifdef ultrix
152     openlog("chat", LOG_PID);
153 #else
154     openlog("chat", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
155
156     if (verbose) {
157         setlogmask(LOG_UPTO(LOG_INFO));
158     } else {
159         setlogmask(LOG_UPTO(LOG_WARNING));
160     }
161 #endif
162
163
164     init();
165     
166     while (arg = ARG(argc, argv))
167         {
168         chat_expect(arg);
169
170         if (arg = ARG(argc, argv))
171             chat_send(arg);
172         }
173
174     terminate(0);
175     }
176
177 /*
178  *      We got an error parsing the command line.
179  */
180 usage()
181     {
182     fprintf(stderr,
183             "Usage: %s [ -v ] [ -l lock-file ] [ -t timeout ] chat-script\n",
184             program_name);
185     exit(1);
186     }
187
188 /*
189  *      Print a warning message.
190  */
191 /*VARARGS1*/
192 warn(format, arg1, arg2, arg3, arg4)
193 char *format;
194 int arg1, arg2, arg3, arg4;
195     {
196     logf("%s: Warning: ", program_name);
197     logf(format, arg1, arg2, arg3, arg4);
198     logf("\n");
199     }
200
201 /*
202  *      Print an error message and terminate.
203  */
204 /*VARARGS1*/
205 fatal(format, arg1, arg2, arg3, arg4)
206 char *format;
207 int arg1, arg2, arg3, arg4;
208     {
209     logf("%s: ", program_name);
210     logf(format, arg1, arg2, arg3, arg4);
211     logf("\n");
212     unlock();
213     terminate(1);
214     }
215
216 /*
217  *      Print an error message along with the system error message and
218  *      terminate.
219  */
220 /*VARARGS1*/
221 sysfatal(format, arg1, arg2, arg3, arg4)
222 char *format;
223 int arg1, arg2, arg3, arg4;
224     {
225     char message[STR_LEN];
226
227     sprintf(message, "%s: ", program_name);
228     sprintf(message + strlen(message), format, arg1, arg2, arg3, arg4);
229     perror(message);
230     unlock();
231     terminate(1);
232     }
233
234 int alarmed = 0;
235
236 SIGTYPE
237   sigalrm()
238 {
239     int flags;
240
241     alarm(1); alarmed = 1;      /* Reset alarm to avoid race window */
242     signal(SIGALRM, sigalrm);   /* that can cause hanging in read() */
243
244     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
245         sysfatal("Can't get file mode flags on stdin");
246     else
247         if (fcntl(0, F_SETFL, flags | FNDELAY) == -1)
248             sysfatal("Can't set file mode flags on stdin");
249
250     if (verbose)
251         {
252         logf("alarm\n");
253         }
254     }
255
256 unalarm()
257     {
258     int flags;
259
260     if ((flags = fcntl(0, F_GETFL, 0)) == -1)
261         sysfatal("Can't get file mode flags on stdin");
262     else
263         if (fcntl(0, F_SETFL, flags & ~FNDELAY) == -1)
264             sysfatal("Can't set file mode flags on stdin");
265     }
266
267 SIGTYPE
268   sigint()
269 {
270   fatal("SIGINT");
271 }
272
273 SIGTYPE
274   sigterm()
275 {
276   fatal("SIGTERM");
277 }
278
279 SIGTYPE
280   sighup()
281 {
282   fatal("SIGHUP");
283 }
284
285 init()
286     {
287     signal(SIGINT, sigint);
288     signal(SIGTERM, sigterm);
289     signal(SIGHUP, sighup);
290
291     if (lock_file)
292         lock();
293
294     set_tty_parameters();
295     signal(SIGALRM, sigalrm);
296     alarm(0); alarmed = 0;
297     }
298
299
300 set_tty_parameters()
301     {
302 #ifdef TERMIO
303     struct termio t;
304
305     if (ioctl(0, TCGETA, &t) < 0)
306         sysfatal("Can't get terminal parameters");
307 #endif
308 #ifdef TERMIOS
309     struct termios t;
310
311     if (tcgetattr(0, &t) < 0)
312         sysfatal("Can't get terminal parameters");
313 #endif
314
315     saved_tty_parameters = t;
316     have_tty_parameters = 1;
317
318     t.c_iflag = IGNBRK | ISTRIP | IGNPAR;
319     t.c_oflag = 0;
320     t.c_lflag = 0;
321     t.c_cc[VERASE] = t.c_cc[VKILL] = 0;
322     t.c_cc[VMIN] = 1;
323     t.c_cc[VTIME] = 0;
324
325 #ifdef TERMIO
326     if (ioctl(0, TCSETA, &t) < 0)
327         sysfatal("Can't set terminal parameters");
328 #endif
329 #ifdef TERMIOS
330     if (tcsetattr(0, TCSANOW, &t) < 0)
331         sysfatal("Can't set terminal parameters");
332 #endif
333     }
334
335
336 terminate(status)
337 {
338   if (have_tty_parameters &&
339 #ifdef TERMIO
340       ioctl(0, TCSETA, &saved_tty_parameters) < 0
341 #endif
342 #ifdef TERMIOS
343       tcsetattr(0, TCSANOW, &saved_tty_parameters) < 0
344 #endif
345       ) {
346     perror("Can't restore terminal parameters");
347     unlock();
348     exit(1);
349   }
350   exit(status);
351 }
352
353 /*
354  *      Create a lock file for the named lock device
355  */
356 lock()
357     {
358     char hdb_lock_buffer[12];
359     int fd, pid;
360
361     lock_file = strcat(strcat(strcpy(malloc(strlen(LOCK_DIR)
362                                        + 1 + strlen(lock_file) + 1),
363                                 LOCK_DIR), "/"), lock_file);
364
365     if ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0)
366         {
367         char *s = lock_file;
368
369         lock_file = (char *)0;  /* Don't remove someone else's lock file! */
370         sysfatal("Can't get lock file '%s'", s);
371         }
372
373 # ifdef PIDSTRING
374     sprintf(hdb_lock_buffer, "%10d\n", getpid());
375     write(fd, hdb_lock_buffer, 11);
376 # else
377     pid = getpid();
378     write(fd, &pid, sizeof pid);
379 # endif
380
381     close(fd);
382     }
383
384 /*
385  *      Remove our lockfile
386  */
387 unlock()
388     {
389     if (lock_file)
390         {
391         unlink(lock_file);
392         lock_file = (char *)0;
393         }
394     }
395
396 /*
397  *      'Clean up' this string.
398  */
399 char *clean(s, sending)
400 register char *s;
401 int sending;
402     {
403     char temp[STR_LEN];
404     register char *s1;
405     int add_return = sending;
406
407     for (s1 = temp; *s; ++s)
408          switch (*s)
409              {
410              case '\\':
411                  switch (*++s)
412                      {
413                      case '\\':
414                      case 'd':  if (sending)
415                                     *s1++ = '\\';
416
417                                 *s1++ = *s;
418                                 break;
419
420                      case 'q':  quiet = ! quiet; break;
421                      case 'r':  *s1++ = '\r'; break;
422                      case 'n':  *s1++ = '\n'; break;
423                      case 's':  *s1++ = ' '; break;
424
425                      case 'c':  if (sending && s[1] == '\0')
426                                     add_return = 0;
427                                 else
428                                     *s1++ = *s;
429
430                                 break;
431
432                      default:   *s1++ = *s;
433                      }
434
435                  break;
436
437              case '^':
438                  *s1++ = (int)(*++s) & 0x1F;
439                  break;
440
441              default:
442                  *s1++ = *s;
443              }
444     
445     if (add_return)
446         *s1++ = '\r';
447
448     *s1 = '\0';
449     return (copyof(temp));
450     }
451
452 /*
453  *
454  */
455 chat_expect(s)
456 register char *s;
457     {
458     if (strcmp(s, "ABORT") == 0)
459         {
460         ++abort_next;
461         return;
462         }
463
464     if (strcmp(s, "TIMEOUT") == 0)
465         {
466         ++timeout_next;
467         return;
468         }
469
470     while (*s)
471         {
472         register char *hyphen;
473
474         for (hyphen = s; *hyphen; ++hyphen)
475             if (*hyphen == '-')
476                 if (hyphen == s || hyphen[-1] != '\\')
477                     break;
478         
479         if (*hyphen == '-')
480             {
481             *hyphen = '\0';
482
483             if (get_string(s))
484                 return;
485             else
486                 {
487                 s = hyphen + 1;
488
489                 for (hyphen = s; *hyphen; ++hyphen)
490                     if (*hyphen == '-')
491                         if (hyphen == s || hyphen[-1] != '\\')
492                             break;
493
494                 if (*hyphen == '-')
495                     {
496                     *hyphen = '\0';
497
498                     chat_send(s);
499                     s = hyphen + 1;
500                     }
501                 else
502                     {
503                     chat_send(s);
504                     return;
505                     }
506                 }
507             }
508         else
509             if (get_string(s))
510                 return;
511             else
512                 {
513                 if (fail_reason)
514                     logf("Failed(%s)\n", fail_reason);
515                 else
516                     logf("Failed\n");
517
518                 unlock();
519                 terminate(1);
520                 }
521         }
522     }
523
524 char *character(c)
525 char c;
526     {
527     static char string[10];
528     char *meta;
529
530     meta = (c & 0x80) ? "M-" : "";
531     c &= 0x7F;
532
533     if (c < 32)
534         sprintf(string, "%s^%c", meta, (int)c + '@');
535     else
536         if (c == 127)
537             sprintf(string, "%s^?", meta);
538         else
539             sprintf(string, "%s%c", meta, c);
540
541     return (string);
542     }
543
544 /*
545  *
546  */
547 chat_send(s)
548 register char *s;
549     {
550     if (abort_next)
551         {
552         char *s1;
553
554         abort_next = 0;
555
556         if (n_aborts >= MAX_ABORTS)
557             fatal("Too many ABORT strings");
558
559         s1 = clean(s, 0);
560
561         if (strlen(s1) > strlen(s))
562             fatal("Illegal ABORT string ('%s')\n", s);
563
564         if (strlen(s1) > sizeof fail_buffer - 1)
565             fatal("Too long ABORT string ('%s')\n", s);
566
567         strcpy(s, s1);
568         abort_string[n_aborts++] = s;
569
570         if (verbose)
571             {
572             register char *s1 = s;
573
574             logf("abort on (");
575
576             for (s1 = s; *s1; ++s1)
577                 logf("%s", character(*s1));
578
579             logf(")\n");
580             }
581         }
582     else
583         if (timeout_next)
584             {
585             timeout_next = 0;
586             timeout = atoi(s);
587
588             if (timeout <= 0)
589                 timeout = DEFAULT_CHAT_TIMEOUT;
590
591             if (verbose)
592                 {
593                 logf("timeout set to %d seconds\n", timeout);
594                 }
595             }
596         else
597             if ( ! put_string(s))
598                 {
599                 logf("Failed\n");
600                 unlock();
601                 terminate(1);
602                 }
603     }
604
605 int get_char()
606     {
607     int status;
608     char c;
609
610     status = read(0, &c, 1);
611
612     switch (status)
613         {
614         case 1:
615             return ((int)c & 0x7F);
616
617         default:
618             warn("read() on stdin returned %d", status);
619
620         case -1:
621             if ((status = fcntl(0, F_GETFL, 0)) == -1)
622                 sysfatal("Can't get file mode flags on stdin");
623             else
624                 if (fcntl(0, F_SETFL, status & ~FNDELAY) == -1)
625                     sysfatal("Can't set file mode flags on stdin");
626
627             return (-1);
628         }
629     }
630
631 int put_char(c)
632 char c;
633     {
634     int status;
635
636     delay();
637
638     status = write(1, &c, 1);
639
640     switch (status)
641         {
642         case 1:
643             return (0);
644
645         default:
646             warn("write() on stdout returned %d", status);
647
648         case -1:
649             if ((status = fcntl(0, F_GETFL, 0)) == -1)
650                 sysfatal("Can't get file mode flags on stdin");
651             else
652                 if (fcntl(0, F_SETFL, status & ~FNDELAY) == -1)
653                     sysfatal("Can't set file mode flags on stdin");
654
655             return (-1);
656         }
657     }
658
659 int put_string(s)
660 register char *s;
661     {
662     s = clean(s, 1);
663
664     if (verbose)
665         {
666         logf("send (");
667
668         if (quiet)
669             logf("??????");
670         else
671             {
672             register char *s1 = s;
673
674             for (s1 = s; *s1; ++s1)
675                 logf("%s", character(*s1));
676             }
677
678         logf(")\n");
679         }
680
681     alarm(timeout); alarmed = 0;
682
683     for ( ; *s; ++s)
684         {
685         register char c = *s;
686
687         if (c == '\\')
688             if ((c = *++s) == '\0')
689                 break;
690             else
691                 if (c == 'd')           /* \d -- Delay */
692                     {
693                     sleep(2);
694                     continue;
695                     }
696
697         if (alarmed || put_char(*s) < 0)
698             {
699             extern int errno;
700
701             alarm(0); alarmed = 0;
702
703             if (verbose)
704                 {
705                 if (errno == EINTR || errno == EWOULDBLOCK)
706                     logf(" -- write timed out\n");
707                 else
708                     syslog(LOG_INFO, " -- write failed: %m");
709                 }
710
711             return (0);
712             }
713         }
714
715     alarm(0); alarmed = 0;
716     return (1);
717     }
718
719 /*
720  *      'Wait for' this string to appear on this file descriptor.
721  */
722 int get_string(string)
723 register char *string;
724     {
725     char temp[STR_LEN];
726     int c, printed = 0, len, minlen;
727     register char *s = temp, *end = s + STR_LEN;
728
729     fail_reason = (char *)0;
730     string = clean(string, 0);
731     len = strlen(string);
732     minlen = (len > sizeof(fail_buffer)? len: sizeof(fail_buffer)) - 1;
733
734     if (verbose)
735         {
736         register char *s1;
737
738         logf("expect (");
739
740         for (s1 = string; *s1; ++s1)
741             logf("%s", character(*s1));
742
743         logf(")\n");
744         }
745
746     if (len > STR_LEN)
747         {
748         logf("expect string is too long\n");
749         return;
750         }
751
752     if (len == 0)
753         {
754         if (verbose)
755             {
756             logf("got it\n");
757             }
758
759         return (1);
760         }
761
762     alarm(timeout); alarmed = 0;
763
764     while ( ! alarmed && (c = get_char()) >= 0)
765         {
766         int n, abort_len;
767
768         if (verbose)
769             {
770             if (c == '\n')
771                 logf("\n");
772             else
773                 logf("%s", character(c));
774             }
775
776         *s++ = c;
777
778         if (s - temp >= len &&
779             c == string[len - 1] &&
780             strncmp(s - len, string, len) == 0)
781             {
782             if (verbose)
783                 {
784                 logf("got it\n");
785                 }
786
787             alarm(0); alarmed = 0;
788             return (1);
789             }
790
791         for (n = 0; n < n_aborts; ++n)
792             if (s - temp >= (abort_len = strlen(abort_string[n])) &&
793                 strncmp(s - abort_len, abort_string[n], abort_len) == 0)
794                 {
795                 if (verbose)
796                     {
797                     logf(" -- failed\n");
798                     }
799
800                 alarm(0); alarmed = 0;
801                 strcpy(fail_reason = fail_buffer, abort_string[n]);
802                 return (0);
803                 }
804
805         if (s >= end)
806             {
807             strncpy(temp, s - minlen, minlen);
808             s = temp + minlen;
809             }
810
811         if (alarmed && verbose)
812             warn("Alarm synchronization problem");
813         }
814
815     alarm(0);
816     
817     if (verbose && printed)
818         {
819         extern int errno;
820
821         if (alarmed)
822             logf(" -- read timed out\n");
823         else
824             syslog(LOG_INFO, " -- read failed: %m");
825         }
826
827     alarmed = 0;
828     return (0);
829     }
830
831 /*
832  *      Delay an amount appropriate for between typed characters.
833  */
834 delay()
835     {
836     register int i;
837
838 # ifdef NO_USLEEP
839     for (i = 0; i < 30000; ++i)         /* ... did we just say appropriate? */
840         ;
841 # else /* NO_USLEEP */
842     usleep(100);
843 # endif /* NO_USLEEP */
844     }
845
846 char line[256];
847 char *p;
848
849 logf(fmt, va_alist)
850 char *fmt;
851 va_dcl
852 {
853     va_list pvar;
854     char buf[256];
855
856     va_start(pvar);
857     vsprintf(buf, fmt, pvar);
858     va_end(pvar);
859
860     p = line + strlen(line);
861     strcat(p, buf);
862
863     if (buf[strlen(buf)-1] == '\n') {
864         syslog(LOG_INFO, "%s", line);
865         line[0] = 0;
866     }
867 }
868 #ifdef ultrix
869 #include <sys/types.h>
870 #include <sys/time.h>
871
872 /*
873   usleep -- support routine for 4.2BSD system call emulations
874   last edit:  29-Oct-1984     D A Gwyn
875   */
876
877 extern int        select();
878
879 int
880 usleep( usec )                            /* returns 0 if ok, else -1 */
881     long                usec;           /* delay in microseconds */
882 {
883     static struct                       /* `timeval' */
884         {
885             long        tv_sec;         /* seconds */
886             long        tv_usec;        /* microsecs */
887         }   delay;          /* _select() timeout */
888
889     delay.tv_sec = usec / 1000000L;
890     delay.tv_usec = usec % 1000000L;
891
892     return select( 0, (long *)0, (long *)0, (long *)0, &delay );
893 }
894 #endif