chat.c revision 43313
1184610Salfred/*-
2184610Salfred * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3184610Salfred * All rights reserved.
4184610Salfred *
5184610Salfred * Redistribution and use in source and binary forms, with or without
6184610Salfred * modification, are permitted provided that the following conditions
7184610Salfred * are met:
8184610Salfred * 1. Redistributions of source code must retain the above copyright
9184610Salfred *    notice, this list of conditions and the following disclaimer.
10184610Salfred * 2. Redistributions in binary form must reproduce the above copyright
11184610Salfred *    notice, this list of conditions and the following disclaimer in the
12184610Salfred *    documentation and/or other materials provided with the distribution.
13184610Salfred *
14184610Salfred * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15184610Salfred * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16184610Salfred * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17184610Salfred * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18184610Salfred * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19184610Salfred * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20184610Salfred * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21184610Salfred * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22184610Salfred * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23184610Salfred * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24184610Salfred * SUCH DAMAGE.
25184610Salfred *
26184610Salfred *	$Id: chat.c,v 1.52 1998/10/27 22:53:25 brian Exp $
27188942Sthompsa */
28188942Sthompsa
29188942Sthompsa#include <sys/param.h>
30184610Salfred#include <netinet/in.h>
31188942Sthompsa#include <netinet/in_systm.h>
32188942Sthompsa#include <netinet/ip.h>
33188942Sthompsa#include <sys/un.h>
34188942Sthompsa
35188942Sthompsa#include <errno.h>
36188942Sthompsa#include <fcntl.h>
37184610Salfred#include <paths.h>
38188942Sthompsa#include <stdio.h>
39188942Sthompsa#include <stdlib.h>
40184610Salfred#include <string.h>
41184610Salfred#include <sys/wait.h>
42190180Sthompsa#include <termios.h>
43184610Salfred#include <unistd.h>
44184610Salfred
45184610Salfred#include "mbuf.h"
46184610Salfred#include "log.h"
47184610Salfred#include "defs.h"
48184610Salfred#include "timer.h"
49184610Salfred#include "lqr.h"
50190180Sthompsa#include "hdlc.h"
51184610Salfred#include "throughput.h"
52184610Salfred#include "fsm.h"
53184610Salfred#include "lcp.h"
54184610Salfred#include "ccp.h"
55184610Salfred#include "link.h"
56184610Salfred#include "async.h"
57184610Salfred#include "descriptor.h"
58184610Salfred#include "physical.h"
59184610Salfred#include "chat.h"
60184610Salfred#include "mp.h"
61184610Salfred#include "auth.h"
62184610Salfred#include "chap.h"
63184610Salfred#include "slcompress.h"
64184610Salfred#include "iplist.h"
65184610Salfred#include "ipcp.h"
66184610Salfred#include "filter.h"
67184610Salfred#include "cbcp.h"
68184610Salfred#include "datalink.h"
69184610Salfred#ifndef NORADIUS
70190180Sthompsa#include "radius.h"
71184610Salfred#endif
72184610Salfred#include "bundle.h"
73184610Salfred
74184610Salfred#define BUFLEFT(c) (sizeof (c)->buf - ((c)->bufend - (c)->buf))
75184610Salfred#define	issep(c)	((c) == '\t' || (c) == ' ')
76184610Salfred
77184610Salfredstatic void ExecStr(struct physical *, char *, char *, int);
78184610Salfredstatic char *ExpandString(struct chat *, const char *, char *, int, int);
79184610Salfred
80184610Salfredstatic void
81190180Sthompsachat_PauseTimer(void *v)
82184610Salfred{
83184610Salfred  struct chat *c = (struct chat *)v;
84184610Salfred  timer_Stop(&c->pause);
85184610Salfred  c->pause.load = 0;
86184610Salfred}
87184610Salfred
88184610Salfredstatic void
89184610Salfredchat_Pause(struct chat *c, u_long load)
90184610Salfred{
91184610Salfred  timer_Stop(&c->pause);
92184610Salfred  c->pause.load += load;
93184610Salfred  c->pause.func = chat_PauseTimer;
94185087Salfred  c->pause.name = "chat pause";
95184610Salfred  c->pause.arg = c;
96184610Salfred  timer_Start(&c->pause);
97184610Salfred}
98184610Salfred
99184610Salfredstatic void
100184610Salfredchat_TimeoutTimer(void *v)
101184610Salfred{
102184610Salfred  struct chat *c = (struct chat *)v;
103184610Salfred  timer_Stop(&c->timeout);
104184610Salfred  c->TimedOut = 1;
105184610Salfred}
106184610Salfred
107184610Salfredstatic void
108184610Salfredchat_SetTimeout(struct chat *c)
109184610Salfred{
110184610Salfred  timer_Stop(&c->timeout);
111184610Salfred  if (c->TimeoutSec > 0) {
112184610Salfred    c->timeout.load = SECTICKS * c->TimeoutSec;
113184610Salfred    c->timeout.func = chat_TimeoutTimer;
114184610Salfred    c->timeout.name = "chat timeout";
115184610Salfred    c->timeout.arg = c;
116184610Salfred    timer_Start(&c->timeout);
117184610Salfred  }
118184610Salfred}
119184610Salfred
120184610Salfredstatic char *
121184610Salfredchat_NextChar(char *ptr, char ch)
122184610Salfred{
123184610Salfred  for (; *ptr; ptr++)
124190180Sthompsa    if (*ptr == ch)
125184610Salfred      return ptr;
126184610Salfred    else if (*ptr == '\\')
127184610Salfred      if (*++ptr == '\0')
128184610Salfred        return NULL;
129184610Salfred
130188411Sthompsa  return NULL;
131188411Sthompsa}
132188411Sthompsa
133184610Salfredstatic int
134184610Salfredchat_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
135188411Sthompsa{
136184610Salfred  struct chat *c = descriptor2chat(d);
137188411Sthompsa  int special, gotabort, gottimeout, needcr;
138188411Sthompsa  int TimedOut = c->TimedOut;
139188411Sthompsa  static char arg_term;		/* An empty string */
140184610Salfred
141188411Sthompsa  if (c->pause.state == TIMER_RUNNING)
142188411Sthompsa    return 0;
143188411Sthompsa
144188411Sthompsa  if (TimedOut) {
145188411Sthompsa    log_Printf(LogCHAT, "Expect timeout\n");
146184610Salfred    if (c->nargptr == NULL)
147184610Salfred      c->state = CHAT_FAILED;
148184610Salfred    else {
149184610Salfred      /* c->state = CHAT_EXPECT; */
150184610Salfred      c->argptr = &arg_term;
151184610Salfred    }
152184610Salfred    c->TimedOut = 0;
153188411Sthompsa  }
154184610Salfred
155188411Sthompsa  if (c->state != CHAT_EXPECT && c->state != CHAT_SEND)
156184610Salfred    return 0;
157184610Salfred
158184610Salfred  gottimeout = gotabort = 0;
159188411Sthompsa
160188411Sthompsa  if (c->arg < c->argc && (c->arg < 0 || *c->argptr == '\0')) {
161184610Salfred    /* Go get the next string */
162184610Salfred    if (c->arg < 0 || c->state == CHAT_SEND)
163184610Salfred      c->state = CHAT_EXPECT;
164184610Salfred    else
165184610Salfred      c->state = CHAT_SEND;
166184610Salfred
167184610Salfred    special = 1;
168184610Salfred    while (special && (c->nargptr || c->arg < c->argc - 1)) {
169184610Salfred      if (c->arg < 0 || (!TimedOut && c->state == CHAT_SEND))
170190180Sthompsa        c->nargptr = NULL;
171184610Salfred
172184610Salfred      if (c->nargptr != NULL) {
173184610Salfred        /* We're doing expect-send-expect.... */
174184610Salfred        c->argptr = c->nargptr;
175184610Salfred        /* Put the '-' back in case we ever want to rerun our script */
176184610Salfred        c->nargptr[-1] = '-';
177184610Salfred        c->nargptr = chat_NextChar(c->nargptr, '-');
178190180Sthompsa        if (c->nargptr != NULL)
179184610Salfred          *c->nargptr++ = '\0';
180184610Salfred      } else {
181184610Salfred        int minus;
182184610Salfred
183184610Salfred        c->argptr = c->argv[++c->arg];
184184610Salfred
185184610Salfred        if (c->state == CHAT_EXPECT) {
186190180Sthompsa          /* Look for expect-send-expect sequence */
187184610Salfred          c->nargptr = c->argptr;
188184610Salfred          minus = 0;
189184610Salfred          while ((c->nargptr = chat_NextChar(c->nargptr, '-'))) {
190184610Salfred            c->nargptr++;
191184610Salfred            minus++;
192184610Salfred          }
193184610Salfred
194184610Salfred          if (minus % 2)
195184610Salfred            log_Printf(LogWARN, "chat_UpdateSet: \"%s\": Uneven number of"
196184610Salfred                      " '-' chars, all ignored\n", c->argptr);
197184610Salfred          else if (minus) {
198184610Salfred            c->nargptr = chat_NextChar(c->argptr, '-');
199184610Salfred            *c->nargptr++ = '\0';
200184610Salfred          }
201184610Salfred        }
202184610Salfred      }
203190180Sthompsa
204184610Salfred      /*
205184610Salfred       * c->argptr now temporarily points into c->script (via c->argv)
206184610Salfred       * If it's an expect-send-expect sequence, we've just got the correct
207184610Salfred       * portion of that sequence.
208184610Salfred       */
209184610Salfred
210184610Salfred      needcr = c->state == CHAT_SEND && *c->argptr != '!';
211184610Salfred
212184610Salfred      /* We leave room for a potential HDLC header in the target string */
213184610Salfred      ExpandString(c, c->argptr, c->exp + 2, sizeof c->exp - 2, needcr);
214184610Salfred
215184610Salfred      if (gotabort) {
216184610Salfred        if (c->abort.num < MAXABORTS) {
217184610Salfred          int len, i;
218184610Salfred
219184610Salfred          len = strlen(c->exp+2);
220184610Salfred          for (i = 0; i < c->abort.num; i++)
221184610Salfred            if (len > c->abort.string[i].len) {
222184610Salfred              int last;
223184610Salfred
224184610Salfred              for (last = c->abort.num; last > i; last--) {
225184610Salfred                c->abort.string[last].data = c->abort.string[last-1].data;
226184610Salfred                c->abort.string[last].len = c->abort.string[last-1].len;
227184610Salfred              }
228184610Salfred              break;
229184610Salfred            }
230184610Salfred          c->abort.string[i].len = len;
231184610Salfred          c->abort.string[i].data = (char *)malloc(len+1);
232184610Salfred          memcpy(c->abort.string[i].data, c->exp+2, len+1);
233184610Salfred          c->abort.num++;
234184610Salfred        } else
235184610Salfred          log_Printf(LogERROR, "chat_UpdateSet: too many abort strings\n");
236184610Salfred        gotabort = 0;
237184610Salfred      } else if (gottimeout) {
238184610Salfred        c->TimeoutSec = atoi(c->exp + 2);
239184610Salfred        if (c->TimeoutSec <= 0)
240184610Salfred          c->TimeoutSec = 30;
241184610Salfred        gottimeout = 0;
242184610Salfred      } else if (c->nargptr == NULL && !strcmp(c->exp+2, "ABORT"))
243184610Salfred        gotabort = 1;
244184610Salfred      else if (c->nargptr == NULL && !strcmp(c->exp+2, "TIMEOUT"))
245184610Salfred        gottimeout = 1;
246184610Salfred      else {
247184610Salfred        if (c->exp[2] == '!')
248184610Salfred          ExecStr(c->physical, c->exp + 3, c->exp + 2, sizeof c->exp - 2);
249184610Salfred
250184610Salfred        if (c->exp[2] == '\0') {
251184610Salfred          /* Empty string, reparse (this may be better as a `goto start') */
252184610Salfred          c->argptr = &arg_term;
253184610Salfred          return chat_UpdateSet(d, r, w, e, n);
254184610Salfred        }
255184610Salfred
256184610Salfred        special = 0;
257190180Sthompsa      }
258184610Salfred    }
259184610Salfred
260184610Salfred    if (special) {
261184610Salfred      if (gottimeout)
262184610Salfred        log_Printf(LogWARN, "chat_UpdateSet: TIMEOUT: Argument expected\n");
263184610Salfred      else if (gotabort)
264184610Salfred        log_Printf(LogWARN, "chat_UpdateSet: ABORT: Argument expected\n");
265184610Salfred
266184610Salfred      /* End of script - all ok */
267184610Salfred      c->state = CHAT_DONE;
268184610Salfred      return 0;
269184610Salfred    }
270184610Salfred
271184610Salfred    /* set c->argptr to point in the right place */
272184610Salfred    c->argptr = c->exp + 2;
273184610Salfred    c->arglen = strlen(c->argptr);
274184610Salfred
275184610Salfred    if (c->state == CHAT_EXPECT) {
276184610Salfred      /* We must check to see if the string's already been found ! */
277184610Salfred      char *begin, *end;
278184610Salfred
279184610Salfred      end = c->bufend - c->arglen + 1;
280184610Salfred      if (end < c->bufstart)
281184610Salfred        end = c->bufstart;
282184610Salfred      for (begin = c->bufstart; begin < end; begin++)
283184610Salfred        if (!strncmp(begin, c->argptr, c->arglen)) {
284184610Salfred          c->bufstart = begin + c->arglen;
285184610Salfred          c->argptr += c->arglen;
286184610Salfred          c->arglen = 0;
287184610Salfred          /* Continue - we've already read our expect string */
288184610Salfred          return chat_UpdateSet(d, r, w, e, n);
289184610Salfred        }
290184610Salfred
291184610Salfred      log_Printf(LogCHAT, "Expect(%d): %s\n", c->TimeoutSec, c->argptr);
292184610Salfred      chat_SetTimeout(c);
293184610Salfred    }
294184610Salfred  }
295184610Salfred
296184610Salfred  /*
297184610Salfred   * We now have c->argptr pointing at what we want to expect/send and
298184610Salfred   * c->state saying what we want to do... we now know what to put in
299184610Salfred   * the fd_set :-)
300184610Salfred   */
301184610Salfred
302184610Salfred  if (c->state == CHAT_EXPECT)
303184610Salfred    return physical_UpdateSet(&c->physical->desc, r, NULL, e, n, 1);
304184610Salfred  else
305184610Salfred    return physical_UpdateSet(&c->physical->desc, NULL, w, e, n, 1);
306184610Salfred}
307184610Salfred
308184610Salfredstatic int
309184610Salfredchat_IsSet(struct descriptor *d, const fd_set *fdset)
310184610Salfred{
311184610Salfred  struct chat *c = descriptor2chat(d);
312184610Salfred  return physical_IsSet(&c->physical->desc, fdset);
313184610Salfred}
314184610Salfred
315184610Salfredstatic void
316184610Salfredchat_UpdateLog(struct chat *c, int in)
317184610Salfred{
318184610Salfred  if (log_IsKept(LogCHAT) || log_IsKept(LogCONNECT)) {
319184610Salfred    /*
320184610Salfred     * If a linefeed appears in the last `in' characters of `c's input
321184610Salfred     * buffer, output from there, all the way back to the last linefeed.
322184610Salfred     * This is called for every read of `in' bytes.
323184610Salfred     */
324184610Salfred    char *ptr, *end, *stop, ch;
325184610Salfred    int level;
326184610Salfred
327184610Salfred    level = log_IsKept(LogCHAT) ? LogCHAT : LogCONNECT;
328184610Salfred    if (in == -1)
329184610Salfred      end = ptr = c->bufend;
330184610Salfred    else {
331184610Salfred      ptr = c->bufend - in;
332184610Salfred      for (end = c->bufend - 1; end >= ptr; end--)
333184610Salfred        if (*end == '\n')
334184610Salfred          break;
335184610Salfred    }
336184610Salfred
337184610Salfred    if (end >= ptr) {
338184610Salfred      for (ptr = c->bufend - (in == -1 ? 1 : in + 1); ptr >= c->bufstart; ptr--)
339184610Salfred        if (*ptr == '\n')
340184610Salfred          break;
341184610Salfred      ptr++;
342184610Salfred      stop = NULL;
343184610Salfred      while (stop < end) {
344184610Salfred        if ((stop = memchr(ptr, '\n', end - ptr)) == NULL)
345184610Salfred          stop = end;
346184610Salfred        ch = *stop;
347184610Salfred        *stop = '\0';
348184610Salfred        if (level == LogCHAT || strstr(ptr, "CONNECT"))
349184610Salfred          log_Printf(level, "Received: %s\n", ptr);
350184610Salfred        *stop = ch;
351184610Salfred        ptr = stop + 1;
352184610Salfred      }
353184610Salfred    }
354  }
355}
356
357static void
358chat_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
359{
360  struct chat *c = descriptor2chat(d);
361
362  if (c->state == CHAT_EXPECT) {
363    ssize_t in;
364    char *abegin, *ebegin, *begin, *aend, *eend, *end;
365    int n;
366
367    /*
368     * XXX - should this read only 1 byte to guarantee that we don't
369     * swallow any ppp talk from the peer ?
370     */
371    in = BUFLEFT(c);
372    if (in > sizeof c->buf / 2)
373      in = sizeof c->buf / 2;
374
375    in = physical_Read(c->physical, c->bufend, in);
376    if (in <= 0)
377      return;
378
379    /* `begin' and `end' delimit where we're going to strncmp() from */
380    ebegin = c->bufend - c->arglen + 1;
381    eend = ebegin + in;
382    if (ebegin < c->bufstart)
383      ebegin = c->bufstart;
384
385    if (c->abort.num) {
386      abegin = c->bufend - c->abort.string[0].len + 1;
387      aend = c->bufend - c->abort.string[c->abort.num-1].len + in + 1;
388      if (abegin < c->bufstart)
389        abegin = c->bufstart;
390    } else {
391      abegin = ebegin;
392      aend = eend;
393    }
394    begin = abegin < ebegin ? abegin : ebegin;
395    end = aend < eend ? eend : aend;
396
397    c->bufend += in;
398
399    chat_UpdateLog(c, in);
400
401    if (c->bufend > c->buf + sizeof c->buf / 2) {
402      /* Shuffle our receive buffer back a bit */
403      int chop;
404
405      for (chop = begin - c->buf; chop; chop--)
406        if (c->buf[chop] == '\n')
407          /* found some already-logged garbage to remove :-) */
408          break;
409
410      if (!chop)
411        chop = begin - c->buf;
412
413      if (chop) {
414        char *from, *to;
415
416        to = c->buf;
417        from = to + chop;
418        while (from < c->bufend)
419          *to++ = *from++;
420        c->bufstart -= chop;
421        c->bufend -= chop;
422        begin -= chop;
423        end -= chop;
424        abegin -= chop;
425        aend -= chop;
426        ebegin -= chop;
427        eend -= chop;
428      }
429    }
430
431    for (; begin < end; begin++)
432      if (begin >= ebegin && begin < eend &&
433          !strncmp(begin, c->argptr, c->arglen)) {
434        /* Got it ! */
435        timer_Stop(&c->timeout);
436        if (memchr(begin + c->arglen - 1, '\n',
437            c->bufend - begin - c->arglen + 1) == NULL) {
438          /* force it into the log */
439          end = c->bufend;
440          c->bufend = begin + c->arglen;
441          chat_UpdateLog(c, -1);
442          c->bufend = end;
443        }
444        c->bufstart = begin + c->arglen;
445        c->argptr += c->arglen;
446        c->arglen = 0;
447        break;
448      } else if (begin >= abegin && begin < aend) {
449        for (n = c->abort.num - 1; n >= 0; n--) {
450          if (begin + c->abort.string[n].len > c->bufend)
451            break;
452          if (!strncmp(begin, c->abort.string[n].data,
453                       c->abort.string[n].len)) {
454            if (memchr(begin + c->abort.string[n].len - 1, '\n',
455                c->bufend - begin - c->abort.string[n].len + 1) == NULL) {
456              /* force it into the log */
457              end = c->bufend;
458              c->bufend = begin + c->abort.string[n].len;
459              chat_UpdateLog(c, -1);
460              c->bufend = end;
461            }
462            c->bufstart = begin + c->abort.string[n].len;
463            c->state = CHAT_FAILED;
464            return;
465          }
466        }
467      }
468  }
469}
470
471static int
472chat_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
473{
474  struct chat *c = descriptor2chat(d);
475  int result = 0;
476
477  if (c->state == CHAT_SEND) {
478    int wrote;
479
480    if (strstr(c->argv[c->arg], "\\P"))            /* Don't log the password */
481      log_Printf(LogCHAT, "Send: %s\n", c->argv[c->arg]);
482    else {
483      int sz;
484
485      sz = c->arglen - 1;
486      while (sz >= 0 && c->argptr[sz] == '\n')
487        sz--;
488      log_Printf(LogCHAT, "Send: %.*s\n", sz + 1, c->argptr);
489    }
490
491    if (physical_IsSync(c->physical)) {
492      /* There's always room for the HDLC header */
493      c->argptr -= 2;
494      c->arglen += 2;
495      memcpy(c->argptr, "\377\003", 2);	/* Prepend HDLC header */
496    }
497
498    wrote = physical_Write(c->physical, c->argptr, c->arglen);
499    result = wrote ? 1 : 0;
500    if (wrote == -1) {
501      if (errno != EINTR)
502        log_Printf(LogERROR, "chat_Write: %s\n", strerror(errno));
503      if (physical_IsSync(c->physical)) {
504        c->argptr += 2;
505        c->arglen -= 2;
506      }
507    } else if (wrote < 2 && physical_IsSync(c->physical)) {
508      /* Oops - didn't even write our HDLC header ! */
509      c->argptr += 2;
510      c->arglen -= 2;
511    } else {
512      c->argptr += wrote;
513      c->arglen -= wrote;
514    }
515  }
516
517  return result;
518}
519
520void
521chat_Init(struct chat *c, struct physical *p, const char *data, int emptybuf,
522          const char *phone)
523{
524  c->desc.type = CHAT_DESCRIPTOR;
525  c->desc.UpdateSet = chat_UpdateSet;
526  c->desc.IsSet = chat_IsSet;
527  c->desc.Read = chat_Read;
528  c->desc.Write = chat_Write;
529  c->physical = p;
530
531  c->state = CHAT_EXPECT;
532
533  if (data == NULL) {
534    *c->script = '\0';
535    c->argc = 0;
536  } else {
537    strncpy(c->script, data, sizeof c->script - 1);
538    c->script[sizeof c->script - 1] = '\0';
539    c->argc =  MakeArgs(c->script, c->argv, VECSIZE(c->argv));
540  }
541
542  c->arg = -1;
543  c->argptr = NULL;
544  c->nargptr = NULL;
545
546  if (emptybuf)
547    c->bufstart = c->bufend = c->buf;
548
549  c->TimeoutSec = 30;
550  c->TimedOut = 0;
551  c->phone = phone;
552  c->abort.num = 0;
553
554  memset(&c->pause, '\0', sizeof c->pause);
555  memset(&c->timeout, '\0', sizeof c->timeout);
556}
557
558void
559chat_Destroy(struct chat *c)
560{
561  timer_Stop(&c->pause);
562  timer_Stop(&c->timeout);
563  while (c->abort.num)
564    free(c->abort.string[--c->abort.num].data);
565  c->abort.num = 0;
566}
567
568static char *
569findblank(char *p, int instring)
570{
571  if (instring) {
572    while (*p) {
573      if (*p == '\\') {
574	strcpy(p, p + 1);
575	if (!*p)
576	  break;
577      } else if (*p == '"')
578	return (p);
579      p++;
580    }
581  } else {
582    while (*p) {
583      if (issep(*p))
584	return (p);
585      p++;
586    }
587  }
588  return p;
589}
590
591int
592MakeArgs(char *script, char **pvect, int maxargs)
593{
594  int nargs, nb;
595  int instring;
596
597  nargs = 0;
598  while (*script) {
599    nb = strspn(script, " \t");
600    script += nb;
601    if (*script) {
602      if (*script == '"') {
603	instring = 1;
604	script++;
605	if (*script == '\0')
606	  break;		/* Shouldn't return here. Need to null
607				 * terminate below */
608      } else
609	instring = 0;
610      if (nargs >= maxargs - 1)
611	break;
612      *pvect++ = script;
613      nargs++;
614      script = findblank(script, instring);
615      if (*script)
616	*script++ = '\0';
617    }
618  }
619  *pvect = NULL;
620  return nargs;
621}
622
623/*
624 *  \c	don't add a cr
625 *  \d  Sleep a little (delay 2 seconds
626 *  \n  Line feed character
627 *  \P  Auth Key password
628 *  \p  pause 0.25 sec
629 *  \r	Carrige return character
630 *  \s  Space character
631 *  \T  Telephone number(s) (defined via `set phone')
632 *  \t  Tab character
633 *  \U  Auth User
634 */
635static char *
636ExpandString(struct chat *c, const char *str, char *result, int reslen,
637                  int sendmode)
638{
639  int addcr = 0;
640
641  result[--reslen] = '\0';
642  if (sendmode)
643    addcr = 1;
644  while (*str && reslen > 0) {
645    switch (*str) {
646    case '\\':
647      str++;
648      switch (*str) {
649      case 'c':
650	if (sendmode)
651	  addcr = 0;
652	break;
653      case 'd':		/* Delay 2 seconds */
654        chat_Pause(c, 2 * SECTICKS);
655	break;
656      case 'p':
657        chat_Pause(c, SECTICKS / 4);
658	break;			/* Pause 0.25 sec */
659      case 'n':
660	*result++ = '\n';
661	reslen--;
662	break;
663      case 'r':
664	*result++ = '\r';
665	reslen--;
666	break;
667      case 's':
668	*result++ = ' ';
669	reslen--;
670	break;
671      case 't':
672	*result++ = '\t';
673	reslen--;
674	break;
675      case 'P':
676	strncpy(result, c->physical->dl->bundle->cfg.auth.key, reslen);
677	reslen -= strlen(result);
678	result += strlen(result);
679	break;
680      case 'T':
681        if (c->phone) {
682          strncpy(result, c->phone, reslen);
683          reslen -= strlen(result);
684          result += strlen(result);
685        }
686	break;
687      case 'U':
688	strncpy(result, c->physical->dl->bundle->cfg.auth.name, reslen);
689	reslen -= strlen(result);
690	result += strlen(result);
691	break;
692      default:
693	reslen--;
694	*result++ = *str;
695	break;
696      }
697      if (*str)
698	str++;
699      break;
700    case '^':
701      str++;
702      if (*str) {
703	*result++ = *str++ & 0x1f;
704	reslen--;
705      }
706      break;
707    default:
708      *result++ = *str++;
709      reslen--;
710      break;
711    }
712  }
713  if (--reslen > 0) {
714    if (addcr)
715      *result++ = '\r';
716  }
717  if (--reslen > 0)
718    *result++ = '\0';
719  return (result);
720}
721
722static void
723ExecStr(struct physical *physical, char *command, char *out, int olen)
724{
725  pid_t pid;
726  int fids[2];
727  char *vector[MAXARGS], *startout, *endout;
728  int stat, nb;
729
730  log_Printf(LogCHAT, "Exec: %s\n", command);
731  MakeArgs(command, vector, VECSIZE(vector));
732
733  if (pipe(fids) < 0) {
734    log_Printf(LogCHAT, "Unable to create pipe in ExecStr: %s\n",
735	      strerror(errno));
736    *out = '\0';
737    return;
738  }
739  if ((pid = fork()) == 0) {
740    close(fids[0]);
741    timer_TermService();
742    fids[1] = fcntl(fids[1], F_DUPFD, 4);
743    dup2(physical_GetFD(physical), STDIN_FILENO);
744    dup2(STDIN_FILENO, STDOUT_FILENO);
745    dup2(fids[1], STDERR_FILENO);
746    close(3);
747    if (open(_PATH_TTY, O_RDWR) == 3)
748      fcntl(3, F_SETFD, 0);	/* Clear close-on-exec flag */
749    else
750      fcntl(3, F_SETFD, 1);	/* Set close-on-exec flag */
751    setuid(geteuid());
752    execvp(vector[0], vector);
753    fprintf(stderr, "execvp failed: %s: %s\n", vector[0], strerror(errno));
754    exit(127);
755  } else {
756    char *name = strdup(vector[0]);
757
758    close(fids[1]);
759    endout = out + olen - 1;
760    startout = out;
761    while (out < endout) {
762      nb = read(fids[0], out, 1);
763      if (nb <= 0)
764	break;
765      out++;
766    }
767    *out = '\0';
768    close(fids[0]);
769    close(fids[1]);
770    waitpid(pid, &stat, WNOHANG);
771    if (WIFSIGNALED(stat)) {
772      log_Printf(LogWARN, "%s: signal %d\n", name, WTERMSIG(stat));
773      free(name);
774      *out = '\0';
775      return;
776    } else if (WIFEXITED(stat)) {
777      switch (WEXITSTATUS(stat)) {
778        case 0:
779          free(name);
780          break;
781        case 127:
782          log_Printf(LogWARN, "%s: %s\n", name, startout);
783          free(name);
784          *out = '\0';
785          return;
786          break;
787        default:
788          log_Printf(LogWARN, "%s: exit %d\n", name, WEXITSTATUS(stat));
789          free(name);
790          *out = '\0';
791          return;
792          break;
793      }
794    } else {
795      log_Printf(LogWARN, "%s: Unexpected exit result\n", name);
796      free(name);
797      *out = '\0';
798      return;
799    }
800  }
801}
802