2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/param.h>
32 #include <netinet/in.h>
33 #include <netinet/in_systm.h>
34 #include <netinet/ip.h>
35 #include <sys/socket.h>
55 #include "throughput.h"
61 #include "descriptor.h"
67 #include "slcompress.h"
83 #define BUFLEFT(c) (sizeof (c)->buf - ((c)->bufend - (c)->buf))
85 static void ExecStr(struct physical *, char *, char *, int);
86 static char *ExpandString(struct chat *, const char *, char *, int, int);
89 chat_PauseTimer(void *v)
91 struct chat *c = (struct chat *)v;
92 timer_Stop(&c->pause);
97 chat_Pause(struct chat *c, u_long load)
99 timer_Stop(&c->pause);
100 c->pause.load += load;
101 c->pause.func = chat_PauseTimer;
102 c->pause.name = "chat pause";
104 timer_Start(&c->pause);
108 chat_TimeoutTimer(void *v)
110 struct chat *c = (struct chat *)v;
111 timer_Stop(&c->timeout);
116 chat_SetTimeout(struct chat *c)
118 timer_Stop(&c->timeout);
119 if (c->TimeoutSec > 0) {
120 c->timeout.load = SECTICKS * c->TimeoutSec;
121 c->timeout.func = chat_TimeoutTimer;
122 c->timeout.name = "chat timeout";
124 timer_Start(&c->timeout);
129 chat_NextChar(char *ptr, char ch)
134 else if (*ptr == '\\')
142 chat_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
144 struct chat *c = descriptor2chat(d);
145 int special, gotabort, gottimeout, needcr;
146 int TimedOut = c->TimedOut;
147 static char arg_term; /* An empty string */
149 if (c->pause.state == TIMER_RUNNING)
153 log_Printf(LogCHAT, "Expect timeout\n");
154 if (c->nargptr == NULL)
155 c->state = CHAT_FAILED;
157 /* c->state = CHAT_EXPECT; */
158 c->argptr = &arg_term;
160 We have to clear the input buffer, because it contains output
161 from the previous (timed out) command.
163 c->bufstart = c->bufend;
168 if (c->state != CHAT_EXPECT && c->state != CHAT_SEND)
171 gottimeout = gotabort = 0;
173 if (c->arg < c->argc && (c->arg < 0 || *c->argptr == '\0')) {
174 /* Go get the next string */
175 if (c->arg < 0 || c->state == CHAT_SEND)
176 c->state = CHAT_EXPECT;
178 c->state = CHAT_SEND;
181 while (special && (c->nargptr || c->arg < c->argc - 1)) {
182 if (c->arg < 0 || (!TimedOut && c->state == CHAT_SEND))
185 if (c->nargptr != NULL) {
186 /* We're doing expect-send-expect.... */
187 c->argptr = c->nargptr;
188 /* Put the '-' back in case we ever want to rerun our script */
189 c->nargptr[-1] = '-';
190 c->nargptr = chat_NextChar(c->nargptr, '-');
191 if (c->nargptr != NULL)
192 *c->nargptr++ = '\0';
196 if ((c->argptr = c->argv[++c->arg]) == NULL) {
197 /* End of script - all ok */
198 c->state = CHAT_DONE;
202 if (c->state == CHAT_EXPECT) {
203 /* Look for expect-send-expect sequence */
204 c->nargptr = c->argptr;
206 while ((c->nargptr = chat_NextChar(c->nargptr, '-'))) {
212 log_Printf(LogWARN, "chat_UpdateSet: \"%s\": Uneven number of"
213 " '-' chars, all ignored\n", c->argptr);
215 c->nargptr = chat_NextChar(c->argptr, '-');
216 *c->nargptr++ = '\0';
222 * c->argptr now temporarily points into c->script (via c->argv)
223 * If it's an expect-send-expect sequence, we've just got the correct
224 * portion of that sequence.
227 needcr = c->state == CHAT_SEND &&
228 (*c->argptr != '!' || c->argptr[1] == '!');
230 /* We leave room for a potential HDLC header in the target string */
231 ExpandString(c, c->argptr, c->exp + 2, sizeof c->exp - 2, needcr);
234 * Now read our string. If it's not a special string, we unset
235 * ``special'' to break out of the loop.
238 if (c->abort.num < MAXABORTS) {
241 len = strlen(c->exp+2);
242 for (i = 0; i < c->abort.num; i++)
243 if (len > c->abort.string[i].len) {
246 for (last = c->abort.num; last > i; last--) {
247 c->abort.string[last].data = c->abort.string[last-1].data;
248 c->abort.string[last].len = c->abort.string[last-1].len;
252 c->abort.string[i].len = len;
253 if ((c->abort.string[i].data = (char *)malloc(len+1)) != NULL) {
254 memcpy(c->abort.string[i].data, c->exp+2, len+1);
258 log_Printf(LogERROR, "chat_UpdateSet: too many abort strings\n");
260 } else if (gottimeout) {
261 c->TimeoutSec = atoi(c->exp + 2);
262 if (c->TimeoutSec <= 0)
265 } else if (c->nargptr == NULL && !strcmp(c->exp+2, "ABORT"))
267 else if (c->nargptr == NULL && !strcmp(c->exp+2, "TIMEOUT"))
270 if (c->exp[2] == '!' && c->exp[3] != '!')
271 ExecStr(c->physical, c->exp + 3, c->exp + 3, sizeof c->exp - 3);
273 if (c->exp[2] == '\0') {
274 /* Empty string, reparse (this may be better as a `goto start') */
275 c->argptr = &arg_term;
276 return chat_UpdateSet(d, r, w, e, n);
285 log_Printf(LogWARN, "chat_UpdateSet: TIMEOUT: Argument expected\n");
287 log_Printf(LogWARN, "chat_UpdateSet: ABORT: Argument expected\n");
289 /* End of script - all ok */
290 c->state = CHAT_DONE;
294 /* set c->argptr to point in the right place */
295 c->argptr = c->exp + (c->exp[2] == '!' ? 3 : 2);
296 c->arglen = strlen(c->argptr);
298 if (c->state == CHAT_EXPECT) {
299 /* We must check to see if the string's already been found ! */
302 end = c->bufend - c->arglen + 1;
303 if (end < c->bufstart)
305 for (begin = c->bufstart; begin < end; begin++)
306 if (!strncmp(begin, c->argptr, c->arglen)) {
307 c->bufstart = begin + c->arglen;
308 c->argptr += c->arglen;
310 /* Continue - we've already read our expect string */
311 return chat_UpdateSet(d, r, w, e, n);
314 log_Printf(LogCHAT, "Expect(%d): %s\n", c->TimeoutSec, c->argptr);
320 * We now have c->argptr pointing at what we want to expect/send and
321 * c->state saying what we want to do... we now know what to put in
325 if (c->state == CHAT_EXPECT)
326 return physical_doUpdateSet(&c->physical->desc, r, NULL, e, n, 1);
328 return physical_doUpdateSet(&c->physical->desc, NULL, w, e, n, 1);
332 chat_IsSet(struct fdescriptor *d, const fd_set *fdset)
334 struct chat *c = descriptor2chat(d);
335 return c->argptr && physical_IsSet(&c->physical->desc, fdset);
339 chat_UpdateLog(struct chat *c, int in)
341 if (log_IsKept(LogCHAT) || log_IsKept(LogCONNECT)) {
343 * If a linefeed appears in the last `in' characters of `c's input
344 * buffer, output from there, all the way back to the last linefeed.
345 * This is called for every read of `in' bytes.
347 char *ptr, *end, *stop, ch;
350 level = log_IsKept(LogCHAT) ? LogCHAT : LogCONNECT;
352 end = ptr = c->bufend;
354 ptr = c->bufend - in;
355 for (end = c->bufend - 1; end >= ptr; end--)
361 for (ptr = c->bufend - (in == -1 ? 1 : in + 1); ptr >= c->bufstart; ptr--)
367 if ((stop = memchr(ptr, '\n', end - ptr)) == NULL)
371 if (level == LogCHAT || strstr(ptr, "CONNECT"))
372 log_Printf(level, "Received: %s\n", ptr);
381 chat_Read(struct fdescriptor *d, struct bundle *bundle __unused,
382 const fd_set *fdset __unused)
384 struct chat *c = descriptor2chat(d);
386 if (c->state == CHAT_EXPECT) {
388 char *abegin, *ebegin, *begin, *aend, *eend, *end;
392 * XXX - should this read only 1 byte to guarantee that we don't
393 * swallow any ppp talk from the peer ?
396 if (in > (ssize_t)sizeof c->buf / 2)
397 in = sizeof c->buf / 2;
399 in = physical_Read(c->physical, c->bufend, in);
403 /* `begin' and `end' delimit where we're going to strncmp() from */
404 ebegin = c->bufend - c->arglen + 1;
406 if (ebegin < c->bufstart)
407 ebegin = c->bufstart;
410 abegin = c->bufend - c->abort.string[0].len + 1;
411 aend = c->bufend - c->abort.string[c->abort.num-1].len + in + 1;
412 if (abegin < c->bufstart)
413 abegin = c->bufstart;
418 begin = abegin < ebegin ? abegin : ebegin;
419 end = aend < eend ? eend : aend;
423 chat_UpdateLog(c, in);
425 if (c->bufend > c->buf + sizeof c->buf / 2) {
426 /* Shuffle our receive buffer back a bit */
429 for (chop = begin - c->buf; chop; chop--)
430 if (c->buf[chop] == '\n')
431 /* found some already-logged garbage to remove :-) */
435 chop = begin - c->buf;
442 while (from < c->bufend)
455 for (; begin < end; begin++)
456 if (begin >= ebegin && begin < eend &&
457 !strncmp(begin, c->argptr, c->arglen)) {
459 timer_Stop(&c->timeout);
460 if (memchr(begin + c->arglen - 1, '\n',
461 c->bufend - begin - c->arglen + 1) == NULL) {
462 /* force it into the log */
464 c->bufend = begin + c->arglen;
465 chat_UpdateLog(c, -1);
468 c->bufstart = begin + c->arglen;
469 c->argptr += c->arglen;
472 } else if (begin >= abegin && begin < aend) {
473 for (n = c->abort.num - 1; n >= 0; n--) {
474 if (begin + c->abort.string[n].len > c->bufend)
476 if (!strncmp(begin, c->abort.string[n].data,
477 c->abort.string[n].len)) {
478 if (memchr(begin + c->abort.string[n].len - 1, '\n',
479 c->bufend - begin - c->abort.string[n].len + 1) == NULL) {
480 /* force it into the log */
482 c->bufend = begin + c->abort.string[n].len;
483 chat_UpdateLog(c, -1);
486 c->bufstart = begin + c->abort.string[n].len;
487 c->state = CHAT_FAILED;
496 chat_Write(struct fdescriptor *d, struct bundle *bundle __unused,
497 const fd_set *fdset __unused)
499 struct chat *c = descriptor2chat(d);
502 if (c->state == CHAT_SEND) {
505 if (strstr(c->argv[c->arg], "\\P")) /* Don't log the password */
506 log_Printf(LogCHAT, "Send: %s\n", c->argv[c->arg]);
511 while (sz >= 0 && c->argptr[sz] == '\n')
513 log_Printf(LogCHAT, "Send: %.*s\n", sz + 1, c->argptr);
516 if (physical_IsSync(c->physical)) {
519 * This data should be stuffed down through the link layers
521 /* There's always room for the HDLC header */
524 memcpy(c->argptr, "\377\003", 2); /* Prepend HDLC header */
527 wrote = physical_Write(c->physical, c->argptr, c->arglen);
528 result = wrote > 0 ? 1 : 0;
530 if (errno != EINTR) {
531 log_Printf(LogWARN, "chat_Write: %s\n", strerror(errno));
534 if (physical_IsSync(c->physical)) {
538 } else if (wrote < 2 && physical_IsSync(c->physical)) {
539 /* Oops - didn't even write our HDLC header ! */
552 chat_Init(struct chat *c, struct physical *p)
554 c->desc.type = CHAT_DESCRIPTOR;
555 c->desc.UpdateSet = chat_UpdateSet;
556 c->desc.IsSet = chat_IsSet;
557 c->desc.Read = chat_Read;
558 c->desc.Write = chat_Write;
565 c->bufstart = c->bufend = c->buf;
567 memset(&c->pause, '\0', sizeof c->pause);
568 memset(&c->timeout, '\0', sizeof c->timeout);
572 chat_Setup(struct chat *c, const char *data, const char *phone)
574 c->state = CHAT_EXPECT;
580 strncpy(c->script, data, sizeof c->script - 1);
581 c->script[sizeof c->script - 1] = '\0';
582 c->argc = MakeArgs(c->script, c->argv, VECSIZE(c->argv), PARSE_NOHASH);
594 timer_Stop(&c->pause);
595 timer_Stop(&c->timeout);
601 chat_Finish(struct chat *c)
603 timer_Stop(&c->pause);
604 timer_Stop(&c->timeout);
606 free(c->abort.string[--c->abort.num].data);
611 chat_Destroy(struct chat *c)
618 * \d Sleep a little (delay 2 seconds
619 * \n Line feed character
620 * \P Auth Key password
622 * \r Carrige return character
624 * \T Telephone number(s) (defined via `set phone')
629 ExpandString(struct chat *c, const char *str, char *result, int reslen, int cr)
633 result[--reslen] = '\0';
634 while (*str && reslen > 0) {
642 case 'd': /* Delay 2 seconds */
643 chat_Pause(c, 2 * SECTICKS);
646 chat_Pause(c, SECTICKS / 4);
647 break; /* Delay 0.25 seconds */
665 strncpy(result, c->physical->dl->bundle->cfg.auth.key, reslen);
666 len = strlen(result);
672 strncpy(result, c->phone, reslen);
673 len = strlen(result);
679 strncpy(result, c->physical->dl->bundle->cfg.auth.name, reslen);
680 len = strlen(result);
695 *result++ = *str++ & 0x1f;
715 ExecStr(struct physical *physical, char *command, char *out, int olen)
719 char *argv[MAXARGS], *vector[MAXARGS], *startout, *endout;
720 int stat, nb, argc, i;
722 log_Printf(LogCHAT, "Exec: %s\n", command);
723 if ((argc = MakeArgs(command, vector, VECSIZE(vector),
724 PARSE_REDUCE|PARSE_NOHASH)) <= 0) {
726 log_Printf(LogWARN, "Syntax error in exec command\n");
731 if (pipe(fids) < 0) {
732 log_Printf(LogCHAT, "Unable to create pipe in ExecStr: %s\n",
737 if ((pid = fork()) == 0) {
738 command_Expand(argv, argc, (char const *const *)vector,
739 physical->dl->bundle, 0, getpid());
742 if (fids[1] == STDIN_FILENO)
743 fids[1] = dup(fids[1]);
744 dup2(physical->fd, STDIN_FILENO);
745 dup2(fids[1], STDERR_FILENO);
746 dup2(STDIN_FILENO, STDOUT_FILENO);
748 if (open(_PATH_TTY, O_RDWR) != 3)
749 open(_PATH_DEVNULL, O_RDWR); /* Leave it closed if it fails... */
750 for (i = getdtablesize(); i > 3; i--)
751 fcntl(i, F_SETFD, 1);
753 setuid(ID0realuid());
755 execvp(argv[0], argv);
756 fprintf(stderr, "execvp: %s: %s\n", argv[0], strerror(errno));
759 char *name = strdup(vector[0]);
762 endout = out + olen - 1;
764 while (out < endout) {
765 nb = read(fids[0], out, 1);
773 waitpid(pid, &stat, WNOHANG);
774 if (WIFSIGNALED(stat)) {
775 log_Printf(LogWARN, "%s: signal %d\n", name, WTERMSIG(stat));
779 } else if (WIFEXITED(stat)) {
780 switch (WEXITSTATUS(stat)) {
785 log_Printf(LogWARN, "%s: %s\n", name, startout);
791 log_Printf(LogWARN, "%s: exit %d\n", name, WEXITSTATUS(stat));
798 log_Printf(LogWARN, "%s: Unexpected exit result\n", name);