chat.c revision 47849
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.56 1999/05/27 09:50:10 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      /*
217       * Now read our string.  If it's not a special string, we unset
218       * ``special'' to break out of the loop.
219       */
220      if (gotabort) {
221        if (c->abort.num < MAXABORTS) {
222          int len, i;
223
224          len = strlen(c->exp+2);
225          for (i = 0; i < c->abort.num; i++)
226            if (len > c->abort.string[i].len) {
227              int last;
228
229              for (last = c->abort.num; last > i; last--) {
230                c->abort.string[last].data = c->abort.string[last-1].data;
231                c->abort.string[last].len = c->abort.string[last-1].len;
232              }
233              break;
234            }
235          c->abort.string[i].len = len;
236          c->abort.string[i].data = (char *)malloc(len+1);
237          memcpy(c->abort.string[i].data, c->exp+2, len+1);
238          c->abort.num++;
239        } else
240          log_Printf(LogERROR, "chat_UpdateSet: too many abort strings\n");
241        gotabort = 0;
242      } else if (gottimeout) {
243        c->TimeoutSec = atoi(c->exp + 2);
244        if (c->TimeoutSec <= 0)
245          c->TimeoutSec = 30;
246        gottimeout = 0;
247      } else if (c->nargptr == NULL && !strcmp(c->exp+2, "ABORT"))
248        gotabort = 1;
249      else if (c->nargptr == NULL && !strcmp(c->exp+2, "TIMEOUT"))
250        gottimeout = 1;
251      else {
252        if (c->exp[2] == '!')
253          ExecStr(c->physical, c->exp + 3, c->exp + 2, sizeof c->exp - 2);
254
255        if (c->exp[2] == '\0') {
256          /* Empty string, reparse (this may be better as a `goto start') */
257          c->argptr = &arg_term;
258          return chat_UpdateSet(d, r, w, e, n);
259        }
260
261        special = 0;
262      }
263    }
264
265    if (special) {
266      if (gottimeout)
267        log_Printf(LogWARN, "chat_UpdateSet: TIMEOUT: Argument expected\n");
268      else if (gotabort)
269        log_Printf(LogWARN, "chat_UpdateSet: ABORT: Argument expected\n");
270
271      /* End of script - all ok */
272      c->state = CHAT_DONE;
273      return 0;
274    }
275
276    /* set c->argptr to point in the right place */
277    c->argptr = c->exp + 2;
278    c->arglen = strlen(c->argptr);
279
280    if (c->state == CHAT_EXPECT) {
281      /* We must check to see if the string's already been found ! */
282      char *begin, *end;
283
284      end = c->bufend - c->arglen + 1;
285      if (end < c->bufstart)
286        end = c->bufstart;
287      for (begin = c->bufstart; begin < end; begin++)
288        if (!strncmp(begin, c->argptr, c->arglen)) {
289          c->bufstart = begin + c->arglen;
290          c->argptr += c->arglen;
291          c->arglen = 0;
292          /* Continue - we've already read our expect string */
293          return chat_UpdateSet(d, r, w, e, n);
294        }
295
296      log_Printf(LogCHAT, "Expect(%d): %s\n", c->TimeoutSec, c->argptr);
297      chat_SetTimeout(c);
298    }
299  }
300
301  /*
302   * We now have c->argptr pointing at what we want to expect/send and
303   * c->state saying what we want to do... we now know what to put in
304   * the fd_set :-)
305   */
306
307  if (c->state == CHAT_EXPECT)
308    return physical_doUpdateSet(&c->physical->desc, r, NULL, e, n, 1);
309  else
310    return physical_doUpdateSet(&c->physical->desc, NULL, w, e, n, 1);
311}
312
313static int
314chat_IsSet(struct descriptor *d, const fd_set *fdset)
315{
316  struct chat *c = descriptor2chat(d);
317  return physical_IsSet(&c->physical->desc, fdset);
318}
319
320static void
321chat_UpdateLog(struct chat *c, int in)
322{
323  if (log_IsKept(LogCHAT) || log_IsKept(LogCONNECT)) {
324    /*
325     * If a linefeed appears in the last `in' characters of `c's input
326     * buffer, output from there, all the way back to the last linefeed.
327     * This is called for every read of `in' bytes.
328     */
329    char *ptr, *end, *stop, ch;
330    int level;
331
332    level = log_IsKept(LogCHAT) ? LogCHAT : LogCONNECT;
333    if (in == -1)
334      end = ptr = c->bufend;
335    else {
336      ptr = c->bufend - in;
337      for (end = c->bufend - 1; end >= ptr; end--)
338        if (*end == '\n')
339          break;
340    }
341
342    if (end >= ptr) {
343      for (ptr = c->bufend - (in == -1 ? 1 : in + 1); ptr >= c->bufstart; ptr--)
344        if (*ptr == '\n')
345          break;
346      ptr++;
347      stop = NULL;
348      while (stop < end) {
349        if ((stop = memchr(ptr, '\n', end - ptr)) == NULL)
350          stop = end;
351        ch = *stop;
352        *stop = '\0';
353        if (level == LogCHAT || strstr(ptr, "CONNECT"))
354          log_Printf(level, "Received: %s\n", ptr);
355        *stop = ch;
356        ptr = stop + 1;
357      }
358    }
359  }
360}
361
362static void
363chat_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
364{
365  struct chat *c = descriptor2chat(d);
366
367  if (c->state == CHAT_EXPECT) {
368    ssize_t in;
369    char *abegin, *ebegin, *begin, *aend, *eend, *end;
370    int n;
371
372    /*
373     * XXX - should this read only 1 byte to guarantee that we don't
374     * swallow any ppp talk from the peer ?
375     */
376    in = BUFLEFT(c);
377    if (in > sizeof c->buf / 2)
378      in = sizeof c->buf / 2;
379
380    in = physical_Read(c->physical, c->bufend, in);
381    if (in <= 0)
382      return;
383
384    /* `begin' and `end' delimit where we're going to strncmp() from */
385    ebegin = c->bufend - c->arglen + 1;
386    eend = ebegin + in;
387    if (ebegin < c->bufstart)
388      ebegin = c->bufstart;
389
390    if (c->abort.num) {
391      abegin = c->bufend - c->abort.string[0].len + 1;
392      aend = c->bufend - c->abort.string[c->abort.num-1].len + in + 1;
393      if (abegin < c->bufstart)
394        abegin = c->bufstart;
395    } else {
396      abegin = ebegin;
397      aend = eend;
398    }
399    begin = abegin < ebegin ? abegin : ebegin;
400    end = aend < eend ? eend : aend;
401
402    c->bufend += in;
403
404    chat_UpdateLog(c, in);
405
406    if (c->bufend > c->buf + sizeof c->buf / 2) {
407      /* Shuffle our receive buffer back a bit */
408      int chop;
409
410      for (chop = begin - c->buf; chop; chop--)
411        if (c->buf[chop] == '\n')
412          /* found some already-logged garbage to remove :-) */
413          break;
414
415      if (!chop)
416        chop = begin - c->buf;
417
418      if (chop) {
419        char *from, *to;
420
421        to = c->buf;
422        from = to + chop;
423        while (from < c->bufend)
424          *to++ = *from++;
425        c->bufstart -= chop;
426        c->bufend -= chop;
427        begin -= chop;
428        end -= chop;
429        abegin -= chop;
430        aend -= chop;
431        ebegin -= chop;
432        eend -= chop;
433      }
434    }
435
436    for (; begin < end; begin++)
437      if (begin >= ebegin && begin < eend &&
438          !strncmp(begin, c->argptr, c->arglen)) {
439        /* Got it ! */
440        timer_Stop(&c->timeout);
441        if (memchr(begin + c->arglen - 1, '\n',
442            c->bufend - begin - c->arglen + 1) == NULL) {
443          /* force it into the log */
444          end = c->bufend;
445          c->bufend = begin + c->arglen;
446          chat_UpdateLog(c, -1);
447          c->bufend = end;
448        }
449        c->bufstart = begin + c->arglen;
450        c->argptr += c->arglen;
451        c->arglen = 0;
452        break;
453      } else if (begin >= abegin && begin < aend) {
454        for (n = c->abort.num - 1; n >= 0; n--) {
455          if (begin + c->abort.string[n].len > c->bufend)
456            break;
457          if (!strncmp(begin, c->abort.string[n].data,
458                       c->abort.string[n].len)) {
459            if (memchr(begin + c->abort.string[n].len - 1, '\n',
460                c->bufend - begin - c->abort.string[n].len + 1) == NULL) {
461              /* force it into the log */
462              end = c->bufend;
463              c->bufend = begin + c->abort.string[n].len;
464              chat_UpdateLog(c, -1);
465              c->bufend = end;
466            }
467            c->bufstart = begin + c->abort.string[n].len;
468            c->state = CHAT_FAILED;
469            return;
470          }
471        }
472      }
473  }
474}
475
476static int
477chat_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
478{
479  struct chat *c = descriptor2chat(d);
480  int result = 0;
481
482  if (c->state == CHAT_SEND) {
483    int wrote;
484
485    if (strstr(c->argv[c->arg], "\\P"))            /* Don't log the password */
486      log_Printf(LogCHAT, "Send: %s\n", c->argv[c->arg]);
487    else {
488      int sz;
489
490      sz = c->arglen - 1;
491      while (sz >= 0 && c->argptr[sz] == '\n')
492        sz--;
493      log_Printf(LogCHAT, "Send: %.*s\n", sz + 1, c->argptr);
494    }
495
496    if (physical_IsSync(c->physical)) {
497      /*
498       * XXX: Fix me
499       * This data should be stuffed down through the link layers
500       */
501      /* There's always room for the HDLC header */
502      c->argptr -= 2;
503      c->arglen += 2;
504      memcpy(c->argptr, "\377\003", 2);	/* Prepend HDLC header */
505    }
506
507    wrote = physical_Write(c->physical, c->argptr, c->arglen);
508    result = wrote ? 1 : 0;
509    if (wrote == -1) {
510      if (errno != EINTR)
511        log_Printf(LogERROR, "chat_Write: %s\n", strerror(errno));
512      if (physical_IsSync(c->physical)) {
513        c->argptr += 2;
514        c->arglen -= 2;
515      }
516    } else if (wrote < 2 && physical_IsSync(c->physical)) {
517      /* Oops - didn't even write our HDLC header ! */
518      c->argptr += 2;
519      c->arglen -= 2;
520    } else {
521      c->argptr += wrote;
522      c->arglen -= wrote;
523    }
524  }
525
526  return result;
527}
528
529void
530chat_Init(struct chat *c, struct physical *p, const char *data, int emptybuf,
531          const char *phone)
532{
533  c->desc.type = CHAT_DESCRIPTOR;
534  c->desc.UpdateSet = chat_UpdateSet;
535  c->desc.IsSet = chat_IsSet;
536  c->desc.Read = chat_Read;
537  c->desc.Write = chat_Write;
538  c->physical = p;
539
540  c->state = CHAT_EXPECT;
541
542  if (data == NULL) {
543    *c->script = '\0';
544    c->argc = 0;
545  } else {
546    strncpy(c->script, data, sizeof c->script - 1);
547    c->script[sizeof c->script - 1] = '\0';
548    c->argc =  MakeArgs(c->script, c->argv, VECSIZE(c->argv));
549  }
550
551  c->arg = -1;
552  c->argptr = NULL;
553  c->nargptr = NULL;
554
555  if (emptybuf)
556    c->bufstart = c->bufend = c->buf;
557
558  c->TimeoutSec = 30;
559  c->TimedOut = 0;
560  c->phone = phone;
561  c->abort.num = 0;
562
563  memset(&c->pause, '\0', sizeof c->pause);
564  memset(&c->timeout, '\0', sizeof c->timeout);
565}
566
567void
568chat_Destroy(struct chat *c)
569{
570  timer_Stop(&c->pause);
571  timer_Stop(&c->timeout);
572  while (c->abort.num)
573    free(c->abort.string[--c->abort.num].data);
574  c->abort.num = 0;
575}
576
577/*
578 *  \c	don't add a cr
579 *  \d  Sleep a little (delay 2 seconds
580 *  \n  Line feed character
581 *  \P  Auth Key password
582 *  \p  pause 0.25 sec
583 *  \r	Carrige return character
584 *  \s  Space character
585 *  \T  Telephone number(s) (defined via `set phone')
586 *  \t  Tab character
587 *  \U  Auth User
588 */
589static char *
590ExpandString(struct chat *c, const char *str, char *result, int reslen, int cr)
591{
592  int len;
593
594  result[--reslen] = '\0';
595  while (*str && reslen > 0) {
596    switch (*str) {
597    case '\\':
598      str++;
599      switch (*str) {
600      case 'c':
601	cr = 0;
602	break;
603      case 'd':		/* Delay 2 seconds */
604        chat_Pause(c, 2 * SECTICKS);
605	break;
606      case 'p':
607        chat_Pause(c, SECTICKS / 4);
608	break;		/* Delay 0.25 seconds */
609      case 'n':
610	*result++ = '\n';
611	reslen--;
612	break;
613      case 'r':
614	*result++ = '\r';
615	reslen--;
616	break;
617      case 's':
618	*result++ = ' ';
619	reslen--;
620	break;
621      case 't':
622	*result++ = '\t';
623	reslen--;
624	break;
625      case 'P':
626	strncpy(result, c->physical->dl->bundle->cfg.auth.key, reslen);
627        len = strlen(result);
628	reslen -= len;
629	result += len;
630	break;
631      case 'T':
632        if (c->phone) {
633          strncpy(result, c->phone, reslen);
634          len = strlen(result);
635          reslen -= len;
636          result += len;
637        }
638	break;
639      case 'U':
640	strncpy(result, c->physical->dl->bundle->cfg.auth.name, reslen);
641        len = strlen(result);
642	reslen -= len;
643	result += len;
644	break;
645      default:
646	reslen--;
647	*result++ = *str;
648	break;
649      }
650      if (*str)
651	str++;
652      break;
653    case '^':
654      str++;
655      if (*str) {
656	*result++ = *str++ & 0x1f;
657	reslen--;
658      }
659      break;
660    default:
661      *result++ = *str++;
662      reslen--;
663      break;
664    }
665  }
666  if (--reslen > 0) {
667    if (cr)
668      *result++ = '\r';
669  }
670  if (--reslen > 0)
671    *result++ = '\0';
672  return (result);
673}
674
675static void
676ExecStr(struct physical *physical, char *command, char *out, int olen)
677{
678  pid_t pid;
679  int fids[2];
680  char *argv[MAXARGS], *vector[MAXARGS], *startout, *endout;
681  int stat, nb, argc;
682
683  log_Printf(LogCHAT, "Exec: %s\n", command);
684  argc = MakeArgs(command, vector, VECSIZE(vector));
685  command_Expand(argv, argc, (char const *const *)vector,
686                 physical->dl->bundle, 0, getpid());
687
688  if (pipe(fids) < 0) {
689    log_Printf(LogCHAT, "Unable to create pipe in ExecStr: %s\n",
690	      strerror(errno));
691    *out = '\0';
692    return;
693  }
694  if ((pid = fork()) == 0) {
695    close(fids[0]);
696    timer_TermService();
697    fids[1] = fcntl(fids[1], F_DUPFD, 4);
698    dup2(physical->fd, STDIN_FILENO);
699    dup2(STDIN_FILENO, STDOUT_FILENO);
700    dup2(fids[1], STDERR_FILENO);
701    close(3);
702    if (open(_PATH_TTY, O_RDWR) == 3)
703      fcntl(3, F_SETFD, 0);	/* Clear close-on-exec flag */
704    else
705      fcntl(3, F_SETFD, 1);	/* Set close-on-exec flag */
706    setuid(geteuid());
707    execvp(argv[0], argv);
708    fprintf(stderr, "execvp: %s: %s\n", argv[0], strerror(errno));
709    exit(127);
710  } else {
711    char *name = strdup(vector[0]);
712
713    close(fids[1]);
714    endout = out + olen - 1;
715    startout = out;
716    while (out < endout) {
717      nb = read(fids[0], out, 1);
718      if (nb <= 0)
719	break;
720      out++;
721    }
722    *out = '\0';
723    close(fids[0]);
724    close(fids[1]);
725    waitpid(pid, &stat, WNOHANG);
726    if (WIFSIGNALED(stat)) {
727      log_Printf(LogWARN, "%s: signal %d\n", name, WTERMSIG(stat));
728      free(name);
729      *out = '\0';
730      return;
731    } else if (WIFEXITED(stat)) {
732      switch (WEXITSTATUS(stat)) {
733        case 0:
734          free(name);
735          break;
736        case 127:
737          log_Printf(LogWARN, "%s: %s\n", name, startout);
738          free(name);
739          *out = '\0';
740          return;
741          break;
742        default:
743          log_Printf(LogWARN, "%s: exit %d\n", name, WEXITSTATUS(stat));
744          free(name);
745          *out = '\0';
746          return;
747          break;
748      }
749    } else {
750      log_Printf(LogWARN, "%s: Unexpected exit result\n", name);
751      free(name);
752      *out = '\0';
753      return;
754    }
755  }
756}
757