2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
29 #include <sys/param.h>
30 #include <netinet/in.h>
31 #include <netinet/in_systm.h>
32 #include <netinet/ip.h>
52 #include "throughput.h"
58 #include "descriptor.h"
64 #include "slcompress.h"
77 #define BUFLEFT(c) (sizeof (c)->buf - ((c)->bufend - (c)->buf))
79 static void ExecStr(struct physical *, char *, char *, int);
80 static char *ExpandString(struct chat *, const char *, char *, int, int);
83 chat_PauseTimer(void *v)
85 struct chat *c = (struct chat *)v;
86 timer_Stop(&c->pause);
91 chat_Pause(struct chat *c, u_long load)
93 timer_Stop(&c->pause);
94 c->pause.load += load;
95 c->pause.func = chat_PauseTimer;
96 c->pause.name = "chat pause";
98 timer_Start(&c->pause);
102 chat_TimeoutTimer(void *v)
104 struct chat *c = (struct chat *)v;
105 timer_Stop(&c->timeout);
110 chat_SetTimeout(struct chat *c)
112 timer_Stop(&c->timeout);
113 if (c->TimeoutSec > 0) {
114 c->timeout.load = SECTICKS * c->TimeoutSec;
115 c->timeout.func = chat_TimeoutTimer;
116 c->timeout.name = "chat timeout";
118 timer_Start(&c->timeout);
123 chat_NextChar(char *ptr, char ch)
128 else if (*ptr == '\\')
136 chat_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
138 struct chat *c = descriptor2chat(d);
139 int special, gotabort, gottimeout, needcr;
140 int TimedOut = c->TimedOut;
141 static char arg_term; /* An empty string */
143 if (c->pause.state == TIMER_RUNNING)
147 log_Printf(LogCHAT, "Expect timeout\n");
148 if (c->nargptr == NULL)
149 c->state = CHAT_FAILED;
151 /* c->state = CHAT_EXPECT; */
152 c->argptr = &arg_term;
157 if (c->state != CHAT_EXPECT && c->state != CHAT_SEND)
160 gottimeout = gotabort = 0;
162 if (c->arg < c->argc && (c->arg < 0 || *c->argptr == '\0')) {
163 /* Go get the next string */
164 if (c->arg < 0 || c->state == CHAT_SEND)
165 c->state = CHAT_EXPECT;
167 c->state = CHAT_SEND;
170 while (special && (c->nargptr || c->arg < c->argc - 1)) {
171 if (c->arg < 0 || (!TimedOut && c->state == CHAT_SEND))
174 if (c->nargptr != NULL) {
175 /* We're doing expect-send-expect.... */
176 c->argptr = c->nargptr;
177 /* Put the '-' back in case we ever want to rerun our script */
178 c->nargptr[-1] = '-';
179 c->nargptr = chat_NextChar(c->nargptr, '-');
180 if (c->nargptr != NULL)
181 *c->nargptr++ = '\0';
185 if ((c->argptr = c->argv[++c->arg]) == NULL) {
186 /* End of script - all ok */
187 c->state = CHAT_DONE;
191 if (c->state == CHAT_EXPECT) {
192 /* Look for expect-send-expect sequence */
193 c->nargptr = c->argptr;
195 while ((c->nargptr = chat_NextChar(c->nargptr, '-'))) {
201 log_Printf(LogWARN, "chat_UpdateSet: \"%s\": Uneven number of"
202 " '-' chars, all ignored\n", c->argptr);
204 c->nargptr = chat_NextChar(c->argptr, '-');
205 *c->nargptr++ = '\0';
211 * c->argptr now temporarily points into c->script (via c->argv)
212 * If it's an expect-send-expect sequence, we've just got the correct
213 * portion of that sequence.
216 needcr = c->state == CHAT_SEND && *c->argptr != '!';
218 /* We leave room for a potential HDLC header in the target string */
219 ExpandString(c, c->argptr, c->exp + 2, sizeof c->exp - 2, needcr);
222 * Now read our string. If it's not a special string, we unset
223 * ``special'' to break out of the loop.
226 if (c->abort.num < MAXABORTS) {
229 len = strlen(c->exp+2);
230 for (i = 0; i < c->abort.num; i++)
231 if (len > c->abort.string[i].len) {
234 for (last = c->abort.num; last > i; last--) {
235 c->abort.string[last].data = c->abort.string[last-1].data;
236 c->abort.string[last].len = c->abort.string[last-1].len;
240 c->abort.string[i].len = len;
241 c->abort.string[i].data = (char *)malloc(len+1);
242 memcpy(c->abort.string[i].data, c->exp+2, len+1);
245 log_Printf(LogERROR, "chat_UpdateSet: too many abort strings\n");
247 } else if (gottimeout) {
248 c->TimeoutSec = atoi(c->exp + 2);
249 if (c->TimeoutSec <= 0)
252 } else if (c->nargptr == NULL && !strcmp(c->exp+2, "ABORT"))
254 else if (c->nargptr == NULL && !strcmp(c->exp+2, "TIMEOUT"))
257 if (c->exp[2] == '!')
258 ExecStr(c->physical, c->exp + 3, c->exp + 2, sizeof c->exp - 2);
260 if (c->exp[2] == '\0') {
261 /* Empty string, reparse (this may be better as a `goto start') */
262 c->argptr = &arg_term;
263 return chat_UpdateSet(d, r, w, e, n);
272 log_Printf(LogWARN, "chat_UpdateSet: TIMEOUT: Argument expected\n");
274 log_Printf(LogWARN, "chat_UpdateSet: ABORT: Argument expected\n");
276 /* End of script - all ok */
277 c->state = CHAT_DONE;
281 /* set c->argptr to point in the right place */
282 c->argptr = c->exp + 2;
283 c->arglen = strlen(c->argptr);
285 if (c->state == CHAT_EXPECT) {
286 /* We must check to see if the string's already been found ! */
289 end = c->bufend - c->arglen + 1;
290 if (end < c->bufstart)
292 for (begin = c->bufstart; begin < end; begin++)
293 if (!strncmp(begin, c->argptr, c->arglen)) {
294 c->bufstart = begin + c->arglen;
295 c->argptr += c->arglen;
297 /* Continue - we've already read our expect string */
298 return chat_UpdateSet(d, r, w, e, n);
301 log_Printf(LogCHAT, "Expect(%d): %s\n", c->TimeoutSec, c->argptr);
307 * We now have c->argptr pointing at what we want to expect/send and
308 * c->state saying what we want to do... we now know what to put in
312 if (c->state == CHAT_EXPECT)
313 return physical_doUpdateSet(&c->physical->desc, r, NULL, e, n, 1);
315 return physical_doUpdateSet(&c->physical->desc, NULL, w, e, n, 1);
319 chat_IsSet(struct descriptor *d, const fd_set *fdset)
321 struct chat *c = descriptor2chat(d);
322 return c->argptr && physical_IsSet(&c->physical->desc, fdset);
326 chat_UpdateLog(struct chat *c, int in)
328 if (log_IsKept(LogCHAT) || log_IsKept(LogCONNECT)) {
330 * If a linefeed appears in the last `in' characters of `c's input
331 * buffer, output from there, all the way back to the last linefeed.
332 * This is called for every read of `in' bytes.
334 char *ptr, *end, *stop, ch;
337 level = log_IsKept(LogCHAT) ? LogCHAT : LogCONNECT;
339 end = ptr = c->bufend;
341 ptr = c->bufend - in;
342 for (end = c->bufend - 1; end >= ptr; end--)
348 for (ptr = c->bufend - (in == -1 ? 1 : in + 1); ptr >= c->bufstart; ptr--)
354 if ((stop = memchr(ptr, '\n', end - ptr)) == NULL)
358 if (level == LogCHAT || strstr(ptr, "CONNECT"))
359 log_Printf(level, "Received: %s\n", ptr);
368 chat_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
370 struct chat *c = descriptor2chat(d);
372 if (c->state == CHAT_EXPECT) {
374 char *abegin, *ebegin, *begin, *aend, *eend, *end;
378 * XXX - should this read only 1 byte to guarantee that we don't
379 * swallow any ppp talk from the peer ?
382 if (in > sizeof c->buf / 2)
383 in = sizeof c->buf / 2;
385 in = physical_Read(c->physical, c->bufend, in);
389 /* `begin' and `end' delimit where we're going to strncmp() from */
390 ebegin = c->bufend - c->arglen + 1;
392 if (ebegin < c->bufstart)
393 ebegin = c->bufstart;
396 abegin = c->bufend - c->abort.string[0].len + 1;
397 aend = c->bufend - c->abort.string[c->abort.num-1].len + in + 1;
398 if (abegin < c->bufstart)
399 abegin = c->bufstart;
404 begin = abegin < ebegin ? abegin : ebegin;
405 end = aend < eend ? eend : aend;
409 chat_UpdateLog(c, in);
411 if (c->bufend > c->buf + sizeof c->buf / 2) {
412 /* Shuffle our receive buffer back a bit */
415 for (chop = begin - c->buf; chop; chop--)
416 if (c->buf[chop] == '\n')
417 /* found some already-logged garbage to remove :-) */
421 chop = begin - c->buf;
428 while (from < c->bufend)
441 for (; begin < end; begin++)
442 if (begin >= ebegin && begin < eend &&
443 !strncmp(begin, c->argptr, c->arglen)) {
445 timer_Stop(&c->timeout);
446 if (memchr(begin + c->arglen - 1, '\n',
447 c->bufend - begin - c->arglen + 1) == NULL) {
448 /* force it into the log */
450 c->bufend = begin + c->arglen;
451 chat_UpdateLog(c, -1);
454 c->bufstart = begin + c->arglen;
455 c->argptr += c->arglen;
458 } else if (begin >= abegin && begin < aend) {
459 for (n = c->abort.num - 1; n >= 0; n--) {
460 if (begin + c->abort.string[n].len > c->bufend)
462 if (!strncmp(begin, c->abort.string[n].data,
463 c->abort.string[n].len)) {
464 if (memchr(begin + c->abort.string[n].len - 1, '\n',
465 c->bufend - begin - c->abort.string[n].len + 1) == NULL) {
466 /* force it into the log */
468 c->bufend = begin + c->abort.string[n].len;
469 chat_UpdateLog(c, -1);
472 c->bufstart = begin + c->abort.string[n].len;
473 c->state = CHAT_FAILED;
482 chat_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
484 struct chat *c = descriptor2chat(d);
487 if (c->state == CHAT_SEND) {
490 if (strstr(c->argv[c->arg], "\\P")) /* Don't log the password */
491 log_Printf(LogCHAT, "Send: %s\n", c->argv[c->arg]);
496 while (sz >= 0 && c->argptr[sz] == '\n')
498 log_Printf(LogCHAT, "Send: %.*s\n", sz + 1, c->argptr);
501 if (physical_IsSync(c->physical)) {
504 * This data should be stuffed down through the link layers
506 /* There's always room for the HDLC header */
509 memcpy(c->argptr, "\377\003", 2); /* Prepend HDLC header */
512 wrote = physical_Write(c->physical, c->argptr, c->arglen);
513 result = wrote ? 1 : 0;
516 log_Printf(LogERROR, "chat_Write: %s\n", strerror(errno));
517 if (physical_IsSync(c->physical)) {
521 } else if (wrote < 2 && physical_IsSync(c->physical)) {
522 /* Oops - didn't even write our HDLC header ! */
535 chat_Init(struct chat *c, struct physical *p)
537 c->desc.type = CHAT_DESCRIPTOR;
538 c->desc.UpdateSet = chat_UpdateSet;
539 c->desc.IsSet = chat_IsSet;
540 c->desc.Read = chat_Read;
541 c->desc.Write = chat_Write;
548 c->bufstart = c->bufend = c->buf;
550 memset(&c->pause, '\0', sizeof c->pause);
551 memset(&c->timeout, '\0', sizeof c->timeout);
555 chat_Setup(struct chat *c, const char *data, const char *phone)
557 c->state = CHAT_EXPECT;
563 strncpy(c->script, data, sizeof c->script - 1);
564 c->script[sizeof c->script - 1] = '\0';
565 c->argc = MakeArgs(c->script, c->argv, VECSIZE(c->argv), PARSE_NOHASH);
577 timer_Stop(&c->pause);
578 timer_Stop(&c->timeout);
584 chat_Finish(struct chat *c)
586 timer_Stop(&c->pause);
587 timer_Stop(&c->timeout);
589 free(c->abort.string[--c->abort.num].data);
594 chat_Destroy(struct chat *c)
601 * \d Sleep a little (delay 2 seconds
602 * \n Line feed character
603 * \P Auth Key password
605 * \r Carrige return character
607 * \T Telephone number(s) (defined via `set phone')
612 ExpandString(struct chat *c, const char *str, char *result, int reslen, int cr)
616 result[--reslen] = '\0';
617 while (*str && reslen > 0) {
625 case 'd': /* Delay 2 seconds */
626 chat_Pause(c, 2 * SECTICKS);
629 chat_Pause(c, SECTICKS / 4);
630 break; /* Delay 0.25 seconds */
648 strncpy(result, c->physical->dl->bundle->cfg.auth.key, reslen);
649 len = strlen(result);
655 strncpy(result, c->phone, reslen);
656 len = strlen(result);
662 strncpy(result, c->physical->dl->bundle->cfg.auth.name, reslen);
663 len = strlen(result);
678 *result++ = *str++ & 0x1f;
698 ExecStr(struct physical *physical, char *command, char *out, int olen)
702 char *argv[MAXARGS], *vector[MAXARGS], *startout, *endout;
703 int stat, nb, argc, i;
705 log_Printf(LogCHAT, "Exec: %s\n", command);
706 if ((argc = MakeArgs(command, vector, VECSIZE(vector),
707 PARSE_REDUCE|PARSE_NOHASH)) <= 0) {
709 log_Printf(LogWARN, "Syntax error in exec command\n");
713 command_Expand(argv, argc, (char const *const *)vector,
714 physical->dl->bundle, 0, getpid());
716 if (pipe(fids) < 0) {
717 log_Printf(LogCHAT, "Unable to create pipe in ExecStr: %s\n",
722 if ((pid = fork()) == 0) {
725 if (fids[1] == STDIN_FILENO)
726 fids[1] = dup(fids[1]);
727 dup2(physical->fd, STDIN_FILENO);
728 dup2(fids[1], STDERR_FILENO);
729 dup2(STDIN_FILENO, STDOUT_FILENO);
731 if (open(_PATH_TTY, O_RDWR) != 3)
732 open(_PATH_DEVNULL, O_RDWR); /* Leave it closed if it fails... */
733 for (i = getdtablesize(); i > 3; i--)
734 fcntl(i, F_SETFD, 1);
735 setuid(ID0realuid());
736 execvp(argv[0], argv);
737 fprintf(stderr, "execvp: %s: %s\n", argv[0], strerror(errno));
740 char *name = strdup(vector[0]);
743 endout = out + olen - 1;
745 while (out < endout) {
746 nb = read(fids[0], out, 1);
754 waitpid(pid, &stat, WNOHANG);
755 if (WIFSIGNALED(stat)) {
756 log_Printf(LogWARN, "%s: signal %d\n", name, WTERMSIG(stat));
760 } else if (WIFEXITED(stat)) {
761 switch (WEXITSTATUS(stat)) {
766 log_Printf(LogWARN, "%s: %s\n", name, startout);
772 log_Printf(LogWARN, "%s: exit %d\n", name, WEXITSTATUS(stat));
779 log_Printf(LogWARN, "%s: Unexpected exit result\n", name);