chat.c revision 46686
1/*-
2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 *	$Id: chat.c,v 1.54 1999/02/12 00:52:29 brian Exp $
27 */
28
29#include <sys/param.h>
30#include <netinet/in.h>
31#include <netinet/in_systm.h>
32#include <netinet/ip.h>
33#include <sys/un.h>
34
35#include <errno.h>
36#include <fcntl.h>
37#include <paths.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <sys/wait.h>
42#include <termios.h>
43#include <unistd.h>
44
45#include "layer.h"
46#include "mbuf.h"
47#include "log.h"
48#include "defs.h"
49#include "timer.h"
50#include "lqr.h"
51#include "hdlc.h"
52#include "throughput.h"
53#include "fsm.h"
54#include "lcp.h"
55#include "ccp.h"
56#include "link.h"
57#include "async.h"
58#include "descriptor.h"
59#include "physical.h"
60#include "chat.h"
61#include "mp.h"
62#include "auth.h"
63#include "chap.h"
64#include "slcompress.h"
65#include "iplist.h"
66#include "ipcp.h"
67#include "filter.h"
68#include "cbcp.h"
69#include "command.h"
70#include "datalink.h"
71#ifndef NORADIUS
72#include "radius.h"
73#endif
74#include "bundle.h"
75
76#define BUFLEFT(c) (sizeof (c)->buf - ((c)->bufend - (c)->buf))
77
78static void ExecStr(struct physical *, char *, char *, int);
79static char *ExpandString(struct chat *, const char *, char *, int, int);
80
81static void
82chat_PauseTimer(void *v)
83{
84  struct chat *c = (struct chat *)v;
85  timer_Stop(&c->pause);
86  c->pause.load = 0;
87}
88
89static void
90chat_Pause(struct chat *c, u_long load)
91{
92  timer_Stop(&c->pause);
93  c->pause.load += load;
94  c->pause.func = chat_PauseTimer;
95  c->pause.name = "chat pause";
96  c->pause.arg = c;
97  timer_Start(&c->pause);
98}
99
100static void
101chat_TimeoutTimer(void *v)
102{
103  struct chat *c = (struct chat *)v;
104  timer_Stop(&c->timeout);
105  c->TimedOut = 1;
106}
107
108static void
109chat_SetTimeout(struct chat *c)
110{
111  timer_Stop(&c->timeout);
112  if (c->TimeoutSec > 0) {
113    c->timeout.load = SECTICKS * c->TimeoutSec;
114    c->timeout.func = chat_TimeoutTimer;
115    c->timeout.name = "chat timeout";
116    c->timeout.arg = c;
117    timer_Start(&c->timeout);
118  }
119}
120
121static char *
122chat_NextChar(char *ptr, char ch)
123{
124  for (; *ptr; ptr++)
125    if (*ptr == ch)
126      return ptr;
127    else if (*ptr == '\\')
128      if (*++ptr == '\0')
129        return NULL;
130
131  return NULL;
132}
133
134static int
135chat_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
136{
137  struct chat *c = descriptor2chat(d);
138  int special, gotabort, gottimeout, needcr;
139  int TimedOut = c->TimedOut;
140  static char arg_term;		/* An empty string */
141
142  if (c->pause.state == TIMER_RUNNING)
143    return 0;
144
145  if (TimedOut) {
146    log_Printf(LogCHAT, "Expect timeout\n");
147    if (c->nargptr == NULL)
148      c->state = CHAT_FAILED;
149    else {
150      /* c->state = CHAT_EXPECT; */
151      c->argptr = &arg_term;
152    }
153    c->TimedOut = 0;
154  }
155
156  if (c->state != CHAT_EXPECT && c->state != CHAT_SEND)
157    return 0;
158
159  gottimeout = gotabort = 0;
160
161  if (c->arg < c->argc && (c->arg < 0 || *c->argptr == '\0')) {
162    /* Go get the next string */
163    if (c->arg < 0 || c->state == CHAT_SEND)
164      c->state = CHAT_EXPECT;
165    else
166      c->state = CHAT_SEND;
167
168    special = 1;
169    while (special && (c->nargptr || c->arg < c->argc - 1)) {
170      if (c->arg < 0 || (!TimedOut && c->state == CHAT_SEND))
171        c->nargptr = NULL;
172
173      if (c->nargptr != NULL) {
174        /* We're doing expect-send-expect.... */
175        c->argptr = c->nargptr;
176        /* Put the '-' back in case we ever want to rerun our script */
177        c->nargptr[-1] = '-';
178        c->nargptr = chat_NextChar(c->nargptr, '-');
179        if (c->nargptr != NULL)
180          *c->nargptr++ = '\0';
181      } else {
182        int minus;
183
184        c->argptr = c->argv[++c->arg];
185
186        if (c->state == CHAT_EXPECT) {
187          /* Look for expect-send-expect sequence */
188          c->nargptr = c->argptr;
189          minus = 0;
190          while ((c->nargptr = chat_NextChar(c->nargptr, '-'))) {
191            c->nargptr++;
192            minus++;
193          }
194
195          if (minus % 2)
196            log_Printf(LogWARN, "chat_UpdateSet: \"%s\": Uneven number of"
197                      " '-' chars, all ignored\n", c->argptr);
198          else if (minus) {
199            c->nargptr = chat_NextChar(c->argptr, '-');
200            *c->nargptr++ = '\0';
201          }
202        }
203      }
204
205      /*
206       * c->argptr now temporarily points into c->script (via c->argv)
207       * If it's an expect-send-expect sequence, we've just got the correct
208       * portion of that sequence.
209       */
210
211      needcr = c->state == CHAT_SEND && *c->argptr != '!';
212
213      /* We leave room for a potential HDLC header in the target string */
214      ExpandString(c, c->argptr, c->exp + 2, sizeof c->exp - 2, needcr);
215
216      if (gotabort) {
217        if (c->abort.num < MAXABORTS) {
218          int len, i;
219
220          len = strlen(c->exp+2);
221          for (i = 0; i < c->abort.num; i++)
222            if (len > c->abort.string[i].len) {
223              int last;
224
225              for (last = c->abort.num; last > i; last--) {
226                c->abort.string[last].data = c->abort.string[last-1].data;
227                c->abort.string[last].len = c->abort.string[last-1].len;
228              }
229              break;
230            }
231          c->abort.string[i].len = len;
232          c->abort.string[i].data = (char *)malloc(len+1);
233          memcpy(c->abort.string[i].data, c->exp+2, len+1);
234          c->abort.num++;
235        } else
236          log_Printf(LogERROR, "chat_UpdateSet: too many abort strings\n");
237        gotabort = 0;
238      } else if (gottimeout) {
239        c->TimeoutSec = atoi(c->exp + 2);
240        if (c->TimeoutSec <= 0)
241          c->TimeoutSec = 30;
242        gottimeout = 0;
243      } else if (c->nargptr == NULL && !strcmp(c->exp+2, "ABORT"))
244        gotabort = 1;
245      else if (c->nargptr == NULL && !strcmp(c->exp+2, "TIMEOUT"))
246        gottimeout = 1;
247      else {
248        if (c->exp[2] == '!')
249          ExecStr(c->physical, c->exp + 3, c->exp + 2, sizeof c->exp - 2);
250
251        if (c->exp[2] == '\0') {
252          /* Empty string, reparse (this may be better as a `goto start') */
253          c->argptr = &arg_term;
254          return chat_UpdateSet(d, r, w, e, n);
255        }
256
257        special = 0;
258      }
259    }
260
261    if (special) {
262      if (gottimeout)
263        log_Printf(LogWARN, "chat_UpdateSet: TIMEOUT: Argument expected\n");
264      else if (gotabort)
265        log_Printf(LogWARN, "chat_UpdateSet: ABORT: Argument expected\n");
266
267      /* End of script - all ok */
268      c->state = CHAT_DONE;
269      return 0;
270    }
271
272    /* set c->argptr to point in the right place */
273    c->argptr = c->exp + 2;
274    c->arglen = strlen(c->argptr);
275
276    if (c->state == CHAT_EXPECT) {
277      /* We must check to see if the string's already been found ! */
278      char *begin, *end;
279
280      end = c->bufend - c->arglen + 1;
281      if (end < c->bufstart)
282        end = c->bufstart;
283      for (begin = c->bufstart; begin < end; begin++)
284        if (!strncmp(begin, c->argptr, c->arglen)) {
285          c->bufstart = begin + c->arglen;
286          c->argptr += c->arglen;
287          c->arglen = 0;
288          /* Continue - we've already read our expect string */
289          return chat_UpdateSet(d, r, w, e, n);
290        }
291
292      log_Printf(LogCHAT, "Expect(%d): %s\n", c->TimeoutSec, c->argptr);
293      chat_SetTimeout(c);
294    }
295  }
296
297  /*
298   * We now have c->argptr pointing at what we want to expect/send and
299   * c->state saying what we want to do... we now know what to put in
300   * the fd_set :-)
301   */
302
303  if (c->state == CHAT_EXPECT)
304    return physical_doUpdateSet(&c->physical->desc, r, NULL, e, n, 1);
305  else
306    return physical_doUpdateSet(&c->physical->desc, NULL, w, e, n, 1);
307}
308
309static int
310chat_IsSet(struct descriptor *d, const fd_set *fdset)
311{
312  struct chat *c = descriptor2chat(d);
313  return physical_IsSet(&c->physical->desc, fdset);
314}
315
316static void
317chat_UpdateLog(struct chat *c, int in)
318{
319  if (log_IsKept(LogCHAT) || log_IsKept(LogCONNECT)) {
320    /*
321     * If a linefeed appears in the last `in' characters of `c's input
322     * buffer, output from there, all the way back to the last linefeed.
323     * This is called for every read of `in' bytes.
324     */
325    char *ptr, *end, *stop, ch;
326    int level;
327
328    level = log_IsKept(LogCHAT) ? LogCHAT : LogCONNECT;
329    if (in == -1)
330      end = ptr = c->bufend;
331    else {
332      ptr = c->bufend - in;
333      for (end = c->bufend - 1; end >= ptr; end--)
334        if (*end == '\n')
335          break;
336    }
337
338    if (end >= ptr) {
339      for (ptr = c->bufend - (in == -1 ? 1 : in + 1); ptr >= c->bufstart; ptr--)
340        if (*ptr == '\n')
341          break;
342      ptr++;
343      stop = NULL;
344      while (stop < end) {
345        if ((stop = memchr(ptr, '\n', end - ptr)) == NULL)
346          stop = end;
347        ch = *stop;
348        *stop = '\0';
349        if (level == LogCHAT || strstr(ptr, "CONNECT"))
350          log_Printf(level, "Received: %s\n", ptr);
351        *stop = ch;
352        ptr = stop + 1;
353      }
354    }
355  }
356}
357
358static void
359chat_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
360{
361  struct chat *c = descriptor2chat(d);
362
363  if (c->state == CHAT_EXPECT) {
364    ssize_t in;
365    char *abegin, *ebegin, *begin, *aend, *eend, *end;
366    int n;
367
368    /*
369     * XXX - should this read only 1 byte to guarantee that we don't
370     * swallow any ppp talk from the peer ?
371     */
372    in = BUFLEFT(c);
373    if (in > sizeof c->buf / 2)
374      in = sizeof c->buf / 2;
375
376    in = physical_Read(c->physical, c->bufend, in);
377    if (in <= 0)
378      return;
379
380    /* `begin' and `end' delimit where we're going to strncmp() from */
381    ebegin = c->bufend - c->arglen + 1;
382    eend = ebegin + in;
383    if (ebegin < c->bufstart)
384      ebegin = c->bufstart;
385
386    if (c->abort.num) {
387      abegin = c->bufend - c->abort.string[0].len + 1;
388      aend = c->bufend - c->abort.string[c->abort.num-1].len + in + 1;
389      if (abegin < c->bufstart)
390        abegin = c->bufstart;
391    } else {
392      abegin = ebegin;
393      aend = eend;
394    }
395    begin = abegin < ebegin ? abegin : ebegin;
396    end = aend < eend ? eend : aend;
397
398    c->bufend += in;
399
400    chat_UpdateLog(c, in);
401
402    if (c->bufend > c->buf + sizeof c->buf / 2) {
403      /* Shuffle our receive buffer back a bit */
404      int chop;
405
406      for (chop = begin - c->buf; chop; chop--)
407        if (c->buf[chop] == '\n')
408          /* found some already-logged garbage to remove :-) */
409          break;
410
411      if (!chop)
412        chop = begin - c->buf;
413
414      if (chop) {
415        char *from, *to;
416
417        to = c->buf;
418        from = to + chop;
419        while (from < c->bufend)
420          *to++ = *from++;
421        c->bufstart -= chop;
422        c->bufend -= chop;
423        begin -= chop;
424        end -= chop;
425        abegin -= chop;
426        aend -= chop;
427        ebegin -= chop;
428        eend -= chop;
429      }
430    }
431
432    for (; begin < end; begin++)
433      if (begin >= ebegin && begin < eend &&
434          !strncmp(begin, c->argptr, c->arglen)) {
435        /* Got it ! */
436        timer_Stop(&c->timeout);
437        if (memchr(begin + c->arglen - 1, '\n',
438            c->bufend - begin - c->arglen + 1) == NULL) {
439          /* force it into the log */
440          end = c->bufend;
441          c->bufend = begin + c->arglen;
442          chat_UpdateLog(c, -1);
443          c->bufend = end;
444        }
445        c->bufstart = begin + c->arglen;
446        c->argptr += c->arglen;
447        c->arglen = 0;
448        break;
449      } else if (begin >= abegin && begin < aend) {
450        for (n = c->abort.num - 1; n >= 0; n--) {
451          if (begin + c->abort.string[n].len > c->bufend)
452            break;
453          if (!strncmp(begin, c->abort.string[n].data,
454                       c->abort.string[n].len)) {
455            if (memchr(begin + c->abort.string[n].len - 1, '\n',
456                c->bufend - begin - c->abort.string[n].len + 1) == NULL) {
457              /* force it into the log */
458              end = c->bufend;
459              c->bufend = begin + c->abort.string[n].len;
460              chat_UpdateLog(c, -1);
461              c->bufend = end;
462            }
463            c->bufstart = begin + c->abort.string[n].len;
464            c->state = CHAT_FAILED;
465            return;
466          }
467        }
468      }
469  }
470}
471
472static int
473chat_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
474{
475  struct chat *c = descriptor2chat(d);
476  int result = 0;
477
478  if (c->state == CHAT_SEND) {
479    int wrote;
480
481    if (strstr(c->argv[c->arg], "\\P"))            /* Don't log the password */
482      log_Printf(LogCHAT, "Send: %s\n", c->argv[c->arg]);
483    else {
484      int sz;
485
486      sz = c->arglen - 1;
487      while (sz >= 0 && c->argptr[sz] == '\n')
488        sz--;
489      log_Printf(LogCHAT, "Send: %.*s\n", sz + 1, c->argptr);
490    }
491
492    if (physical_IsSync(c->physical)) {
493      /* There's always room for the HDLC header */
494      c->argptr -= 2;
495      c->arglen += 2;
496      memcpy(c->argptr, "\377\003", 2);	/* Prepend HDLC header */
497    }
498
499    wrote = physical_Write(c->physical, c->argptr, c->arglen);
500    result = wrote ? 1 : 0;
501    if (wrote == -1) {
502      if (errno != EINTR)
503        log_Printf(LogERROR, "chat_Write: %s\n", strerror(errno));
504      if (physical_IsSync(c->physical)) {
505        c->argptr += 2;
506        c->arglen -= 2;
507      }
508    } else if (wrote < 2 && physical_IsSync(c->physical)) {
509      /* Oops - didn't even write our HDLC header ! */
510      c->argptr += 2;
511      c->arglen -= 2;
512    } else {
513      c->argptr += wrote;
514      c->arglen -= wrote;
515    }
516  }
517
518  return result;
519}
520
521void
522chat_Init(struct chat *c, struct physical *p, const char *data, int emptybuf,
523          const char *phone)
524{
525  c->desc.type = CHAT_DESCRIPTOR;
526  c->desc.UpdateSet = chat_UpdateSet;
527  c->desc.IsSet = chat_IsSet;
528  c->desc.Read = chat_Read;
529  c->desc.Write = chat_Write;
530  c->physical = p;
531
532  c->state = CHAT_EXPECT;
533
534  if (data == NULL) {
535    *c->script = '\0';
536    c->argc = 0;
537  } else {
538    strncpy(c->script, data, sizeof c->script - 1);
539    c->script[sizeof c->script - 1] = '\0';
540    c->argc =  MakeArgs(c->script, c->argv, VECSIZE(c->argv));
541  }
542
543  c->arg = -1;
544  c->argptr = NULL;
545  c->nargptr = NULL;
546
547  if (emptybuf)
548    c->bufstart = c->bufend = c->buf;
549
550  c->TimeoutSec = 30;
551  c->TimedOut = 0;
552  c->phone = phone;
553  c->abort.num = 0;
554
555  memset(&c->pause, '\0', sizeof c->pause);
556  memset(&c->timeout, '\0', sizeof c->timeout);
557}
558
559void
560chat_Destroy(struct chat *c)
561{
562  timer_Stop(&c->pause);
563  timer_Stop(&c->timeout);
564  while (c->abort.num)
565    free(c->abort.string[--c->abort.num].data);
566  c->abort.num = 0;
567}
568
569/*
570 *  \c	don't add a cr
571 *  \d  Sleep a little (delay 2 seconds
572 *  \n  Line feed character
573 *  \P  Auth Key password
574 *  \p  pause 0.25 sec
575 *  \r	Carrige return character
576 *  \s  Space character
577 *  \T  Telephone number(s) (defined via `set phone')
578 *  \t  Tab character
579 *  \U  Auth User
580 */
581static char *
582ExpandString(struct chat *c, const char *str, char *result, int reslen,
583                  int sendmode)
584{
585  int addcr = 0;
586
587  result[--reslen] = '\0';
588  if (sendmode)
589    addcr = 1;
590  while (*str && reslen > 0) {
591    switch (*str) {
592    case '\\':
593      str++;
594      switch (*str) {
595      case 'c':
596	if (sendmode)
597	  addcr = 0;
598	break;
599      case 'd':		/* Delay 2 seconds */
600        chat_Pause(c, 2 * SECTICKS);
601	break;
602      case 'p':
603        chat_Pause(c, SECTICKS / 4);
604	break;			/* Pause 0.25 sec */
605      case 'n':
606	*result++ = '\n';
607	reslen--;
608	break;
609      case 'r':
610	*result++ = '\r';
611	reslen--;
612	break;
613      case 's':
614	*result++ = ' ';
615	reslen--;
616	break;
617      case 't':
618	*result++ = '\t';
619	reslen--;
620	break;
621      case 'P':
622	strncpy(result, c->physical->dl->bundle->cfg.auth.key, reslen);
623	reslen -= strlen(result);
624	result += strlen(result);
625	break;
626      case 'T':
627        if (c->phone) {
628          strncpy(result, c->phone, reslen);
629          reslen -= strlen(result);
630          result += strlen(result);
631        }
632	break;
633      case 'U':
634	strncpy(result, c->physical->dl->bundle->cfg.auth.name, reslen);
635	reslen -= strlen(result);
636	result += strlen(result);
637	break;
638      default:
639	reslen--;
640	*result++ = *str;
641	break;
642      }
643      if (*str)
644	str++;
645      break;
646    case '^':
647      str++;
648      if (*str) {
649	*result++ = *str++ & 0x1f;
650	reslen--;
651      }
652      break;
653    default:
654      *result++ = *str++;
655      reslen--;
656      break;
657    }
658  }
659  if (--reslen > 0) {
660    if (addcr)
661      *result++ = '\r';
662  }
663  if (--reslen > 0)
664    *result++ = '\0';
665  return (result);
666}
667
668static void
669ExecStr(struct physical *physical, char *command, char *out, int olen)
670{
671  pid_t pid;
672  int fids[2];
673  char *argv[MAXARGS], *vector[MAXARGS], *startout, *endout;
674  int stat, nb, argc;
675
676  log_Printf(LogCHAT, "Exec: %s\n", command);
677  argc = MakeArgs(command, vector, VECSIZE(vector));
678  command_Expand(argv, argc, (char const *const *)vector,
679                 physical->dl->bundle, 0);
680
681  if (pipe(fids) < 0) {
682    log_Printf(LogCHAT, "Unable to create pipe in ExecStr: %s\n",
683	      strerror(errno));
684    *out = '\0';
685    return;
686  }
687  if ((pid = fork()) == 0) {
688    close(fids[0]);
689    timer_TermService();
690    fids[1] = fcntl(fids[1], F_DUPFD, 4);
691    dup2(physical->fd, STDIN_FILENO);
692    dup2(STDIN_FILENO, STDOUT_FILENO);
693    dup2(fids[1], STDERR_FILENO);
694    close(3);
695    if (open(_PATH_TTY, O_RDWR) == 3)
696      fcntl(3, F_SETFD, 0);	/* Clear close-on-exec flag */
697    else
698      fcntl(3, F_SETFD, 1);	/* Set close-on-exec flag */
699    setuid(geteuid());
700    execvp(argv[0], argv);
701    fprintf(stderr, "execvp: %s: %s\n", argv[0], strerror(errno));
702    exit(127);
703  } else {
704    char *name = strdup(vector[0]);
705
706    close(fids[1]);
707    endout = out + olen - 1;
708    startout = out;
709    while (out < endout) {
710      nb = read(fids[0], out, 1);
711      if (nb <= 0)
712	break;
713      out++;
714    }
715    *out = '\0';
716    close(fids[0]);
717    close(fids[1]);
718    waitpid(pid, &stat, WNOHANG);
719    if (WIFSIGNALED(stat)) {
720      log_Printf(LogWARN, "%s: signal %d\n", name, WTERMSIG(stat));
721      free(name);
722      *out = '\0';
723      return;
724    } else if (WIFEXITED(stat)) {
725      switch (WEXITSTATUS(stat)) {
726        case 0:
727          free(name);
728          break;
729        case 127:
730          log_Printf(LogWARN, "%s: %s\n", name, startout);
731          free(name);
732          *out = '\0';
733          return;
734          break;
735        default:
736          log_Printf(LogWARN, "%s: exit %d\n", name, WEXITSTATUS(stat));
737          free(name);
738          *out = '\0';
739          return;
740          break;
741      }
742    } else {
743      log_Printf(LogWARN, "%s: Unexpected exit result\n", name);
744      free(name);
745      *out = '\0';
746      return;
747    }
748  }
749}
750