pppctl.c revision 123229
1/*-
2 * Copyright (c) 1997 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
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/usr.sbin/pppctl/pppctl.c 123229 2003-12-07 08:39:29Z tjr $");
29
30#include <sys/types.h>
31
32#include <sys/socket.h>
33#include <netinet/in.h>
34#include <arpa/inet.h>
35#include <sys/un.h>
36#include <netdb.h>
37
38#include <sys/time.h>
39#include <err.h>
40#include <errno.h>
41#include <histedit.h>
42#include <semaphore.h>
43#include <pthread.h>
44#include <setjmp.h>
45#include <signal.h>
46#include <stdio.h>
47#include <stdlib.h>
48#include <string.h>
49#include <time.h>
50#include <unistd.h>
51
52#define LINELEN 2048
53
54/* Data passed to the threads we create */
55struct thread_data {
56    EditLine *edit;		/* libedit stuff */
57    History *hist;		/* libedit stuff */
58    pthread_t trm;		/* Terminal thread (for pthread_kill()) */
59    int ppp;			/* ppp descriptor */
60};
61
62/* Flags passed to Receive() */
63#define REC_PASSWD  (1)		/* Handle a password request from ppp */
64#define REC_SHOW    (2)		/* Show everything except prompts */
65#define REC_VERBOSE (4)		/* Show everything */
66
67static char *passwd;
68static char *prompt;		/* Tell libedit what the current prompt is */
69static int data = -1;		/* setjmp() has been done when data != -1 */
70static jmp_buf pppdead;		/* Jump the Terminal thread out of el_gets() */
71static int timetogo;		/* Tell the Monitor thread to exit */
72static sem_t sem_select;	/* select() co-ordination between threads */
73static int TimedOut;		/* Set if our connect() timed out */
74static int want_sem_post;	/* Need to let the Monitor thread in ? */
75
76/*
77 * How to use pppctl...
78 */
79static int
80usage()
81{
82    fprintf(stderr, "usage: pppctl [-v] [-t n] [-p passwd] "
83            "Port|LocalSock [command[;command]...]\n");
84    fprintf(stderr, "              -v tells pppctl to output all"
85            " conversation\n");
86    fprintf(stderr, "              -t n specifies a timeout of n"
87            " seconds when connecting (default 2)\n");
88    fprintf(stderr, "              -p passwd specifies your password\n");
89    exit(1);
90}
91
92/*
93 * Handle the SIGALRM received due to a connect() timeout.
94 */
95static void
96Timeout(int Sig)
97{
98    TimedOut = 1;
99}
100
101/*
102 * A callback routine for libedit to find out what the current prompt is.
103 * All the work is done in Receive() below.
104 */
105static char *
106GetPrompt(EditLine *e)
107{
108    if (prompt == NULL)
109        prompt = "";
110    return prompt;
111}
112
113/*
114 * Receive data from the ppp descriptor.
115 * We also handle password prompts here (if asked via the `display' arg)
116 * and buffer what our prompt looks like (via the `prompt' global).
117 */
118static int
119Receive(int fd, int display)
120{
121    static char Buffer[LINELEN];
122    struct timeval t;
123    int Result;
124    char *last;
125    fd_set f;
126    int len;
127
128    FD_ZERO(&f);
129    FD_SET(fd, &f);
130    t.tv_sec = 0;
131    t.tv_usec = 100000;
132    prompt = Buffer;
133    len = 0;
134
135    while (Result = read(fd, Buffer+len, sizeof(Buffer)-len-1), Result != -1) {
136        if (Result == 0 && errno != EINTR) {
137            Result = -1;
138            break;
139        }
140        len += Result;
141        Buffer[len] = '\0';
142        if (len > 2 && !strcmp(Buffer+len-2, "> ")) {
143            prompt = strrchr(Buffer, '\n');
144            if (display & (REC_SHOW|REC_VERBOSE)) {
145                if (display & REC_VERBOSE)
146                    last = Buffer+len-1;
147                else
148                    last = prompt;
149                if (last) {
150                    last++;
151                    write(STDOUT_FILENO, Buffer, last-Buffer);
152                }
153            }
154            prompt = prompt == NULL ? Buffer : prompt+1;
155            for (last = Buffer+len-2; last > Buffer && *last != ' '; last--)
156                ;
157            if (last > Buffer+3 && !strncmp(last-3, " on", 3)) {
158                 /* a password is required ! */
159                 if (display & REC_PASSWD) {
160                    /* password time */
161                    if (!passwd)
162                        passwd = getpass("Password: ");
163                    sprintf(Buffer, "passwd %s\n", passwd);
164                    memset(passwd, '\0', strlen(passwd));
165                    if (display & REC_VERBOSE)
166                        write(STDOUT_FILENO, Buffer, strlen(Buffer));
167                    write(fd, Buffer, strlen(Buffer));
168                    memset(Buffer, '\0', strlen(Buffer));
169                    return Receive(fd, display & ~REC_PASSWD);
170                }
171                Result = 1;
172            } else
173                Result = 0;
174            break;
175        } else
176            prompt = "";
177        if (len == sizeof Buffer - 1) {
178            int flush;
179            if ((last = strrchr(Buffer, '\n')) == NULL)
180                /* Yeuch - this is one mother of a line ! */
181                flush = sizeof Buffer / 2;
182            else
183                flush = last - Buffer + 1;
184            write(STDOUT_FILENO, Buffer, flush);
185            strcpy(Buffer, Buffer + flush);
186            len -= flush;
187        }
188        if ((Result = select(fd + 1, &f, NULL, NULL, &t)) <= 0) {
189            if (len)
190                write(STDOUT_FILENO, Buffer, len);
191            break;
192        }
193    }
194
195    return Result;
196}
197
198/*
199 * Handle being told by the Monitor thread that there's data to be read
200 * on the ppp descriptor.
201 *
202 * Note, this is a signal handler - be careful of what we do !
203 */
204static void
205InputHandler(int sig)
206{
207    static char buf[LINELEN];
208    struct timeval t;
209    int len;
210    fd_set f;
211
212    if (data != -1) {
213        FD_ZERO(&f);
214        FD_SET(data, &f);
215        t.tv_sec = t.tv_usec = 0;
216
217        if (select(data + 1, &f, NULL, NULL, &t) > 0) {
218            len = read(data, buf, sizeof buf);
219
220            if (len > 0)
221                write(STDOUT_FILENO, buf, len);
222            else if (data != -1)
223                longjmp(pppdead, -1);
224        }
225
226        sem_post(&sem_select);
227    } else
228        /* Don't let the Monitor thread in 'till we've set ``data'' up again */
229        want_sem_post = 1;
230}
231
232/*
233 * This is a simple wrapper for el_gets(), allowing our SIGUSR1 signal
234 * handler (above) to take effect only after we've done a setjmp().
235 *
236 * We don't want it to do anything outside of here as we're going to
237 * service the ppp descriptor anyway.
238 */
239static const char *
240SmartGets(EditLine *e, int *count, int fd)
241{
242    const char *result;
243
244    if (setjmp(pppdead))
245        result = NULL;
246    else {
247        data = fd;
248        if (want_sem_post)
249            /* Let the Monitor thread in again */
250            sem_post(&sem_select);
251        result = el_gets(e, count);
252    }
253
254    data = -1;
255
256    return result;
257}
258
259/*
260 * The Terminal thread entry point.
261 *
262 * The bulk of the interactive work is done here.  We read the terminal,
263 * write the results to our ppp descriptor and read the results back.
264 *
265 * While reading the terminal (using el_gets()), it's possible to take
266 * a SIGUSR1 from the Monitor thread, telling us that the ppp descriptor
267 * has some data.  The data is read and displayed by the signal handler
268 * itself.
269 */
270static void *
271Terminal(void *v)
272{
273    struct sigaction act, oact;
274    struct thread_data *td;
275    const char *l;
276    int len;
277#ifndef __OpenBSD__
278    HistEvent hev = { 0, "" };
279#endif
280
281    act.sa_handler = InputHandler;
282    sigemptyset(&act.sa_mask);
283    act.sa_flags = SA_RESTART;
284    sigaction(SIGUSR1, &act, &oact);
285
286    td = (struct thread_data *)v;
287    want_sem_post = 1;
288
289    while ((l = SmartGets(td->edit, &len, td->ppp))) {
290        if (len > 1)
291#ifdef __OpenBSD__
292            history(td->hist, H_ENTER, l);
293#else
294            history(td->hist, &hev, H_ENTER, l);
295#endif
296        write(td->ppp, l, len);
297        if (Receive(td->ppp, REC_SHOW) != 0)
298            break;
299    }
300
301    return NULL;
302}
303
304/*
305 * The Monitor thread entry point.
306 *
307 * This thread simply monitors our ppp descriptor.  When there's something
308 * to read, a SIGUSR1 is sent to the Terminal thread.
309 *
310 * sem_select() is used by the Terminal thread to keep us from sending
311 * flurries of SIGUSR1s, and is used from the main thread to wake us up
312 * when it's time to exit.
313 */
314static void *
315Monitor(void *v)
316{
317    struct thread_data *td;
318    fd_set f;
319    int ret;
320
321    td = (struct thread_data *)v;
322    FD_ZERO(&f);
323    FD_SET(td->ppp, &f);
324
325    sem_wait(&sem_select);
326    while (!timetogo)
327        if ((ret = select(td->ppp + 1, &f, NULL, NULL, NULL)) > 0) {
328            pthread_kill(td->trm, SIGUSR1);
329            sem_wait(&sem_select);
330        }
331
332    return NULL;
333}
334
335static const char *
336sockaddr_ntop(const struct sockaddr *sa)
337{
338    const void *addr;
339    static char addrbuf[INET6_ADDRSTRLEN];
340
341    switch (sa->sa_family) {
342    case AF_INET:
343	addr = &((const struct sockaddr_in *)sa)->sin_addr;
344	break;
345    case AF_UNIX:
346	addr = &((const struct sockaddr_un *)sa)->sun_path;
347	break;
348    case AF_INET6:
349	addr = &((const struct sockaddr_in6 *)sa)->sin6_addr;
350	break;
351    default:
352	return NULL;
353    }
354    inet_ntop(sa->sa_family, addr, addrbuf, sizeof(addrbuf));
355    return addrbuf;
356}
357
358/*
359 * Connect to ppp using either a local domain socket or a tcp socket.
360 *
361 * If we're given arguments, process them and quit, otherwise create two
362 * threads to handle interactive mode.
363 */
364int
365main(int argc, char **argv)
366{
367    struct sockaddr_un ifsun;
368    int n, arg, fd, len, verbose, save_errno, hide1, hide1off, hide2;
369    unsigned TimeoutVal;
370    char *DoneWord = "x", *next, *start;
371    struct sigaction act, oact;
372    void *thread_ret;
373    pthread_t mon;
374    char Command[LINELEN];
375    char Buffer[LINELEN];
376
377    verbose = 0;
378    TimeoutVal = 2;
379    hide1 = hide1off = hide2 = 0;
380
381    for (arg = 1; arg < argc; arg++)
382        if (*argv[arg] == '-') {
383            for (start = argv[arg] + 1; *start; start++)
384                switch (*start) {
385                    case 't':
386                        TimeoutVal = (unsigned)atoi
387                            (start[1] ? start + 1 : argv[++arg]);
388                        start = DoneWord;
389                        break;
390
391                    case 'v':
392                        verbose = REC_VERBOSE;
393                        break;
394
395                    case 'p':
396                        if (start[1]) {
397                          hide1 = arg;
398                          hide1off = start - argv[arg];
399                          passwd = start + 1;
400                        } else {
401                          hide1 = arg;
402                          hide1off = start - argv[arg];
403                          passwd = argv[++arg];
404                          hide2 = arg;
405                        }
406                        start = DoneWord;
407                        break;
408
409                    default:
410                        usage();
411                }
412        }
413        else
414            break;
415
416
417    if (argc < arg + 1)
418        usage();
419
420    if (hide1) {
421      char title[1024];
422      int pos, harg;
423
424      for (harg = pos = 0; harg < argc; harg++)
425        if (harg == 0 || harg != hide2) {
426          if (harg == 0 || harg != hide1)
427            n = snprintf(title + pos, sizeof title - pos, "%s%s",
428                            harg ? " " : "", argv[harg]);
429          else if (hide1off > 1)
430            n = snprintf(title + pos, sizeof title - pos, " %.*s",
431                            hide1off, argv[harg]);
432          else
433            n = 0;
434          if (n < 0 || n >= sizeof title - pos)
435            break;
436          pos += n;
437        }
438#ifdef __FreeBSD__
439      setproctitle("-%s", title);
440#else
441      setproctitle("%s", title);
442#endif
443    }
444
445    if (*argv[arg] == '/') {
446        memset(&ifsun, '\0', sizeof ifsun);
447        ifsun.sun_len = strlen(argv[arg]);
448        if (ifsun.sun_len > sizeof ifsun.sun_path - 1) {
449            warnx("%s: path too long", argv[arg]);
450            return 1;
451        }
452        ifsun.sun_family = AF_LOCAL;
453        strcpy(ifsun.sun_path, argv[arg]);
454
455        if (fd = socket(AF_LOCAL, SOCK_STREAM, 0), fd < 0) {
456            warnx("cannot create local domain socket");
457            return 2;
458        }
459	if (connect(fd, (struct sockaddr *)&ifsun, sizeof(ifsun)) < 0) {
460	    if (errno)
461		warn("cannot connect to socket %s", argv[arg]);
462	    else
463		warnx("cannot connect to socket %s", argv[arg]);
464	    close(fd);
465	    return 3;
466	}
467    } else {
468        char *addr, *p, *port;
469	const char *caddr;
470	struct addrinfo hints, *res, *pai;
471        int gai;
472	char local[] = "localhost";
473
474	addr = argv[arg];
475	if (addr[strspn(addr, "0123456789")] == '\0') {
476	    /* port on local machine */
477	    port = addr;
478	    addr = local;
479	} else if (*addr == '[') {
480	    /* [addr]:port */
481	    if ((p = strchr(addr, ']')) == NULL) {
482		warnx("%s: mismatched '['", addr);
483		return 1;
484	    }
485	    addr++;
486	    *p++ = '\0';
487	    if (*p != ':') {
488		warnx("%s: missing port", addr);
489		return 1;
490	    }
491	    port = ++p;
492	} else {
493	    /* addr:port */
494	    p = addr + strcspn(addr, ":");
495	    if (*p != ':') {
496		warnx("%s: missing port", addr);
497		return 1;
498	    }
499	    *p++ = '\0';
500	    port = p;
501	}
502	memset(&hints, 0, sizeof(hints));
503	hints.ai_socktype = SOCK_STREAM;
504	gai = getaddrinfo(addr, port, &hints, &res);
505	if (gai != 0) {
506	    warnx("%s: %s", addr, gai_strerror(gai));
507	    return 1;
508	}
509	for (pai = res; pai != NULL; pai = pai->ai_next) {
510	    if (fd = socket(pai->ai_family, pai->ai_socktype,
511		pai->ai_protocol), fd < 0) {
512		warnx("cannot create socket");
513		continue;
514	    }
515	    TimedOut = 0;
516	    if (TimeoutVal) {
517		act.sa_handler = Timeout;
518		sigemptyset(&act.sa_mask);
519		act.sa_flags = 0;
520		sigaction(SIGALRM, &act, &oact);
521		alarm(TimeoutVal);
522	    }
523	    if (connect(fd, pai->ai_addr, pai->ai_addrlen) == 0)
524		break;
525	    if (TimeoutVal) {
526		save_errno = errno;
527		alarm(0);
528		sigaction(SIGALRM, &oact, 0);
529		errno = save_errno;
530	    }
531	    caddr = sockaddr_ntop(pai->ai_addr);
532	    if (caddr == NULL)
533		caddr = argv[arg];
534	    if (TimedOut)
535		warnx("timeout: cannot connect to %s", caddr);
536	    else {
537		if (errno)
538		    warn("cannot connect to %s", caddr);
539		else
540		    warnx("cannot connect to %s", caddr);
541	    }
542	    close(fd);
543	}
544	freeaddrinfo(res);
545	if (pai == NULL)
546	    return 1;
547	if (TimeoutVal) {
548	    alarm(0);
549	    sigaction(SIGALRM, &oact, 0);
550	}
551    }
552
553    len = 0;
554    Command[sizeof(Command)-1] = '\0';
555    for (arg++; arg < argc; arg++) {
556        if (len && len < sizeof(Command)-1)
557            strcpy(Command+len++, " ");
558        strncpy(Command+len, argv[arg], sizeof(Command)-len-1);
559        len += strlen(Command+len);
560    }
561
562    switch (Receive(fd, verbose | REC_PASSWD)) {
563        case 1:
564            fprintf(stderr, "Password incorrect\n");
565            break;
566
567        case 0:
568            passwd = NULL;
569            if (len == 0) {
570                struct thread_data td;
571                const char *env;
572                int size;
573#ifndef __OpenBSD__
574                HistEvent hev = { 0, "" };
575#endif
576
577                td.hist = history_init();
578                if ((env = getenv("EL_SIZE"))) {
579                    size = atoi(env);
580                    if (size < 0)
581                      size = 20;
582                } else
583                    size = 20;
584#ifdef __OpenBSD__
585                history(td.hist, H_EVENT, size);
586                td.edit = el_init("pppctl", stdin, stdout);
587#else
588                history(td.hist, &hev, H_SETSIZE, size);
589                td.edit = el_init("pppctl", stdin, stdout, stderr);
590#endif
591                el_source(td.edit, NULL);
592                el_set(td.edit, EL_PROMPT, GetPrompt);
593                if ((env = getenv("EL_EDITOR"))) {
594                    if (!strcmp(env, "vi"))
595                        el_set(td.edit, EL_EDITOR, "vi");
596                    else if (!strcmp(env, "emacs"))
597                        el_set(td.edit, EL_EDITOR, "emacs");
598                }
599                el_set(td.edit, EL_SIGNAL, 1);
600                el_set(td.edit, EL_HIST, history, (const char *)td.hist);
601
602                td.ppp = fd;
603                td.trm = NULL;
604
605                /*
606                 * We create two threads.  The Terminal thread does all the
607                 * work while the Monitor thread simply tells the Terminal
608                 * thread when ``fd'' becomes readable.  The telling is done
609                 * by sending a SIGUSR1 to the Terminal thread.  The
610                 * sem_select semaphore is used to prevent the monitor
611                 * thread from firing excessive signals at the Terminal
612                 * thread (it's abused for exit handling too - see below).
613                 *
614                 * The Terminal thread never uses td.trm !
615                 */
616                sem_init(&sem_select, 0, 0);
617
618                pthread_create(&td.trm, NULL, Terminal, &td);
619                pthread_create(&mon, NULL, Monitor, &td);
620
621                /* Wait for the terminal thread to finish */
622                pthread_join(td.trm, &thread_ret);
623                fprintf(stderr, "Connection closed\n");
624
625                /* Get rid of the monitor thread by abusing sem_select */
626                timetogo = 1;
627                close(fd);
628                fd = -1;
629                sem_post(&sem_select);
630                pthread_join(mon, &thread_ret);
631
632                /* Restore our terminal and release resources */
633                el_end(td.edit);
634                history_end(td.hist);
635                sem_destroy(&sem_select);
636            } else {
637                start = Command;
638                do {
639                    next = strchr(start, ';');
640                    while (*start == ' ' || *start == '\t')
641                        start++;
642                    if (next)
643                        *next = '\0';
644                    strcpy(Buffer, start);
645                    Buffer[sizeof(Buffer)-2] = '\0';
646                    strcat(Buffer, "\n");
647                    if (verbose)
648                        write(STDOUT_FILENO, Buffer, strlen(Buffer));
649                    write(fd, Buffer, strlen(Buffer));
650                    if (Receive(fd, verbose | REC_SHOW) != 0) {
651                        fprintf(stderr, "Connection closed\n");
652                        break;
653                    }
654                    if (next)
655                        start = ++next;
656                } while (next && *next);
657                if (verbose)
658                    write(STDOUT_FILENO, "quit\n", 5);
659                write(fd, "quit\n", 5);
660                while (Receive(fd, verbose | REC_SHOW) == 0)
661                    ;
662                if (verbose)
663                    puts("");
664            }
665            break;
666
667        default:
668            warnx("ppp is not responding");
669            break;
670    }
671
672    if (fd != -1)
673        close(fd);
674
675    return 0;
676}
677