2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 1997 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
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/types.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
44 #include <semaphore.h>
56 /* Data passed to the threads we create */
58 EditLine *edit; /* libedit stuff */
59 History *hist; /* libedit stuff */
60 pthread_t trm; /* Terminal thread (for pthread_kill()) */
61 int ppp; /* ppp descriptor */
64 /* Flags passed to Receive() */
65 #define REC_PASSWD (1) /* Handle a password request from ppp */
66 #define REC_SHOW (2) /* Show everything except prompts */
67 #define REC_VERBOSE (4) /* Show everything */
70 static char *prompt; /* Tell libedit what the current prompt is */
71 static int data = -1; /* setjmp() has been done when data != -1 */
72 static jmp_buf pppdead; /* Jump the Terminal thread out of el_gets() */
73 static int timetogo; /* Tell the Monitor thread to exit */
74 static sem_t sem_select; /* select() co-ordination between threads */
75 static int TimedOut; /* Set if our connect() timed out */
76 static int want_sem_post; /* Need to let the Monitor thread in ? */
79 * How to use pppctl...
84 fprintf(stderr, "usage: pppctl [-v] [-t n] [-p passwd] "
85 "Port|LocalSock [command[;command]...]\n");
86 fprintf(stderr, " -v tells pppctl to output all"
88 fprintf(stderr, " -t n specifies a timeout of n"
89 " seconds when connecting (default 2)\n");
90 fprintf(stderr, " -p passwd specifies your password\n");
95 * Handle the SIGALRM received due to a connect() timeout.
104 * A callback routine for libedit to find out what the current prompt is.
105 * All the work is done in Receive() below.
108 GetPrompt(EditLine *e)
116 * Receive data from the ppp descriptor.
117 * We also handle password prompts here (if asked via the `display' arg)
118 * and buffer what our prompt looks like (via the `prompt' global).
121 Receive(int fd, int display)
123 static char Buffer[LINELEN];
138 while (Result = read(fd, Buffer+len, sizeof(Buffer)-len-1), Result != -1) {
145 if (len > 2 && !strcmp(Buffer+len-2, "> ")) {
146 prompt = strrchr(Buffer, '\n');
147 if (display & (REC_SHOW|REC_VERBOSE)) {
148 if (display & REC_VERBOSE)
154 write(STDOUT_FILENO, Buffer, last-Buffer);
157 prompt = prompt == NULL ? Buffer : prompt+1;
158 for (last = Buffer+len-2; last > Buffer && *last != ' '; last--)
160 if (last > Buffer+3 && !strncmp(last-3, " on", 3)) {
161 /* a password is required ! */
162 if (display & REC_PASSWD) {
165 passwd = getpass("Password: ");
166 sprintf(Buffer, "passwd %s\n", passwd);
167 memset(passwd, '\0', strlen(passwd));
168 if (display & REC_VERBOSE)
169 write(STDOUT_FILENO, Buffer, strlen(Buffer));
170 write(fd, Buffer, strlen(Buffer));
171 memset(Buffer, '\0', strlen(Buffer));
172 return Receive(fd, display & ~REC_PASSWD);
180 if (len == sizeof Buffer - 1) {
182 if ((last = strrchr(Buffer, '\n')) == NULL)
183 /* Yeuch - this is one mother of a line ! */
184 flush = sizeof Buffer / 2;
186 flush = last - Buffer + 1;
187 write(STDOUT_FILENO, Buffer, flush);
188 strcpy(Buffer, Buffer + flush);
191 if ((Result = select(fd + 1, &f, NULL, NULL, &t)) <= 0) {
192 err = Result == -1 ? errno : 0;
194 write(STDOUT_FILENO, Buffer, len);
205 * Handle being told by the Monitor thread that there's data to be read
206 * on the ppp descriptor.
208 * Note, this is a signal handler - be careful of what we do !
211 InputHandler(int sig)
213 static char buf[LINELEN];
221 t.tv_sec = t.tv_usec = 0;
223 if (select(data + 1, &f, NULL, NULL, &t) > 0) {
224 len = read(data, buf, sizeof buf);
227 write(STDOUT_FILENO, buf, len);
229 longjmp(pppdead, -1);
232 sem_post(&sem_select);
234 /* Don't let the Monitor thread in 'till we've set ``data'' up again */
239 * This is a simple wrapper for el_gets(), allowing our SIGUSR1 signal
240 * handler (above) to take effect only after we've done a setjmp().
242 * We don't want it to do anything outside of here as we're going to
243 * service the ppp descriptor anyway.
246 SmartGets(EditLine *e, int *count, int fd)
255 /* Let the Monitor thread in again */
256 sem_post(&sem_select);
257 result = el_gets(e, count);
266 * The Terminal thread entry point.
268 * The bulk of the interactive work is done here. We read the terminal,
269 * write the results to our ppp descriptor and read the results back.
271 * While reading the terminal (using el_gets()), it's possible to take
272 * a SIGUSR1 from the Monitor thread, telling us that the ppp descriptor
273 * has some data. The data is read and displayed by the signal handler
279 struct sigaction act, oact;
280 struct thread_data *td;
284 HistEvent hev = { 0, "" };
287 act.sa_handler = InputHandler;
288 sigemptyset(&act.sa_mask);
289 act.sa_flags = SA_RESTART;
290 sigaction(SIGUSR1, &act, &oact);
292 td = (struct thread_data *)v;
295 while ((l = SmartGets(td->edit, &len, td->ppp))) {
298 history(td->hist, H_ENTER, l);
300 history(td->hist, &hev, H_ENTER, l);
302 write(td->ppp, l, len);
303 if (Receive(td->ppp, REC_SHOW) != 0)
311 * The Monitor thread entry point.
313 * This thread simply monitors our ppp descriptor. When there's something
314 * to read, a SIGUSR1 is sent to the Terminal thread.
316 * sem_select() is used by the Terminal thread to keep us from sending
317 * flurries of SIGUSR1s, and is used from the main thread to wake us up
318 * when it's time to exit.
323 struct thread_data *td;
327 td = (struct thread_data *)v;
331 sem_wait(&sem_select);
333 if ((ret = select(td->ppp + 1, &f, NULL, NULL, NULL)) > 0) {
334 pthread_kill(td->trm, SIGUSR1);
335 sem_wait(&sem_select);
342 sockaddr_ntop(const struct sockaddr *sa)
345 static char addrbuf[INET6_ADDRSTRLEN];
347 switch (sa->sa_family) {
349 addr = &((const struct sockaddr_in *)sa)->sin_addr;
352 addr = &((const struct sockaddr_un *)sa)->sun_path;
355 addr = &((const struct sockaddr_in6 *)sa)->sin6_addr;
360 inet_ntop(sa->sa_family, addr, addrbuf, sizeof(addrbuf));
365 * Connect to ppp using either a local domain socket or a tcp socket.
367 * If we're given arguments, process them and quit, otherwise create two
368 * threads to handle interactive mode.
371 main(int argc, char **argv)
373 struct sockaddr_un ifsun;
374 int n, arg, fd, len, verbose, save_errno, hide1, hide1off, hide2;
376 char *DoneWord = "x", *next, *start;
377 struct sigaction act, oact;
380 char Command[LINELEN];
381 char Buffer[LINELEN];
385 hide1 = hide1off = hide2 = 0;
387 for (arg = 1; arg < argc; arg++)
388 if (*argv[arg] == '-') {
389 for (start = argv[arg] + 1; *start; start++)
392 TimeoutVal = (unsigned)atoi
393 (start[1] ? start + 1 : argv[++arg]);
398 verbose = REC_VERBOSE;
404 hide1off = start - argv[arg];
408 hide1off = start - argv[arg];
409 passwd = argv[++arg];
430 for (harg = pos = 0; harg < argc; harg++)
431 if (harg == 0 || harg != hide2) {
432 if (harg == 0 || harg != hide1)
433 n = snprintf(title + pos, sizeof title - pos, "%s%s",
434 harg ? " " : "", argv[harg]);
435 else if (hide1off > 1)
436 n = snprintf(title + pos, sizeof title - pos, " %.*s",
437 hide1off, argv[harg]);
440 if (n < 0 || n >= sizeof title - pos)
445 setproctitle("-%s", title);
447 setproctitle("%s", title);
451 if (*argv[arg] == '/') {
452 memset(&ifsun, '\0', sizeof ifsun);
453 ifsun.sun_len = strlen(argv[arg]);
454 if (ifsun.sun_len > sizeof ifsun.sun_path - 1) {
455 warnx("%s: path too long", argv[arg]);
458 ifsun.sun_family = AF_LOCAL;
459 strcpy(ifsun.sun_path, argv[arg]);
461 if (fd = socket(AF_LOCAL, SOCK_STREAM, 0), fd < 0) {
462 warnx("cannot create local domain socket");
465 if (connect(fd, (struct sockaddr *)&ifsun, sizeof(ifsun)) < 0) {
467 warn("cannot connect to socket %s", argv[arg]);
469 warnx("cannot connect to socket %s", argv[arg]);
474 char *addr, *p, *port;
476 struct addrinfo hints, *res, *pai;
478 char local[] = "localhost";
481 if (addr[strspn(addr, "0123456789")] == '\0') {
482 /* port on local machine */
485 } else if (*addr == '[') {
487 if ((p = strchr(addr, ']')) == NULL) {
488 warnx("%s: mismatched '['", addr);
494 warnx("%s: missing port", addr);
500 p = addr + strcspn(addr, ":");
502 warnx("%s: missing port", addr);
508 memset(&hints, 0, sizeof(hints));
509 hints.ai_socktype = SOCK_STREAM;
510 gai = getaddrinfo(addr, port, &hints, &res);
512 warnx("%s: %s", addr, gai_strerror(gai));
515 for (pai = res; pai != NULL; pai = pai->ai_next) {
516 if (fd = socket(pai->ai_family, pai->ai_socktype,
517 pai->ai_protocol), fd < 0) {
518 warnx("cannot create socket");
523 act.sa_handler = Timeout;
524 sigemptyset(&act.sa_mask);
526 sigaction(SIGALRM, &act, &oact);
529 if (connect(fd, pai->ai_addr, pai->ai_addrlen) == 0)
534 sigaction(SIGALRM, &oact, 0);
537 caddr = sockaddr_ntop(pai->ai_addr);
541 warnx("timeout: cannot connect to %s", caddr);
544 warn("cannot connect to %s", caddr);
546 warnx("cannot connect to %s", caddr);
555 sigaction(SIGALRM, &oact, 0);
560 Command[sizeof(Command)-1] = '\0';
561 for (arg++; arg < argc; arg++) {
562 if (len && len < sizeof(Command)-1)
563 strcpy(Command+len++, " ");
564 strncpy(Command+len, argv[arg], sizeof(Command)-len-1);
565 len += strlen(Command+len);
568 switch (Receive(fd, verbose | REC_PASSWD)) {
570 fprintf(stderr, "Password incorrect\n");
576 struct thread_data td;
580 HistEvent hev = { 0, "" };
583 td.hist = history_init();
584 if ((env = getenv("EL_SIZE"))) {
591 history(td.hist, H_EVENT, size);
592 td.edit = el_init("pppctl", stdin, stdout);
594 history(td.hist, &hev, H_SETSIZE, size);
595 td.edit = el_init("pppctl", stdin, stdout, stderr);
597 el_source(td.edit, NULL);
598 el_set(td.edit, EL_PROMPT, GetPrompt);
599 if ((env = getenv("EL_EDITOR"))) {
600 if (!strcmp(env, "vi"))
601 el_set(td.edit, EL_EDITOR, "vi");
602 else if (!strcmp(env, "emacs"))
603 el_set(td.edit, EL_EDITOR, "emacs");
605 el_set(td.edit, EL_SIGNAL, 1);
606 el_set(td.edit, EL_HIST, history, (const char *)td.hist);
612 * We create two threads. The Terminal thread does all the
613 * work while the Monitor thread simply tells the Terminal
614 * thread when ``fd'' becomes readable. The telling is done
615 * by sending a SIGUSR1 to the Terminal thread. The
616 * sem_select semaphore is used to prevent the monitor
617 * thread from firing excessive signals at the Terminal
618 * thread (it's abused for exit handling too - see below).
620 * The Terminal thread never uses td.trm !
622 sem_init(&sem_select, 0, 0);
624 pthread_create(&td.trm, NULL, Terminal, &td);
625 pthread_create(&mon, NULL, Monitor, &td);
627 /* Wait for the terminal thread to finish */
628 pthread_join(td.trm, &thread_ret);
629 fprintf(stderr, "Connection closed\n");
631 /* Get rid of the monitor thread by abusing sem_select */
635 sem_post(&sem_select);
636 pthread_join(mon, &thread_ret);
638 /* Restore our terminal and release resources */
640 history_end(td.hist);
641 sem_destroy(&sem_select);
645 next = strchr(start, ';');
646 while (*start == ' ' || *start == '\t')
650 strcpy(Buffer, start);
651 Buffer[sizeof(Buffer)-2] = '\0';
652 strcat(Buffer, "\n");
654 write(STDOUT_FILENO, Buffer, strlen(Buffer));
655 write(fd, Buffer, strlen(Buffer));
656 if (Receive(fd, verbose | REC_SHOW) != 0) {
657 fprintf(stderr, "Connection closed\n");
662 } while (next && *next);
664 write(STDOUT_FILENO, "quit\n", 5);
665 write(fd, "quit\n", 5);
666 while (Receive(fd, verbose | REC_SHOW) == 0)
674 warnx("ppp is not responding");