8322 nl: misleading-indentation
[unleashed/tickless.git] / usr / src / cmd / cmd-inet / usr.bin / pppd / main.c
blob4207ea17125ec0ccae5dea12e24cdd989725be4f
1 /*
2 * main.c - Point-to-Point Protocol main module
4 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
5 * Use is subject to license terms.
7 * Permission to use, copy, modify, and distribute this software and its
8 * documentation is hereby granted, provided that the above copyright
9 * notice appears in all copies.
11 * SUN MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF
12 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
13 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
14 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
15 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
16 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES
18 * Copyright (c) 1989 Carnegie Mellon University.
19 * All rights reserved.
21 * Redistribution and use in source and binary forms are permitted
22 * provided that the above copyright notice and this paragraph are
23 * duplicated in all such forms and that any documentation,
24 * advertising materials, and other materials related to such
25 * distribution and use acknowledge that the software was developed
26 * by Carnegie Mellon University. The name of the
27 * University may not be used to endorse or promote products derived
28 * from this software without specific prior written permission.
29 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
31 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
34 * Copyright (c) 2016 by Delphix. All rights reserved.
37 #define RCSID "$Id: main.c,v 1.97 2000/04/24 02:54:16 masputra Exp $"
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <signal.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <syslog.h>
47 #include <netdb.h>
48 #include <pwd.h>
49 #include <setjmp.h>
50 #include <sys/param.h>
51 #include <sys/types.h>
52 #include <sys/wait.h>
53 #include <sys/time.h>
54 #include <sys/resource.h>
55 #include <sys/stat.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <arpa/inet.h>
60 #include "pppd.h"
61 #include "magic.h"
62 #include "fsm.h"
63 #include "lcp.h"
64 #include "ipcp.h"
65 #ifdef INET6
66 #include "ipv6cp.h"
67 #endif
68 #include "upap.h"
69 #include "chap.h"
70 #include "ccp.h"
71 #include "pathnames.h"
72 #include "patchlevel.h"
74 #ifdef HAVE_MULTILINK
75 #include "tdb.h"
76 #endif
78 #ifdef CBCP_SUPPORT
79 #include "cbcp.h"
80 #endif
82 #ifdef IPX_CHANGE
83 #include "ipxcp.h"
84 #endif /* IPX_CHANGE */
85 #ifdef AT_CHANGE
86 #include "atcp.h"
87 #endif
89 #if !defined(lint) && !defined(_lint)
90 static const char rcsid[] = RCSID;
91 #endif
93 /* interface vars */
94 char ifname[32]; /* Interface name */
95 int ifunit = -1; /* Interface unit number */
97 char *progname; /* Name of this program */
98 char hostname[MAXHOSTNAMELEN+1]; /* Our hostname */
99 static char pidfilename[MAXPATHLEN]; /* name of pid file */
100 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
101 char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
102 static uid_t uid; /* Our real user-id */
103 static int conn_running; /* we have a [dis]connector running */
105 int ttyfd; /* Serial port file descriptor */
106 mode_t tty_mode = (mode_t)-1; /* Original access permissions to tty */
107 int baud_rate; /* Actual bits/second for serial device */
108 bool hungup; /* terminal has been hung up */
109 bool privileged; /* we're running as real uid root */
110 bool need_holdoff; /* need holdoff period before restarting */
111 bool detached; /* have detached from terminal */
112 struct stat devstat; /* result of stat() on devnam */
113 bool prepass = 0; /* doing prepass to find device name */
114 int devnam_fixed; /* set while in options.ttyxx file */
115 volatile int status; /* exit status for pppd */
116 int unsuccess; /* # unsuccessful connection attempts */
117 int do_callback; /* != 0 if we should do callback next */
118 int doing_callback; /* != 0 if we are doing callback */
119 char *callback_script; /* script for doing callback */
120 #ifdef HAVE_MULTILINK
121 TDB_CONTEXT *pppdb; /* database for storing status etc. */
122 char db_key[32];
123 #endif
126 * For plug-in usage:
128 * holdoff_hook - Can be used to change the demand-dial hold-off
129 * time dynamically. This is normally set by the
130 * "holdoff" option, and is 30 seconds by default.
132 * new_phase_hook - This is called for each change in the PPP
133 * phase (per RFC 1661). This can be used to log
134 * progress.
136 * check_options_hook - This is called before doing sys_init()
137 * and allows the plugin to verify the selected options.
139 * updown_script_hook - This is called with the proposed
140 * command-line arguments for any of the
141 * /etc/ppp/{ip,ipv6,ipx,auth}-{up,down} scripts before
142 * fork/exec. It can be used to add or change arguments.
144 * device_pipe_hook - If this is set, then an extra fd (3) is
145 * passed to the connect/disconnect script. This extra
146 * fd is the write side of a pipe, and the read side is
147 * passed to this routine. This can be used to pass
148 * arbitrary data from the script back to pppd.
150 int (*holdoff_hook) __P((void)) = NULL;
151 int (*new_phase_hook) __P((int new, int old)) = NULL;
152 int (*check_options_hook) __P((uid_t uid)) = NULL;
153 int (*updown_script_hook) __P((const char ***argsp)) = NULL;
154 void (*device_pipe_hook) __P((int pipefd)) = NULL;
156 static int fd_ppp = -1; /* fd for talking PPP */
157 static int fd_loop; /* fd for getting demand-dial packets */
158 static int pty_master; /* fd for master side of pty */
159 int pty_slave = -1; /* fd for slave side of pty */
160 static int real_ttyfd; /* fd for actual serial port (not pty) */
162 int phase; /* where the link is at */
163 int kill_link;
164 int open_ccp_flag;
166 static int waiting; /* for input from peer or timer expiration */
167 static sigjmp_buf sigjmp;
169 char **script_env; /* Env. variable values for scripts */
170 int s_env_nalloc; /* # words avail at script_env */
172 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
173 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
174 u_char nak_buffer[PPP_MRU]; /* where we construct a nak packet */
176 static int n_children; /* # child processes still running */
177 static bool got_sigchld; /* set if we have received a SIGCHLD */
178 static sigset_t main_sigmask; /* signals blocked while dispatching */
180 static bool locked; /* lock() has succeeded */
181 static bool privopen; /* don't lock, open device as root */
183 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
185 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
186 int ngroups; /* How many groups valid in groups */
188 static struct timeval start_time; /* Time when link was started. */
190 struct pppd_stats link_stats;
191 int link_connect_time;
192 bool link_stats_valid;
194 static pid_t charshunt_pid; /* Process ID for charshunt */
196 extern option_t general_options[];
197 extern option_t auth_options[];
200 * We maintain a list of child process pids and
201 * functions to call when they exit.
203 struct subprocess {
204 pid_t pid;
205 char *prog;
206 void (*done) __P((void *, int));
207 void *arg;
208 struct subprocess *next;
211 static struct subprocess *children;
213 /* Prototypes for procedures local to this file. */
215 static void setup_signals __P((void));
216 static void create_pidfile __P((void));
217 static void create_linkpidfile __P((void));
218 static void cleanup __P((void));
219 static void close_tty __P((void));
220 static void get_input __P((void));
221 static void calltimeout __P((void));
222 static struct timeval *timeleft __P((struct timeval *));
223 static void kill_my_pg __P((int));
224 static void hup __P((int));
225 static void term __P((int));
226 static void chld __P((int));
227 static void toggle_debug __P((int));
228 static void open_ccp __P((int));
229 static void bad_signal __P((int));
230 static void holdoff_end __P((void *));
231 static int device_script __P((char *, int, int, int, char *));
232 static int reap_kids __P((int waitfor));
233 static void record_child __P((pid_t, char *, void (*) (void *, int), void *));
234 static int open_socket __P((char *));
235 static int start_charshunt __P((int, int));
236 static void charshunt_done __P((void *, int));
237 static void charshunt __P((int, int, char *));
238 static int record_write __P((FILE *, int code, u_char *buf, int nb,
239 struct timeval *));
240 static void final_reap __P((void));
242 #ifdef HAVE_MULTILINK
243 static void update_db_entry __P((void));
244 static void add_db_key __P((const char *));
245 static void delete_db_key __P((const char *));
246 static void cleanup_db __P((void));
247 #endif
249 int main __P((int, char *[]));
251 #ifdef ultrix
252 #undef O_NONBLOCK
253 #define O_NONBLOCK O_NDELAY
254 #endif
256 #ifdef ULTRIX
257 #define setlogmask(x) 0
258 #endif
260 /* Backward compatibility for Linux */
261 #ifndef RECMARK_TIMESTART
262 #define RECMARK_STARTSEND 1
263 #define RECMARK_STARTRECV 2
264 #define RECMARK_ENDSEND 3
265 #define RECMARK_ENDRECV 4
266 #define RECMARK_TIMEDELTA32 5
267 #define RECMARK_TIMEDELTA8 6
268 #define RECMARK_TIMESTART 7
269 #endif
272 * PPP Data Link Layer "protocol" table.
273 * One entry per supported protocol.
274 * The last entry must be NULL.
276 struct protent *protocols[] = {
277 &lcp_protent,
278 &pap_protent,
279 &chap_protent,
280 #ifdef CBCP_SUPPORT
281 &cbcp_protent,
282 #endif
283 &ipcp_protent,
284 #ifdef INET6
285 &ipv6cp_protent,
286 #endif
287 &ccp_protent,
288 #ifdef IPX_CHANGE
289 &ipxcp_protent,
290 #endif
291 #ifdef AT_CHANGE
292 &atcp_protent,
293 #endif
294 NULL
298 main(argc, argv)
299 int argc;
300 char *argv[];
302 int i, fdflags, t;
303 char *p, *connector;
304 struct passwd *pw;
305 struct timeval timo;
306 struct protent *protp;
307 struct stat statbuf;
308 char numbuf[16];
310 ifname[0] = '\0';
311 new_phase(PHASE_INITIALIZE);
314 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
315 * This way we can close 0, 1, 2 in detach() without clobbering
316 * a fd that we are using.
318 if ((i = open(_PATH_DEVNULL, O_RDWR)) >= 0) {
319 while (0 <= i && i <= 2)
320 i = dup(i);
321 if (i >= 0)
322 (void) close(i);
325 script_env = NULL;
327 /* Initialize syslog facilities */
328 reopen_log();
330 if (gethostname(hostname, MAXHOSTNAMELEN+1) < 0 ) {
331 option_error("Couldn't get hostname: %m");
332 exit(1);
334 hostname[MAXHOSTNAMELEN] = '\0';
336 /* make sure we don't create world or group writable files. */
337 (void) umask(umask(0777) | 022);
339 uid = getuid();
340 privileged = (uid == 0);
341 (void) slprintf(numbuf, sizeof(numbuf), "%d", uid);
342 script_setenv("ORIG_UID", numbuf, 0);
344 ngroups = getgroups(NGROUPS_MAX, groups);
347 * Initialize magic number generator now so that protocols may
348 * use magic numbers in initialization.
350 magic_init();
352 progname = *argv;
353 prepass = 0;
355 * Initialize to the standard option set, then parse, in order, the
356 * system options file, the user's options file, the tty's options file,
357 * and the command line arguments. At last, install the options declared
358 * by each protocol into the extra_option list.
360 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
361 (*protp->init)(0);
362 if (protp->options != NULL) {
363 add_options(protp->options);
368 * Install "generic" options into the extra_options list.
370 add_options(auth_options);
371 add_options(general_options);
373 /* Install any system-specific options (or remove unusable ones) */
374 sys_options();
376 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
377 || !options_from_user())
378 exit(EXIT_OPTION_ERROR);
380 /* scan command line and options files to find device name */
381 prepass = 1;
382 (void) parse_args(argc-1, argv+1);
383 prepass = 0;
386 * Work out the device name, if it hasn't already been specified.
388 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
389 if (!using_pty && default_device && !direct_tty) {
390 char *p;
392 if (!isatty(0) || (p = ttyname(0)) == NULL) {
393 option_error("no device specified and stdin is not a tty");
394 exit(EXIT_OPTION_ERROR);
396 (void) strlcpy(devnam, p, sizeof(devnam));
397 if (stat(devnam, &devstat) < 0)
398 fatal("Couldn't stat default device %s: %m", devnam);
402 * Parse the tty options file and the command line.
403 * The per-tty options file should not change
404 * ptycommand, pty_socket, notty or devnam.
406 devnam_fixed = 1;
407 if (!using_pty && !direct_tty) {
408 if (!options_for_tty())
409 exit(EXIT_OPTION_ERROR);
412 devnam_fixed = 0;
413 if (!parse_args(argc-1, argv+1))
414 exit(EXIT_OPTION_ERROR);
417 * Check that we are running as root.
419 if (geteuid() != 0) {
420 option_error("must be root to run %s, since it is not setuid-root",
421 argv[0]);
422 exit(EXIT_NOT_ROOT);
425 if (!ppp_available()) {
426 option_error(no_ppp_msg);
427 exit(EXIT_NO_KERNEL_SUPPORT);
431 * Check that the options given are valid and consistent.
433 if (!sys_check_options())
434 exit(EXIT_OPTION_ERROR);
435 auth_check_options();
436 #ifdef HAVE_MULTILINK
437 mp_check_options();
438 #endif
439 for (i = 0; (protp = protocols[i]) != NULL; ++i)
440 if (protp->enabled_flag && protp->check_options != NULL)
441 (*protp->check_options)();
442 if (demand && (connect_script == NULL)) {
443 option_error("connect script is required for demand-dialling\n");
444 exit(EXIT_OPTION_ERROR);
446 if (updetach && (nodetach || demand)) {
447 option_error("updetach cannot be used with %s",
448 nodetach ? "nodetach" : "demand");
449 exit(EXIT_OPTION_ERROR);
451 /* default holdoff to 0 if no connect script has been given */
452 if ((connect_script == NULL) && !holdoff_specified)
453 holdoff = 0;
455 if (using_pty || direct_tty) {
456 if (!default_device) {
457 option_error("%s option precludes specifying device name",
458 notty? "notty": "pty");
459 exit(EXIT_OPTION_ERROR);
461 if (ptycommand != NULL && (notty || direct_tty)) {
462 option_error("pty option is incompatible with notty option");
463 exit(EXIT_OPTION_ERROR);
465 if (pty_socket != NULL && (ptycommand != NULL || notty ||
466 direct_tty)) {
467 option_error("socket option is incompatible with pty and notty");
468 exit(EXIT_OPTION_ERROR);
470 default_device = notty || direct_tty;
471 lockflag = 0;
472 modem = 0;
473 if (default_device && log_to_fd <= 1)
474 log_to_fd = -1;
475 } else {
477 * If the user has specified a device which is the same as
478 * the one on stdin, pretend they didn't specify any.
479 * If the device is already open read/write on stdin,
480 * we assume we don't need to lock it, and we can open it as root.
482 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
483 && statbuf.st_rdev == devstat.st_rdev) {
484 default_device = 1;
485 fdflags = fcntl(0, F_GETFL);
486 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
487 privopen = 1;
490 if (default_device)
491 nodetach = 1;
494 * Don't send log messages to the serial port, it tends to
495 * confuse the peer. :-)
497 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
498 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
499 log_to_fd = -1;
500 early_log = 0;
502 if (debug)
503 (void) setlogmask(LOG_UPTO(LOG_DEBUG));
506 * Initialize system-dependent stuff.
508 if (check_options_hook != NULL &&
509 (*check_options_hook)(uid) == -1) {
510 exit(EXIT_OPTION_ERROR);
512 sys_init(!devnam_info.priv && !privopen);
514 #ifdef HAVE_MULTILINK
515 pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
516 if (pppdb != NULL) {
517 (void) slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
518 update_db_entry();
519 } else {
520 warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
521 if (multilink) {
522 warn("Warning: disabling multilink");
523 multilink = 0;
526 #endif
529 * Detach ourselves from the terminal, if required, and identify
530 * who is running us. Printing to stderr stops here unless
531 * nodetach or updetach is set.
533 if (!nodetach && !updetach)
534 detach();
535 p = getlogin();
536 if (p == NULL) {
537 pw = getpwuid(uid);
538 if (pw != NULL && pw->pw_name != NULL)
539 p = pw->pw_name;
540 else
541 p = "(unknown)";
543 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
544 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
545 script_setenv("PPPLOGNAME", p, 0);
547 if (devnam[0] != '\0')
548 script_setenv("DEVICE", devnam, 1);
549 (void) slprintf(numbuf, sizeof(numbuf), "%d", getpid());
550 script_setenv("PPPD_PID", numbuf, 1);
552 setup_signals();
554 waiting = 0;
556 create_linkpidfile();
559 * If we're doing dial-on-demand, set up the interface now.
561 if (demand) {
563 * Open the loopback channel and set it up to be the ppp interface.
565 #ifdef HAVE_MULTILINK
566 (void) tdb_writelock(pppdb);
567 #endif
568 set_ifunit(1);
569 fd_loop = open_ppp_loopback();
570 #ifdef HAVE_MULTILINK
571 (void) tdb_writeunlock(pppdb);
572 #endif
575 * Configure the interface and mark it up, etc.
577 demand_conf();
580 new_phase(PHASE_INITIALIZED);
581 do_callback = 0;
582 for (;;) {
584 need_holdoff = 1;
585 ttyfd = -1;
586 real_ttyfd = -1;
587 status = EXIT_OK;
588 ++unsuccess;
589 doing_callback = do_callback;
590 do_callback = 0;
592 if (demand && !doing_callback) {
594 * Don't do anything until we see some activity.
596 kill_link = 0;
597 new_phase(PHASE_DORMANT);
598 demand_unblock();
599 add_fd(fd_loop);
600 for (;;) {
601 if (sigsetjmp(sigjmp, 1) == 0) {
602 (void) sigprocmask(SIG_BLOCK, &main_sigmask, NULL);
603 if (kill_link || got_sigchld) {
604 (void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
605 } else {
606 waiting = 1;
607 (void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
608 wait_input(timeleft(&timo));
611 waiting = 0;
612 calltimeout();
613 if (kill_link) {
614 if (!persist)
615 break;
616 kill_link = 0;
618 if (get_loop_output())
619 break;
620 if (got_sigchld)
621 (void) reap_kids(0);
623 remove_fd(fd_loop);
624 if (kill_link && !persist)
625 break;
628 * Now we want to bring up the link.
630 demand_block();
631 info("Starting link");
634 new_phase(doing_callback ? PHASE_CALLINGBACK : PHASE_SERIALCONN);
637 * Get a pty master/slave pair if the pty, notty, socket,
638 * or record options were specified.
640 (void) strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
641 pty_master = -1;
642 pty_slave = -1;
643 if (using_pty || record_file != NULL) {
644 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
645 error("Couldn't allocate pseudo-tty");
646 status = EXIT_FATAL_ERROR;
647 goto fail;
649 set_up_tty(pty_slave, 1);
653 * Lock the device if we've been asked to.
655 status = EXIT_LOCK_FAILED;
656 if (lockflag && !privopen && !direct_tty) {
657 if (lock(devnam) < 0)
658 goto fail;
659 locked = 1;
663 * Open the serial device and set it up to be the ppp interface.
664 * First we open it in non-blocking mode so we can set the
665 * various termios flags appropriately. If we aren't dialling
666 * out and we want to use the modem lines, we reopen it later
667 * in order to wait for the carrier detect signal from the modem.
669 hungup = 0;
670 kill_link = 0;
671 connector = doing_callback? callback_script: connect_script;
672 if (direct_tty) {
673 ttyfd = 0;
674 } else if (devnam[0] != '\0') {
675 for (;;) {
676 /* If the user specified the device name, become the
677 user before opening it. */
678 int err;
679 if (!devnam_info.priv && !privopen)
680 (void) seteuid(uid);
681 if ((ttyfd = sys_extra_fd()) < 0)
682 ttyfd = open(devnam, O_NONBLOCK | O_RDWR);
683 err = errno;
684 if (!devnam_info.priv && !privopen)
685 (void) seteuid(0);
686 if (ttyfd >= 0)
687 break;
688 errno = err;
689 if (err != EINTR) {
690 error("Failed to open %s: %m", devnam);
691 status = EXIT_OPEN_FAILED;
693 if (!persist || err != EINTR)
694 goto fail;
696 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
697 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
698 warn("Couldn't reset non-blocking mode on device: %m");
701 * Do the equivalent of `mesg n' to stop broadcast messages.
703 if (fstat(ttyfd, &statbuf) < 0
704 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
705 warn("Couldn't restrict write permissions to %s: %m", devnam);
706 } else
707 tty_mode = statbuf.st_mode;
710 * Set line speed, flow control, etc.
711 * If we have a non-null connection or initializer script,
712 * on most systems we set CLOCAL for now so that we can talk
713 * to the modem before carrier comes up. But this has the
714 * side effect that we might miss it if CD drops before we
715 * get to clear CLOCAL below. On systems where we can talk
716 * successfully to the modem with CLOCAL clear and CD down,
717 * we could clear CLOCAL at this point.
719 set_up_tty(ttyfd, ((connector != NULL && connector[0] != '\0')
720 || initializer != NULL));
721 real_ttyfd = ttyfd;
725 * If the pty, socket, notty and/or record option was specified,
726 * start up the character shunt now.
728 status = EXIT_PTYCMD_FAILED;
729 if (ptycommand != NULL) {
730 if (record_file != NULL) {
731 int ipipe[2], opipe[2], ok;
733 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
734 fatal("Couldn't create pipes for record option: %m");
735 dbglog("starting charshunt for pty option");
736 ok = device_script(ptycommand, opipe[0], ipipe[1], 1,
737 "record") == 0 && start_charshunt(ipipe[0], opipe[1]);
738 (void) close(ipipe[0]);
739 (void) close(ipipe[1]);
740 (void) close(opipe[0]);
741 (void) close(opipe[1]);
742 if (!ok)
743 goto fail;
744 } else {
745 if (device_script(ptycommand, pty_master, pty_master, 1,
746 "pty") < 0)
747 goto fail;
748 ttyfd = pty_slave;
749 (void) close(pty_master);
750 pty_master = -1;
752 } else if (pty_socket != NULL) {
753 int fd = open_socket(pty_socket);
754 if (fd < 0)
755 goto fail;
756 dbglog("starting charshunt for socket option");
757 if (!start_charshunt(fd, fd))
758 goto fail;
759 } else if (notty) {
760 dbglog("starting charshunt for notty option");
761 if (!start_charshunt(0, 1))
762 goto fail;
763 } else if (record_file != NULL) {
764 dbglog("starting charshunt for record option");
765 if (!start_charshunt(ttyfd, ttyfd))
766 goto fail;
769 /* run connection script */
770 if (((connector != NULL) && (connector[0] != '\0')) || initializer) {
771 if (real_ttyfd != -1) {
772 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
773 if (!default_device && modem && !direct_tty) {
774 setdtr(real_ttyfd, 0); /* in case modem is off hook */
775 (void) sleep(1);
776 setdtr(real_ttyfd, 1);
780 if ((initializer != NULL) && (initializer[0] != '\0')) {
781 if (device_script(initializer, ttyfd, ttyfd, 0, "init") < 0) {
782 error("Initializer script failed");
783 status = EXIT_INIT_FAILED;
784 goto fail;
786 if (kill_link)
787 goto disconnect;
789 info("Serial port initialized.");
792 if ((connector != NULL) && (connector[0] != '\0')) {
793 if (device_script(connector, ttyfd, ttyfd, 0, "connect") < 0) {
794 error("Connect script failed");
795 status = EXIT_CONNECT_FAILED;
796 goto fail;
798 if (kill_link)
799 goto disconnect;
801 info("Serial connection established.");
805 * Clear CLOCAL if modem option -- we now have carrier
806 * established, and we should respect loss of carrier.
808 if (real_ttyfd != -1)
809 set_up_tty(real_ttyfd, 0);
811 if (doing_callback == CALLBACK_DIALIN)
812 connector = NULL;
815 /* reopen tty if necessary to wait for carrier */
816 if (connector == NULL && modem && devnam[0] != '\0' && !direct_tty) {
817 for (;;) {
818 if ((i = open(devnam, O_RDWR)) >= 0)
819 break;
820 if (errno != EINTR) {
821 error("Failed to reopen %s: %m", devnam);
822 status = EXIT_OPEN_FAILED;
824 if (!persist || errno != EINTR || hungup || kill_link)
825 goto fail;
827 (void) close(i);
830 (void) slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
831 script_setenv("SPEED", numbuf, 0);
833 /* run welcome script, if any */
834 if ((welcomer != NULL) && (welcomer[0] != '\0')) {
835 if (device_script(welcomer, ttyfd, ttyfd, 0, "welcome") < 0)
836 warn("Welcome script failed");
839 /* set up the serial device as a ppp interface */
840 #ifdef HAVE_MULTILINK
841 (void) tdb_writelock(pppdb);
842 #endif
843 fd_ppp = establish_ppp(ttyfd);
844 if (fd_ppp < 0) {
845 #ifdef HAVE_MULTILINK
846 (void) tdb_writeunlock(pppdb);
847 #endif
848 status = EXIT_FATAL_ERROR;
849 goto disconnect;
852 if (!demand && ifunit >= 0)
853 set_ifunit(1);
854 #ifdef HAVE_MULTILINK
855 (void) tdb_writeunlock(pppdb);
856 #endif
859 * Start opening the connection and wait for
860 * incoming events (reply, timeout, etc.).
862 notice("Connect: %s <--> %s", ifname, ppp_devnam);
863 (void) gettimeofday(&start_time, NULL);
864 link_stats_valid = 0;
865 script_unsetenv("CONNECT_TIME");
866 script_unsetenv("BYTES_SENT");
867 script_unsetenv("BYTES_RCVD");
868 lcp_lowerup(0);
870 /* Mostly for accounting purposes */
871 new_phase(PHASE_CONNECTED);
874 * If we are initiating this connection, wait for a short
875 * time for something from the peer. This can avoid bouncing
876 * our packets off its tty before it has set up the tty.
878 add_fd(fd_ppp);
879 if (connect_delay != 0 && (connector != NULL || ptycommand != NULL)) {
880 struct timeval t;
881 t.tv_sec = connect_delay / 1000;
882 t.tv_usec = connect_delay % 1000;
883 wait_input(&t);
886 lcp_open(0); /* Start protocol */
887 open_ccp_flag = 0;
888 status = EXIT_NEGOTIATION_FAILED;
889 new_phase(PHASE_ESTABLISH);
890 while (phase != PHASE_DEAD) {
891 if (sigsetjmp(sigjmp, 1) == 0) {
892 (void) sigprocmask(SIG_BLOCK, &main_sigmask, NULL);
893 if (kill_link || open_ccp_flag || got_sigchld) {
894 (void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
895 } else {
896 waiting = 1;
897 (void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
898 wait_input(timeleft(&timo));
901 waiting = 0;
902 calltimeout();
903 get_input();
904 if (kill_link) {
905 lcp_close(0, "User request");
906 kill_link = 0;
908 if (open_ccp_flag) {
909 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
910 /* Uncloak ourselves. */
911 ccp_fsm[0].flags &= ~OPT_SILENT;
912 (*ccp_protent.open)(0);
914 open_ccp_flag = 0;
916 if (got_sigchld)
917 (void) reap_kids(0); /* Don't leave dead kids lying around */
921 * Print connect time and statistics.
923 if (link_stats_valid) {
924 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
925 info("Connect time %d.%d minutes.", t/10, t%10);
926 info("Sent %" PPP_COUNTER_F " bytes (%" PPP_COUNTER_F
927 " packets), received %" PPP_COUNTER_F " bytes (%" PPP_COUNTER_F
928 " packets).",
929 link_stats.bytes_out, link_stats.pkts_out,
930 link_stats.bytes_in, link_stats.pkts_in);
934 * Delete pid file before disestablishing ppp. Otherwise it
935 * can happen that another pppd gets the same unit and then
936 * we delete its pid file.
938 if (!demand) {
939 if (pidfilename[0] != '\0'
940 && unlink(pidfilename) < 0 && errno != ENOENT)
941 warn("unable to delete pid file %s: %m", pidfilename);
942 pidfilename[0] = '\0';
946 * If we may want to bring the link up again, transfer
947 * the ppp unit back to the loopback. Set the
948 * real serial device back to its normal mode of operation.
950 remove_fd(fd_ppp);
951 clean_check();
952 if (demand)
953 restore_loop();
954 disestablish_ppp(ttyfd);
955 fd_ppp = -1;
956 if (!hungup)
957 lcp_lowerdown(0);
958 if (!demand)
959 script_unsetenv("IFNAME");
962 * Run disconnector script, if requested.
963 * XXX we may not be able to do this if the line has hung up!
965 disconnect:
966 if ((disconnect_script != NULL) && (disconnect_script[0] != '\0') &&
967 !hungup) {
968 new_phase(PHASE_DISCONNECT);
969 if (real_ttyfd >= 0)
970 set_up_tty(real_ttyfd, 1);
971 if (device_script(disconnect_script, ttyfd, ttyfd, 0,
972 "disconnect") < 0) {
973 warn("disconnect script failed");
974 } else {
975 info("Serial link disconnected.");
979 fail:
980 if (pty_master >= 0)
981 (void) close(pty_master);
982 if (pty_slave >= 0) {
983 (void) close(pty_slave);
984 pty_slave = -1;
986 if (real_ttyfd >= 0)
987 close_tty();
988 if (locked) {
989 locked = 0;
990 unlock();
993 if (!demand) {
994 if (pidfilename[0] != '\0'
995 && unlink(pidfilename) < 0 && errno != ENOENT)
996 warn("unable to delete pid file %s: %m", pidfilename);
997 pidfilename[0] = '\0';
1000 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
1001 break;
1003 kill_link = 0;
1004 if (demand)
1005 demand_discard();
1006 t = need_holdoff? holdoff: 0;
1007 if (holdoff_hook != NULL)
1008 t = (*holdoff_hook)();
1009 if (t > 0) {
1010 new_phase(PHASE_HOLDOFF);
1011 TIMEOUT(holdoff_end, NULL, t);
1012 do {
1013 if (sigsetjmp(sigjmp, 1) == 0) {
1014 (void) sigprocmask(SIG_BLOCK, &main_sigmask, NULL);
1015 if (kill_link || got_sigchld) {
1016 (void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
1017 } else {
1018 waiting = 1;
1019 (void) sigprocmask(SIG_UNBLOCK, &main_sigmask, NULL);
1020 wait_input(timeleft(&timo));
1023 waiting = 0;
1024 calltimeout();
1025 if (kill_link) {
1026 kill_link = 0;
1027 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
1029 if (got_sigchld)
1030 (void) reap_kids(0);
1031 } while (phase == PHASE_HOLDOFF);
1032 if (!persist)
1033 break;
1037 /* Wait for scripts to finish */
1038 final_reap();
1040 die(status);
1041 return (0);
1045 * setup_signals - initialize signal handling.
1047 static void
1048 setup_signals()
1050 struct sigaction sa;
1053 * Compute mask of all interesting signals and install signal handlers
1054 * for each. Only one signal handler may be active at a time. Therefore,
1055 * all other signals should be masked when any handler is executing.
1057 (void) sigemptyset(&main_sigmask);
1058 (void) sigaddset(&main_sigmask, SIGHUP);
1059 (void) sigaddset(&main_sigmask, SIGINT);
1060 (void) sigaddset(&main_sigmask, SIGTERM);
1061 (void) sigaddset(&main_sigmask, SIGCHLD);
1062 (void) sigaddset(&main_sigmask, SIGUSR2);
1064 #define SIGNAL(s, handler) if (1) { \
1065 sa.sa_handler = handler; \
1066 if (sigaction(s, &sa, NULL) < 0) \
1067 fatal("Couldn't establish signal handler (%d): %m", s); \
1068 } else ((void)0)
1070 sa.sa_mask = main_sigmask;
1071 sa.sa_flags = 0;
1072 /*CONSTANTCONDITION*/ SIGNAL(SIGHUP, hup); /* Hangup */
1073 /*CONSTANTCONDITION*/ SIGNAL(SIGINT, term); /* Interrupt */
1074 /*CONSTANTCONDITION*/ SIGNAL(SIGTERM, term); /* Terminate */
1075 /*CONSTANTCONDITION*/ SIGNAL(SIGCHLD, chld);
1077 /*CONSTANTCONDITION*/ SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
1078 /*CONSTANTCONDITION*/ SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
1081 * Install a handler for other signals which would otherwise
1082 * cause pppd to exit without cleaning up.
1084 /*CONSTANTCONDITION*/ SIGNAL(SIGALRM, bad_signal);
1085 /*CONSTANTCONDITION*/ SIGNAL(SIGQUIT, bad_signal);
1087 /* Do not hook any of these signals on Solaris; allow core dump instead */
1088 #ifndef SOL2
1089 /*CONSTANTCONDITION*/ SIGNAL(SIGABRT, bad_signal);
1090 /*CONSTANTCONDITION*/ SIGNAL(SIGFPE, bad_signal);
1091 /*CONSTANTCONDITION*/ SIGNAL(SIGILL, bad_signal);
1092 #ifndef DEBUG
1093 /*CONSTANTCONDITION*/ SIGNAL(SIGSEGV, bad_signal);
1094 #endif
1095 #ifdef SIGBUS
1096 /*CONSTANTCONDITION*/ SIGNAL(SIGBUS, bad_signal);
1097 #endif
1098 #ifdef SIGEMT
1099 /*CONSTANTCONDITION*/ SIGNAL(SIGEMT, bad_signal);
1100 #endif
1101 #ifdef SIGPOLL
1102 /*CONSTANTCONDITION*/ SIGNAL(SIGPOLL, bad_signal);
1103 #endif
1104 #ifdef SIGPROF
1105 /*CONSTANTCONDITION*/ SIGNAL(SIGPROF, bad_signal);
1106 #endif
1107 #ifdef SIGSYS
1108 /*CONSTANTCONDITION*/ SIGNAL(SIGSYS, bad_signal);
1109 #endif
1110 #ifdef SIGTRAP
1111 /*CONSTANTCONDITION*/ SIGNAL(SIGTRAP, bad_signal);
1112 #endif
1113 #ifdef SIGVTALRM
1114 /*CONSTANTCONDITION*/ SIGNAL(SIGVTALRM, bad_signal);
1115 #endif
1116 #ifdef SIGXCPU
1117 /*CONSTANTCONDITION*/ SIGNAL(SIGXCPU, bad_signal);
1118 #endif
1119 #ifdef SIGXFSZ
1120 /*CONSTANTCONDITION*/ SIGNAL(SIGXFSZ, bad_signal);
1121 #endif
1122 #endif
1125 * Apparently we can get a SIGPIPE when we call syslog, if
1126 * syslogd has died and been restarted. Ignoring it seems
1127 * be sufficient.
1129 (void) signal(SIGPIPE, SIG_IGN);
1133 * set_ifunit - do things we need to do once we know which ppp
1134 * unit we are using.
1136 void
1137 set_ifunit(iskey)
1138 int iskey;
1140 sys_ifname();
1141 info("Using interface %s", ifname);
1142 script_setenv("IFNAME", ifname, iskey);
1143 if (iskey) {
1144 create_pidfile(); /* write pid to file */
1145 create_linkpidfile();
1150 * detach - detach us from the controlling terminal.
1152 void
1153 detach()
1155 pid_t pid;
1156 char numbuf[16];
1158 if (detached)
1159 return;
1160 if ((pid = fork()) == (pid_t)-1) {
1161 error("Couldn't detach (fork failed: %m)");
1162 die(1); /* or just return? */
1164 if (pid != (pid_t)0) {
1165 /* parent */
1166 if (locked)
1167 (void) relock(pid);
1168 exit(0); /* parent dies */
1170 (void) setsid();
1172 * Fork again to relinquish session leadership. This is needed
1173 * to prevent the daemon from acquiring controlling terminal.
1175 if ((pid = fork()) == (pid_t)-1) {
1176 error("Couldn't detach (second fork failed: %m)");
1177 die(1); /* or just return? */
1179 if (pid != (pid_t)0) {
1180 /* parent */
1181 if (locked)
1182 (void) relock(pid);
1183 exit(0); /* parent dies */
1185 (void) chdir("/");
1186 (void) close(0);
1187 (void) close(1);
1188 (void) close(2);
1189 detached = 1;
1190 if (!log_to_file && !log_to_specific_fd)
1191 log_to_fd = -1;
1192 /* update pid files if they have been written already */
1193 if (pidfilename[0] != '\0')
1194 create_pidfile();
1195 if (linkpidfile[0] != '\0')
1196 create_linkpidfile();
1197 (void) slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1198 script_setenv("PPPD_PID", numbuf, 1);
1202 * reopen_log - (re)open our connection to syslog.
1204 void
1205 reopen_log()
1207 #ifdef ULTRIX
1208 openlog("pppd", LOG_PID);
1209 #else
1210 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1211 (void) setlogmask(LOG_UPTO(LOG_INFO));
1212 #endif
1216 * Create a file containing our process ID.
1218 static void
1219 create_pidfile()
1221 FILE *pidfile;
1223 (void) slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1224 _PATH_VARRUN, ifname);
1225 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1226 (void) fprintf(pidfile, "%u\n", (unsigned)getpid());
1227 (void) fclose(pidfile);
1228 } else {
1229 error("Failed to create pid file %s: %m", pidfilename);
1230 pidfilename[0] = '\0';
1234 static void
1235 create_linkpidfile()
1237 FILE *pidfile;
1239 if (linkname[0] == '\0')
1240 return;
1241 script_setenv("LINKNAME", linkname, 1);
1242 (void) slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1243 _PATH_VARRUN, linkname);
1244 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1245 (void) fprintf(pidfile, "%u\n", (unsigned)getpid());
1246 if (ifname[0] != '\0')
1247 (void) fprintf(pidfile, "%s\n", ifname);
1248 (void) fclose(pidfile);
1249 } else {
1250 error("Failed to create pid file %s: %m", linkpidfile);
1251 linkpidfile[0] = '\0';
1256 * holdoff_end - called via a timeout when the holdoff period ends.
1258 /*ARGSUSED*/
1259 static void
1260 holdoff_end(arg)
1261 void *arg;
1263 new_phase(PHASE_DORMANT);
1266 /* List of protocol names, to make our messages a little more informative. */
1267 struct protocol_list {
1268 u_short proto;
1269 const char *name;
1270 } protocol_list[] = {
1271 { 0x21, "IP" },
1272 { 0x23, "OSI Network Layer" },
1273 { 0x25, "Xerox NS IDP" },
1274 { 0x27, "DECnet Phase IV" },
1275 { 0x29, "Appletalk" },
1276 { 0x2b, "Novell IPX" },
1277 { 0x2d, "VJ compressed TCP/IP" },
1278 { 0x2f, "VJ uncompressed TCP/IP" },
1279 { 0x31, "Bridging PDU" },
1280 { 0x33, "Stream Protocol ST-II" },
1281 { 0x35, "Banyan Vines" },
1282 { 0x37, "Old VJ compressed TCP/IP" },
1283 { 0x39, "AppleTalk EDDP" },
1284 { 0x3b, "AppleTalk SmartBuffered" },
1285 { 0x3d, "Multilink" },
1286 { 0x3f, "NetBIOS Frame" },
1287 { 0x41, "Cisco LAN Extension" },
1288 { 0x43, "Ascom Timeplex" },
1289 { 0x45, "Fujitsu Link Backup and Load Balancing (LBLB)" },
1290 { 0x47, "DCA Remote Lan" },
1291 { 0x49, "Serial Data Transport Protocol (PPP-SDTP)" },
1292 { 0x4b, "SNA over 802.2" },
1293 { 0x4d, "SNA" },
1294 { 0x4f, "IP6 Header Compression" },
1295 { 0x51, "KNX Bridging" },
1296 { 0x53, "Encrypted" },
1297 { 0x55, "per-link encrypted" },
1298 { 0x57, "IPv6" },
1299 { 0x59, "PPP Muxing" },
1300 { 0x6f, "Stampede Bridging" },
1301 { 0x73, "MP+" },
1302 { 0xc1, "STMF" },
1303 { 0xfb, "per-link compressed" },
1304 { 0xfd, "compressed datagram" },
1305 { 0x0201, "802.1d Hello Packets" },
1306 { 0x0203, "IBM Source Routing BPDU" },
1307 { 0x0205, "DEC LANBridge100 Spanning Tree" },
1308 { 0x0207, "Cisco Discovery Protocol" },
1309 { 0x0231, "Luxcom" },
1310 { 0x0233, "Sigma Network Systems" },
1311 { 0x0235, "Apple Client Server Protocol" },
1312 { 0x0281, "MPLS Unicast" },
1313 { 0x0283, "MPLS Multicast" },
1314 { 0x0285, "IEEE p1284.4" },
1315 { 0x0287, "ETSI TETRA TNP1" },
1316 { 0x4021, "Stacker LZS" },
1317 { 0x8021, "Internet Protocol Control Protocol" },
1318 { 0x8023, "OSI Network Layer Control Protocol" },
1319 { 0x8025, "Xerox NS IDP Control Protocol" },
1320 { 0x8027, "DECnet Phase IV Control Protocol" },
1321 { 0x8029, "Appletalk Control Protocol" },
1322 { 0x802b, "Novell IPX Control Protocol" },
1323 { 0x8031, "Bridging Control Protocol" },
1324 { 0x8033, "Stream Protocol Control Protocol" },
1325 { 0x8035, "Banyan Vines Control Protocol" },
1326 { 0x803f, "NetBIOS Frames Control Protocol" },
1327 { 0x8041, "Cisco LAN Extension Control Protocol" },
1328 { 0x8043, "Ascom Timeplex Control Protocol" },
1329 { 0x8045, "Fujitsu LBLB Control Protocol" },
1330 { 0x8047, "DCA Remote Lan Network Control Protocol (RLNCP)" },
1331 { 0x8049, "Serial Data Control Protocol (PPP-SDCP)" },
1332 { 0x804b, "SNA over 802.2 Control Protocol" },
1333 { 0x804d, "SNA Control Protocol" },
1334 { 0x8051, "KNX Bridging Control Protocol" },
1335 { 0x8053, "Encryption Control Protocol" },
1336 { 0x8055, "Per-link Encryption Control Protocol" },
1337 { 0x8057, "IPv6 Control Protocol" },
1338 { 0x806f, "Stampede Bridging Control Protocol" },
1339 { 0x80c1, "STMF Control Protocol" },
1340 { 0x80fb, "Per-link Compression Control Protocol" },
1341 { 0x80fd, "Compression Control Protocol" },
1342 { 0x8207, "Cisco Discovery Control Protocol" },
1343 { 0x8235, "Apple Client Server Control Protocol" },
1344 { 0x8281, "MPLS Control Protocol" },
1345 { 0x8287, "ETSI TETRA TNP1 Control Protocol" },
1346 { 0xc021, "Link Control Protocol" },
1347 { 0xc023, "Password Authentication Protocol" },
1348 { 0xc025, "Link Quality Report" },
1349 { 0xc027, "Shiva Password Authentication Protocol" },
1350 { 0xc029, "CallBack Control Protocol (CBCP)" },
1351 { 0xc02b, "Bandwidth Allocation Control Protocol" },
1352 { 0xc02d, "BAP" },
1353 { 0xc081, "Container Control Protocol" },
1354 { 0xc223, "Challenge Handshake Authentication Protocol" },
1355 { 0xc227, "Extensible Authentication Protocol" },
1356 { 0xc281, "Funk Proprietary Authentication Protocol" },
1357 { 0, NULL },
1361 * protocol_name - find a name for a PPP protocol.
1363 const char *
1364 protocol_name(proto)
1365 int proto;
1367 struct protocol_list *lp;
1369 for (lp = protocol_list; lp->proto != 0; ++lp)
1370 if (proto == lp->proto)
1371 return (lp->name);
1372 return (NULL);
1375 static const char *phase_names[] = { PHASE__NAMES };
1377 const char *
1378 phase_name(pval)
1379 int pval;
1381 static char buf[32];
1383 if (pval < 0 || pval >= Dim(phase_names)) {
1384 (void) slprintf(buf, sizeof (buf), "unknown %d", pval);
1385 return ((const char *)buf);
1387 return (phase_names[pval]);
1391 * get_input - called when incoming data is available.
1393 static void
1394 get_input()
1396 int len, i;
1397 u_char *p;
1398 u_short protocol;
1399 struct protent *protp;
1400 const char *pname;
1402 p = inpacket_buf; /* point to beginning of packet buffer */
1404 len = read_packet(inpacket_buf);
1405 if (len < 0)
1406 return;
1408 if (len == 0) {
1409 notice("Modem hangup");
1410 hungup = 1;
1411 status = EXIT_HANGUP;
1412 lcp_lowerdown(0); /* serial link is no longer available */
1413 link_terminated(0);
1414 return;
1417 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1418 dbglog("rcvd %P", p, len);
1420 if (len < PPP_HDRLEN) {
1421 dbglog("Discarded short packet (%d < %d)", len, PPP_HDRLEN);
1422 return;
1425 p += 2; /* Skip address and control */
1426 GETSHORT(protocol, p);
1427 len -= PPP_HDRLEN;
1429 pname = debug ? NULL : protocol_name(protocol);
1432 * Toss all non-LCP packets unless LCP is in Opened state and
1433 * discard non-authentication protocols if we're not yet
1434 * authenticated.
1436 if ((protocol != PPP_LCP &&
1437 (phase < PHASE_AUTHENTICATE || phase > PHASE_RUNNING)) ||
1438 (phase <= PHASE_AUTHENTICATE &&
1439 !(protocol == PPP_LCP || protocol == PPP_LQR ||
1440 protocol == PPP_PAP || protocol == PPP_CHAP))) {
1441 if (pname == NULL)
1442 dbglog("Discarded proto 0x%x in %s phase",
1443 protocol, phase_name(phase));
1444 else
1445 dbglog("Discarded %s (0x%x) in %s phase",
1446 pname, protocol, phase_name(phase));
1447 return;
1451 * Upcall the proper protocol input routine.
1453 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1454 if (protp->protocol == protocol && protp->enabled_flag) {
1455 (*protp->input)(0, p, len);
1456 return;
1458 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1459 && protp->datainput != NULL) {
1460 (*protp->datainput)(0, p, len);
1461 return;
1465 if (debug) {
1466 if (pname != NULL)
1467 warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1468 else
1469 warn("Unsupported protocol 0x%x received", protocol);
1471 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1475 * new_phase - signal the start of a new phase of pppd's operation.
1477 void
1478 new_phase(p)
1479 int p;
1481 if (new_phase_hook != NULL)
1482 (*new_phase_hook)(p, phase);
1483 phase = p;
1487 * die - clean up state and exit with the specified status.
1489 void
1490 die(status)
1491 int status;
1493 cleanup();
1494 if (phase != PHASE_EXIT) {
1495 syslog(LOG_INFO, "Exit.");
1496 new_phase(PHASE_EXIT);
1498 exit(status);
1502 * cleanup - restore anything which needs to be restored before we exit
1504 static void
1505 cleanup()
1507 sys_cleanup(); /* XXX: Need to check if this is okay after close_tty */
1509 if (fd_ppp >= 0) {
1510 fd_ppp = -1;
1511 disestablish_ppp(ttyfd);
1513 if (real_ttyfd >= 0)
1514 close_tty();
1516 if (pidfilename[0] != '\0' && unlink(pidfilename) < 0 && errno != ENOENT)
1517 warn("unable to delete pid file %s: %m", pidfilename);
1518 pidfilename[0] = '\0';
1519 if (linkpidfile[0] != '\0' && unlink(linkpidfile) < 0 && errno != ENOENT)
1520 warn("unable to delete pid file %s: %m", linkpidfile);
1521 linkpidfile[0] = '\0';
1523 if (locked) {
1524 locked = 0;
1525 unlock();
1528 #ifdef HAVE_MULTILINK
1529 if (pppdb != NULL) {
1530 cleanup_db();
1531 pppdb = NULL;
1533 #endif
1537 * close_tty - restore the terminal device and close it.
1539 static void
1540 close_tty()
1542 int fd = real_ttyfd;
1544 real_ttyfd = -1;
1546 /* drop dtr to hang up */
1547 if (!default_device && modem) {
1548 setdtr(fd, 0);
1550 * This sleep is in case the serial port has CLOCAL set by default,
1551 * and consequently will reassert DTR when we close the device.
1553 (void) sleep(1);
1556 restore_tty(fd);
1558 if (tty_mode != (mode_t) -1) {
1559 if (fchmod(fd, tty_mode) != 0) {
1560 /* XXX if devnam is a symlink, this will change the link */
1561 if (chmod(devnam, tty_mode) != 0) {
1562 error("Unable to chmod file %s: %m", devnam);
1567 (void) close(fd);
1571 * update_link_stats - get stats at link termination.
1573 void
1574 update_link_stats(u)
1575 int u;
1577 struct timeval now;
1578 char numbuf[32];
1580 if (gettimeofday(&now, NULL) >= 0) {
1581 link_connect_time = now.tv_sec - start_time.tv_sec;
1582 (void) slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1583 script_setenv("CONNECT_TIME", numbuf, 0);
1584 } else {
1585 link_connect_time = 0;
1588 if (get_ppp_stats(u, &link_stats)) {
1589 (void) slprintf(numbuf, sizeof(numbuf), "%" PPP_COUNTER_F,
1590 link_stats.bytes_out);
1591 script_setenv("BYTES_SENT", numbuf, 0);
1592 (void) slprintf(numbuf, sizeof(numbuf), "%" PPP_COUNTER_F,
1593 link_stats.bytes_in);
1594 script_setenv("BYTES_RCVD", numbuf, 0);
1595 (void) slprintf(numbuf, sizeof(numbuf), "%" PPP_COUNTER_F,
1596 link_stats.pkts_in);
1597 script_setenv("PKTS_RCVD", numbuf, 0);
1598 (void) slprintf(numbuf, sizeof(numbuf), "%" PPP_COUNTER_F,
1599 link_stats.pkts_out);
1600 script_setenv("PKTS_SENT", numbuf, 0);
1601 link_stats_valid = 1;
1606 struct callout {
1607 struct timeval c_time; /* time at which to call routine */
1608 void *c_arg; /* argument to routine */
1609 void (*c_func) __P((void *)); /* routine */
1610 struct callout *c_next;
1613 static struct callout *callout = NULL; /* Callout list */
1614 static struct timeval timenow; /* Current time */
1617 * timeout - Schedule a timeout.
1619 * Note that this timeout takes the number of seconds, NOT hz (as in
1620 * the kernel).
1622 void
1623 timeout(func, arg, time)
1624 void (*func) __P((void *));
1625 void *arg;
1626 int time;
1628 struct callout *newp, *p, **pp;
1630 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1633 * Allocate timeout.
1635 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1636 novm("callout structure for timeout.");
1637 newp->c_arg = arg;
1638 newp->c_func = func;
1639 (void) gettimeofday(&timenow, NULL);
1640 newp->c_time.tv_sec = timenow.tv_sec + time;
1641 newp->c_time.tv_usec = timenow.tv_usec;
1644 * Find correct place and link it in.
1646 for (pp = &callout; (p = *pp) != NULL; pp = &p->c_next)
1647 if (newp->c_time.tv_sec < p->c_time.tv_sec
1648 || (newp->c_time.tv_sec == p->c_time.tv_sec
1649 && newp->c_time.tv_usec < p->c_time.tv_usec))
1650 break;
1651 newp->c_next = p;
1652 *pp = newp;
1657 * untimeout - Unschedule a timeout.
1659 void
1660 untimeout(func, arg)
1661 void (*func) __P((void *));
1662 void *arg;
1664 struct callout **copp, *freep;
1666 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1669 * Find first matching timeout and remove it from the list.
1671 for (copp = &callout; (freep = *copp) != NULL; copp = &freep->c_next)
1672 if (freep->c_func == func && freep->c_arg == arg) {
1673 *copp = freep->c_next;
1674 free((char *) freep);
1675 break;
1681 * calltimeout - Call any timeout routines which are now due.
1683 static void
1684 calltimeout()
1686 struct callout *p;
1688 while (callout != NULL) {
1689 p = callout;
1691 if (gettimeofday(&timenow, NULL) < 0)
1692 fatal("Failed to get time of day: %m");
1693 if (!(p->c_time.tv_sec < timenow.tv_sec
1694 || (p->c_time.tv_sec == timenow.tv_sec
1695 && p->c_time.tv_usec <= timenow.tv_usec)))
1696 break; /* no, it's not time yet */
1698 callout = p->c_next;
1699 (*p->c_func)(p->c_arg);
1701 free((char *) p);
1707 * timeleft - return the length of time until the next timeout is due.
1709 static struct timeval *
1710 timeleft(tvp)
1711 struct timeval *tvp;
1713 if (callout == NULL)
1714 return (NULL);
1716 (void) gettimeofday(&timenow, NULL);
1717 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1718 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1719 if (tvp->tv_usec < 0) {
1720 tvp->tv_usec += 1000000;
1721 tvp->tv_sec -= 1;
1723 if (tvp->tv_sec < 0)
1724 tvp->tv_sec = tvp->tv_usec = 0;
1726 return (tvp);
1731 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1733 static void
1734 kill_my_pg(sig)
1735 int sig;
1737 struct sigaction act, oldact;
1738 sigset_t mask;
1740 BZERO(&act, sizeof (act));
1741 act.sa_handler = SIG_IGN;
1742 (void) sigemptyset(&mask);
1743 (void) sigaddset(&mask, sig);
1745 * Ignore signal 'sig' temporarily, before finally re-activating the
1746 * original handler. We need to do it in the following sequence, since
1747 * otherwise the signal handler for 'sig' will be called forever.
1749 if (sigaction(sig, &act, &oldact) < 0) {
1750 fatal("kill_my_pg: couldn't establish signal handler (%d): %m", sig);
1752 (void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
1754 * Send signal 'sig' to all processes whose process group ID is equal
1755 * to the process group ID of the sender.
1757 (void) kill(0, sig);
1758 if (sigaction(sig, &oldact, NULL) < 0) {
1759 fatal("kill_my_pg: couldn't establish signal handler (%d): %m", sig);
1765 * hup - Catch SIGHUP signal.
1767 * Indicates that the physical layer has been disconnected.
1768 * We don't rely on this indication; if the user has sent this
1769 * signal, we just take the link down.
1771 static void
1772 hup(sig)
1773 int sig;
1775 info("Hangup (SIGHUP)");
1776 kill_link = 1;
1777 if (status != EXIT_HANGUP)
1778 status = EXIT_USER_REQUEST;
1779 if (conn_running > 0)
1780 /* Send the signal to the [dis]connector process(es) also */
1781 kill_my_pg(sig);
1782 if (charshunt_pid)
1783 (void) kill(charshunt_pid, sig);
1784 if (waiting)
1785 siglongjmp(sigjmp, 1);
1790 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1792 * Indicates that we should initiate a graceful disconnect and exit.
1794 /*ARGSUSED*/
1795 static void
1796 term(sig)
1797 int sig;
1799 info("Terminating on signal %d.", sig);
1800 persist = 0; /* don't try to restart */
1801 kill_link = 1;
1802 status = EXIT_USER_REQUEST;
1803 if (conn_running > 0)
1804 /* Send the signal to the [dis]connector process(es) also */
1805 kill_my_pg(sig);
1806 if (charshunt_pid)
1807 (void) kill(charshunt_pid, sig);
1808 if (waiting)
1809 siglongjmp(sigjmp, 1);
1814 * chld - Catch SIGCHLD signal.
1815 * Sets a flag so we will call reap_kids in the mainline.
1817 /*ARGSUSED*/
1818 static void
1819 chld(sig)
1820 int sig;
1822 got_sigchld = 1;
1823 if (waiting)
1824 siglongjmp(sigjmp, 1);
1828 * toggle_debug - Catch SIGUSR1 signal.
1830 * Toggle debug flag.
1832 /*ARGSUSED*/
1833 static void
1834 toggle_debug(sig)
1835 int sig;
1837 if (debug) {
1838 print_ncpstate(0, NULL);
1839 dbglog("debug logging disabled");
1840 (void) setlogmask(LOG_UPTO(LOG_WARNING));
1841 debug = 0;
1842 } else {
1843 (void) setlogmask(LOG_UPTO(LOG_DEBUG));
1844 dbglog("debug logging enabled");
1845 print_ncpstate(0, NULL);
1846 debug = 1;
1852 * open_ccp - Catch SIGUSR2 signal.
1854 * Try to (re)negotiate compression.
1856 /*ARGSUSED*/
1857 static void
1858 open_ccp(sig)
1859 int sig;
1861 open_ccp_flag = 1;
1862 if (waiting)
1863 siglongjmp(sigjmp, 1);
1868 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1870 static void
1871 bad_signal(sig)
1872 int sig;
1874 static int crashed = 0;
1876 if (crashed)
1877 _exit(127);
1878 crashed = 1;
1879 error("Fatal signal %d", sig);
1880 if (conn_running > 0)
1881 kill_my_pg(SIGTERM);
1882 if (charshunt_pid)
1883 (void) kill(charshunt_pid, SIGTERM);
1884 die(127);
1889 * device_script - run a program to talk to the serial device
1890 * (e.g. to run the connector or disconnector script).
1892 static int
1893 device_script(program, in, out, dont_wait, optname)
1894 char *program;
1895 int in, out;
1896 int dont_wait;
1897 char *optname;
1899 pid_t pid;
1900 int status = -1;
1901 int errfd;
1902 int envpipe[2];
1904 envpipe[0] = envpipe[1] = -1;
1905 if (!dont_wait && device_pipe_hook != NULL && pipe(envpipe) == -1) {
1906 error("Cannot create pipe for child: %m");
1907 return (-1);
1910 ++conn_running;
1911 pid = fork();
1913 if (pid == (pid_t)-1) {
1914 --conn_running;
1915 error("Failed to create child process: %m");
1916 return (-1);
1919 if (pid == (pid_t)0) {
1920 sys_close();
1921 closelog();
1922 if (envpipe[0] >= 0) {
1923 if (envpipe[1] <= 2)
1924 envpipe[1] = dup(envpipe[1]);
1925 (void) close(envpipe[0]);
1927 if (in == 2) {
1928 /* aargh!!! */
1929 int newin = dup(in);
1930 if (in == out)
1931 out = newin;
1932 in = newin;
1933 } else if (out == 2) {
1934 out = dup(out);
1936 if (log_to_fd >= 0) {
1937 if (log_to_fd != 2) {
1938 if (dup2(log_to_fd, 2) < 0)
1939 error("dup2(log_to_fd, STDERR) failed: %m");
1941 } else {
1942 (void) close(2);
1943 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1944 if (errfd >= 0 && errfd != 2) {
1945 if (dup2(errfd, 2) < 0)
1946 error("dup2(errfd, STDERR) failed: %m");
1947 (void) close(errfd);
1950 if (in != 0) {
1951 if (out == 0)
1952 out = dup(out);
1953 if (dup2(in, 0) < 0)
1954 error("dup2(in, STDIN) failed: %m");
1956 if (out != 1) {
1957 if (dup2(out, 1) < 0)
1958 error("dup2(out, STDOUT) failed: %m");
1960 if (envpipe[0] >= 0 && dup2(envpipe[1], 3) < 0)
1961 error("dup2(pipe, pipeout) failed: %m");
1962 if (real_ttyfd > 2)
1963 (void) close(real_ttyfd);
1964 if (pty_master > 2)
1965 (void) close(pty_master);
1966 if (pty_slave > 2) {
1967 (void) close(pty_slave);
1968 pty_slave = -1;
1970 (void) setuid(uid);
1971 if (getuid() != uid) {
1972 error("setuid failed");
1973 exit(1);
1975 (void) setgid(getgid());
1976 if (script_env != NULL) {
1977 while (*script_env != NULL) {
1978 if (putenv(*script_env) == -1)
1979 warn("unable to set %s for %s: %m", *script_env, program);
1980 script_env++;
1983 (void) execl("/bin/sh", "sh", "-c", program, (char *)0);
1984 error("could not exec /bin/sh: %m");
1985 exit(99);
1986 /* NOTREACHED */
1989 if (debug)
1990 dbglog("%s option: '%s' started (pid %d)", optname, program, pid);
1991 if (dont_wait) {
1992 record_child(pid, program, NULL, NULL);
1993 status = 0;
1994 } else {
1995 if (envpipe[0] >= 0) {
1996 (void) close(envpipe[1]);
1997 (*device_pipe_hook)(envpipe[0]);
1999 while (waitpid(pid, &status, 0) < 0) {
2000 if (errno == EINTR)
2001 continue;
2002 fatal("error waiting for (dis)connection process: %m");
2004 if (envpipe[0] >= 0)
2005 (void) close(envpipe[0]);
2006 --conn_running;
2009 return (status == 0 ? 0 : -1);
2014 * run-program - execute a program with given arguments,
2015 * but don't wait for it.
2016 * If the program can't be executed, logs an error unless
2017 * must_exist is 0 and the program file doesn't exist.
2018 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
2019 * or isn't an executable plain file, or the process ID of the child.
2020 * If done != NULL, (*done)(arg, int) will be called later (within
2021 * reap_kids) if this routine returns value > 0.
2023 pid_t
2024 run_program(prog, args, must_exist, done, arg)
2025 char *prog;
2026 char **args;
2027 int must_exist;
2028 void (*done) __P((void *arg, int status));
2029 void *arg;
2031 pid_t pid;
2032 struct stat sbuf;
2033 int retv;
2036 * First check if the file exists and is executable.
2037 * We don't use access() because that would use the
2038 * real user-id, which might not be root, and the script
2039 * might be accessible only to root.
2041 errno = EINVAL;
2042 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
2043 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
2044 if (must_exist || errno != ENOENT)
2045 warn("Can't execute %s: %m", prog);
2046 return (0);
2049 if (updown_script_hook != NULL) {
2050 retv = (*updown_script_hook)((const char ***)&args);
2051 if (retv == -1) {
2052 return (-1);
2056 pid = fork();
2057 if (pid == (pid_t)-1) {
2058 error("Failed to create child process for %s: %m", prog);
2059 return (-1);
2061 if (pid == (pid_t)0) {
2062 int new_fd;
2064 /* Leave the current location */
2065 (void) setsid(); /* No controlling tty. */
2066 (void) umask (S_IRWXG|S_IRWXO);
2067 (void) chdir ("/"); /* no current directory. */
2068 (void) setuid(0); /* set real UID = root */
2069 (void) setgid(getegid());
2071 /* Ensure that nothing of our device environment is inherited. */
2072 sys_close();
2073 closelog();
2074 (void) close(0);
2075 (void) close(1);
2076 (void) close(2);
2077 (void) close(ttyfd); /* tty interface to the ppp device */
2078 if (real_ttyfd >= 0)
2079 (void) close(real_ttyfd);
2081 /* Don't pass handles to the PPP device, even by accident. */
2082 new_fd = open (_PATH_DEVNULL, O_RDWR);
2083 if (new_fd >= 0) {
2084 if (new_fd != 0) {
2085 if (dup2(new_fd, 0) < 0) /* stdin <- /dev/null */
2086 error("dup2(/dev/null, STDIN) failed: %m");
2087 (void) close(new_fd);
2089 if (dup2(0, 1) < 0) /* stdout -> /dev/null */
2090 error("dup2(/dev/null, STDOUT) failed: %m");
2091 if (dup2(0, 2) < 0) /* stderr -> /dev/null */
2092 error("dup2(/dev/null, STDERR) failed: %m");
2095 #ifdef BSD
2096 /* Force the priority back to zero if pppd is running higher. */
2097 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
2098 warn("can't reset priority to 0: %m");
2099 #endif
2101 /* SysV recommends a second fork at this point. */
2103 /* run the program */
2104 (void) execve(prog, args, script_env);
2105 if (must_exist || errno != ENOENT) {
2106 /* have to reopen the log, there's nowhere else
2107 for the message to go. */
2108 reopen_log();
2109 syslog(LOG_ERR, "Can't execute %s: %m", prog);
2110 closelog();
2112 _exit(-1);
2115 if (debug)
2116 dbglog("Script %s started (pid %d)", prog, pid);
2117 record_child(pid, prog, done, arg);
2119 return (pid);
2124 * record_child - add a child process to the list for reap_kids
2125 * to use.
2127 static void
2128 record_child(pid, prog, done, arg)
2129 pid_t pid;
2130 char *prog;
2131 void (*done) __P((void *, int));
2132 void *arg;
2134 struct subprocess *chp;
2136 ++n_children;
2138 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
2139 if (chp == NULL) {
2140 warn("losing track of %s process", prog);
2141 } else {
2142 chp->pid = pid;
2143 chp->prog = prog;
2144 chp->done = done;
2145 chp->arg = arg;
2146 chp->next = children;
2147 children = chp;
2153 * reap_kids - get status from any dead child processes,
2154 * and log a message for abnormal terminations.
2156 static int
2157 reap_kids(waitfor)
2158 int waitfor;
2160 pid_t pid;
2161 int status, i;
2162 struct subprocess *chp, **prevp;
2164 got_sigchld = 0;
2165 if (n_children == 0)
2166 return (0);
2168 /*CONSTANTCONDITION*/
2169 while (1) {
2170 pid = waitpid(-1, &status, (waitfor ? 0 : WNOHANG));
2171 if (pid == 0) {
2172 break; /* return 0 */
2173 } else if (pid == -1) {
2174 if (errno == EINTR)
2175 continue;
2176 if (errno != ECHILD)
2177 error("Error waiting for child process: %m");
2178 return (-1);
2179 } else {
2180 for (prevp = &children; (chp = *prevp) != NULL;
2181 prevp = &chp->next) {
2182 if (chp->pid == pid) {
2183 --n_children;
2184 *prevp = chp->next;
2185 break;
2188 if (WIFSIGNALED(status) || WIFSTOPPED(status)) {
2189 i = WIFSIGNALED(status) ? WTERMSIG(status) : WSTOPSIG(status);
2190 warn("Child process %s (pid %d) %s with signal %d (%s)",
2191 (chp != NULL ? chp->prog : "??"), pid,
2192 (WIFSIGNALED(status) ? "terminated" : "stopped"),
2193 i, signal_name(i));
2194 } else if (debug) {
2195 dbglog("Child process %s finished (pid %d), status = %d",
2196 (chp != NULL ? chp->prog: "??"), pid,
2197 WEXITSTATUS(status));
2199 if ((chp != NULL) && (chp->done != NULL))
2200 (*chp->done)(chp->arg, status);
2201 if (chp != NULL)
2202 free(chp);
2205 return (0);
2209 * infanticide - timeout while waiting for child process.
2211 /*ARGSUSED*/
2212 static void
2213 infanticide(sig)
2214 int sig;
2216 struct subprocess *chp;
2217 static int runcount = 0;
2219 if (runcount < 2) {
2220 for (chp = children; chp != NULL; chp = chp->next)
2221 (void) kill(chp->pid, runcount == 0 ? SIGTERM : SIGKILL);
2222 } else {
2223 kill_my_pg(SIGTERM);
2224 /* Quit and hope for the best. */
2225 n_children = 0;
2227 runcount++;
2231 * Perform final wait before exiting.
2233 static void
2234 final_reap()
2236 struct sigaction sa;
2237 struct subprocess *chp;
2239 if (n_children > 0 && debug) {
2240 dbglog("Waiting for %d child processes...", n_children);
2241 for (chp = children; chp != NULL; chp = chp->next)
2242 dbglog(" pid %d: %s", chp->pid, chp->prog);
2244 BZERO(&sa, sizeof (sa));
2245 /*CONSTANTCONDITION*/ SIGNAL(SIGALRM, infanticide);
2246 while (n_children > 0) {
2247 (void) alarm(7);
2248 if (reap_kids(1) < 0)
2249 break;
2251 (void) alarm(0);
2255 * novm - log an error message saying we ran out of memory, and die.
2257 void
2258 novm(msg)
2259 char *msg;
2261 fatal("Virtual memory exhausted allocating %s\n", msg);
2265 * script_setenv - set an environment variable value to be used
2266 * for scripts that we run (e.g. ip-up, auth-up, etc.)
2268 void
2269 script_setenv(var, value, iskey)
2270 const char *var;
2271 const char *value;
2272 int iskey;
2274 size_t varl = strlen(var);
2275 size_t vl = varl + strlen(value) + 2;
2276 int i;
2277 char *p, *newstring;
2280 * XXX: Can we assert that a tdb write lock is held here ? It appears that
2281 * Linux's use of tdb is not safe.
2283 newstring = (char *) malloc(vl+1);
2284 if (newstring == NULL) {
2285 novm("script environment string");
2286 return;
2288 *newstring++ = iskey;
2289 (void) slprintf(newstring, vl, "%s=%s", var, value);
2291 /* check if this variable is already set */
2292 if (script_env != NULL) {
2293 for (i = 0; (p = script_env[i]) != NULL; ++i) {
2294 if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
2295 #ifdef HAVE_MULTILINK
2296 if (p[-1] != '\0' && pppdb != NULL)
2297 delete_db_key(p);
2298 #endif
2299 free(p-1);
2300 script_env[i] = newstring;
2301 #ifdef HAVE_MULTILINK
2302 if (iskey && pppdb != NULL)
2303 add_db_key(newstring);
2304 update_db_entry();
2305 #endif
2306 return;
2309 } else {
2310 /* no space allocated for script env. ptrs. yet */
2311 i = 0;
2312 script_env = (char **) malloc(16 * sizeof(char *));
2313 if (script_env == NULL) {
2314 novm("script environment variable.");
2315 return;
2317 s_env_nalloc = 16;
2320 /* reallocate script_env with more space if needed */
2321 if (i + 1 >= s_env_nalloc) {
2322 int new_n = i + 17;
2323 char **newenv = (char **) realloc((void *)script_env,
2324 new_n * sizeof(char *));
2325 if (newenv == NULL) {
2326 novm("expanded script environment variable.");
2327 return;
2329 script_env = newenv;
2330 s_env_nalloc = new_n;
2333 script_env[i] = newstring;
2334 script_env[i+1] = NULL;
2336 #ifdef HAVE_MULTILINK
2337 if (pppdb != NULL) {
2338 if (iskey)
2339 add_db_key(newstring);
2340 update_db_entry();
2342 #endif
2346 * script_unsetenv - remove a variable from the environment
2347 * for scripts.
2349 void
2350 script_unsetenv(var)
2351 const char *var;
2353 int vl = strlen(var);
2354 int i;
2355 char *p;
2358 * XXX: Can we assert that a tdb write lock is held here ? It appears that
2359 * Linux's use of tdb is not safe.
2361 if (script_env == NULL)
2362 return;
2363 for (i = 0; (p = script_env[i]) != NULL; ++i) {
2364 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2365 #ifdef HAVE_MULTILINK
2366 if (p[-1] != '\0' && pppdb != NULL)
2367 delete_db_key(p);
2368 #endif
2369 free(p-1);
2370 while ((script_env[i] = script_env[i+1]) != NULL)
2371 ++i;
2372 break;
2375 #ifdef HAVE_MULTILINK
2376 if ((pppdb != NULL) && (p != NULL))
2377 update_db_entry();
2378 #endif
2382 * script_getenv - find a variable in the script environment.
2384 const char *
2385 script_getenv(var)
2386 const char *var;
2388 int vl = strlen(var);
2389 int i;
2390 char *p;
2392 if (script_env == NULL)
2393 return (NULL);
2394 for (i = 0; (p = script_env[i]) != NULL; ++i) {
2395 if (strncmp(p, var, vl) == 0 && p[vl] == '=')
2396 return ((const char *)p+vl+1);
2398 return (NULL);
2401 #ifdef HAVE_MULTILINK
2403 * update_db_entry - update our entry in the database.
2405 static void
2406 update_db_entry()
2408 TDB_DATA key, dbuf;
2409 int vlen, i;
2410 char *p, *q, *vbuf;
2412 if (script_env == NULL)
2413 return;
2415 * vlen needs to be initialized as 1, or otherwise, the last string
2416 * is truncated by slprintf.
2418 vlen = 1;
2419 for (i = 0; (p = script_env[i]) != NULL; ++i)
2420 vlen += strlen(p) + 1;
2421 vbuf = malloc(vlen);
2422 if (vbuf == NULL)
2423 novm("database entry");
2424 q = vbuf;
2425 for (i = 0; (p = script_env[i]) != NULL; ++i)
2426 q += slprintf(q, vbuf + vlen - q, "%s;", p);
2428 key.dptr = db_key;
2429 key.dsize = strlen(db_key);
2430 dbuf.dptr = vbuf;
2431 dbuf.dsize = vlen;
2432 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2433 error("tdb_store failed: %s", tdb_error(pppdb));
2437 * add_db_key - add a key that we can use to look up our database entry.
2439 static void
2440 add_db_key(str)
2441 const char *str;
2443 TDB_DATA key, dbuf;
2445 key.dptr = (char *) str;
2446 key.dsize = strlen(str);
2447 dbuf.dptr = db_key;
2448 dbuf.dsize = strlen(db_key);
2449 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2450 error("tdb_store key failed: %s", tdb_error(pppdb));
2454 * delete_db_key - delete a key for looking up our database entry.
2456 static void
2457 delete_db_key(str)
2458 const char *str;
2460 TDB_DATA key;
2462 key.dptr = (char *) str;
2463 key.dsize = strlen(str);
2464 (void) tdb_delete(pppdb, key);
2468 * cleanup_db - delete all the entries we put in the database.
2470 static void
2471 cleanup_db()
2473 TDB_DATA key;
2474 int i;
2475 char *p;
2477 key.dptr = db_key;
2478 key.dsize = strlen(db_key);
2479 (void) tdb_delete(pppdb, key);
2480 for (i = 0; (p = script_env[i]) != NULL; ++i)
2481 if (p[-1] != '\0')
2482 delete_db_key(p);
2484 #endif /* HAVE_MULTILINK */
2487 * open_socket - establish a stream socket connection to the nominated
2488 * host and port.
2489 * XXX: Need IPv6 support for those systems that support it (use getaddrinfo),
2490 * but requires portability changes.
2492 static int
2493 open_socket(dest)
2494 char *dest;
2496 char *sep, *endp = NULL;
2497 int sock;
2498 int port = -1;
2499 u_int32_t host;
2500 struct hostent *hent = NULL;
2501 struct sockaddr_in sad;
2502 struct servent *se;
2504 /* parse host:port and resolve host to an IP address */
2505 sep = strchr(dest, ':');
2506 if (sep != NULL) {
2507 se = getservbyname((const char *)sep+1, "tcp");
2508 if (se != NULL) {
2509 port = ntohs(se->s_port);
2510 } else {
2511 port = strtol(sep+1, &endp, 10);
2512 if (endp == sep+1 || *endp != '\0') {
2513 error("Can't parse host:port for socket destination");
2514 return (-1);
2518 if (port < 0 || port > 65535 || sep == dest) {
2519 error("Can't parse host:port for socket destination");
2520 return (-1);
2522 *sep = '\0';
2523 host = inet_addr(dest);
2524 if (host == (u_int32_t) -1) {
2525 hent = gethostbyname(dest);
2526 if (hent == NULL) {
2527 error("%s: unknown host in socket option", dest);
2528 *sep = ':';
2529 return (-1);
2531 BCOPY(hent->h_addr_list[0], &host, sizeof(host));
2532 hent->h_addr_list++;
2534 *sep = ':';
2536 for (;;) {
2537 /* get a socket and connect it to the other end */
2538 sock = socket(PF_INET, SOCK_STREAM, 0);
2539 if (sock < 0) {
2540 error("Can't create socket: %m");
2541 return (-1);
2543 BZERO(&sad, sizeof(sad));
2544 sad.sin_family = AF_INET;
2545 sad.sin_port = htons(port);
2546 sad.sin_addr.s_addr = host;
2547 if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) >= 0) {
2548 break; /* return sock file descriptor */
2550 if ((hent != NULL) && (hent->h_addr_list != NULL)) {
2551 BCOPY(hent->h_addr_list[0], &host, sizeof(host));
2552 hent->h_addr_list++;
2553 (void) close(sock);
2554 continue;
2556 error("Can't connect to %s: %m", dest);
2557 (void) close(sock);
2558 return (-1);
2560 return (sock);
2564 * print_ncpstate - prints out current NCP state.
2566 * We're normally called from SIGUSR1 here, but this is safe because
2567 * these signals are blocked unless we're idle waiting for events.
2568 * There's no need to otherwise lock the data structures referenced.
2570 void
2571 print_ncpstate(unit, strptr)
2572 int unit;
2573 FILE *strptr;
2575 struct protent *protp;
2576 int i;
2578 (void) flprintf(strptr, "In %s phase\n", phase_name(phase));
2579 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
2580 if (protp->print_stat != NULL)
2581 (*protp->print_stat)(unit, strptr);
2583 sys_print_state(strptr);
2587 * start_charshunt - create a child process to run the character shunt.
2589 static int
2590 start_charshunt(ifd, ofd)
2591 int ifd, ofd;
2593 pid_t cpid;
2595 cpid = fork();
2596 if (cpid == (pid_t)-1) {
2597 error("Can't fork process for character shunt: %m");
2598 return (0);
2600 if (cpid == (pid_t)0) {
2601 /* child */
2602 (void) close(pty_slave);
2603 pty_slave = -1;
2604 (void) setgid(getgid());
2605 (void) setuid(uid);
2606 if (getuid() != uid)
2607 fatal("setuid failed");
2608 if (!nodetach)
2609 log_to_fd = -1;
2610 charshunt(ifd, ofd, record_file);
2611 exit(0);
2613 charshunt_pid = cpid;
2614 (void) close(pty_master);
2615 pty_master = -1;
2616 ttyfd = pty_slave;
2617 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2618 return (1);
2621 /*ARGSUSED*/
2622 static void
2623 charshunt_done(arg, status)
2624 void *arg;
2625 int status;
2627 charshunt_pid = (pid_t)0;
2630 static void
2631 reportme(int signo)
2633 dbglog("charshunt taking signal %d", signo);
2634 exit(1);
2638 * charshunt - the character shunt, which passes characters between
2639 * the pty master side and the serial port (or stdin/stdout).
2640 * This runs as the user (not as root).
2641 * (We assume ofd >= ifd which is true the way this gets called. :-).
2643 static void
2644 charshunt(ifd, ofd, record_file)
2645 int ifd, ofd;
2646 char *record_file;
2648 int n, nfds;
2649 fd_set ready, writey;
2650 u_char *ibufp, *obufp;
2651 int nibuf, nobuf;
2652 int flags;
2653 struct timeval lasttime;
2654 FILE *recordf = NULL;
2655 int ilevel, olevel, max_level;
2656 struct timeval levelt, tout, *top;
2659 * Reset signal handlers.
2661 (void) signal(SIGHUP, SIG_IGN); /* Hangup */
2662 (void) signal(SIGINT, reportme); /* Interrupt */
2663 (void) signal(SIGTERM, reportme); /* Terminate */
2664 (void) signal(SIGCHLD, reportme);
2665 (void) signal(SIGUSR1, reportme);
2666 (void) signal(SIGUSR2, reportme);
2667 (void) signal(SIGABRT, reportme);
2668 (void) signal(SIGALRM, reportme);
2669 (void) signal(SIGFPE, reportme);
2670 (void) signal(SIGILL, reportme);
2671 (void) signal(SIGPIPE, reportme);
2672 (void) signal(SIGQUIT, reportme);
2673 #ifndef DEBUG
2674 (void) signal(SIGSEGV, reportme);
2675 #endif
2676 #ifdef SIGBUS
2677 (void) signal(SIGBUS, reportme);
2678 #endif
2679 #ifdef SIGEMT
2680 (void) signal(SIGEMT, reportme);
2681 #endif
2682 #ifdef SIGPOLL
2683 (void) signal(SIGPOLL, reportme);
2684 #endif
2685 #ifdef SIGPROF
2686 (void) signal(SIGPROF, reportme);
2687 #endif
2688 #ifdef SIGSYS
2689 (void) signal(SIGSYS, reportme);
2690 #endif
2691 #ifdef SIGTRAP
2692 (void) signal(SIGTRAP, reportme);
2693 #endif
2694 #ifdef SIGVTALRM
2695 (void) signal(SIGVTALRM, reportme);
2696 #endif
2697 #ifdef SIGXCPU
2698 (void) signal(SIGXCPU, reportme);
2699 #endif
2700 #ifdef SIGXFSZ
2701 (void) signal(SIGXFSZ, reportme);
2702 #endif
2705 * Open the record file if required.
2707 if (record_file != NULL) {
2708 recordf = fopen(record_file, "a");
2709 if (recordf == NULL)
2710 error("Couldn't create record file %s: %m", record_file);
2713 /* set all the fds to non-blocking mode */
2714 flags = fcntl(pty_master, F_GETFL);
2715 if (flags == -1
2716 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2717 warn("couldn't set pty master to nonblock: %m");
2718 flags = fcntl(ifd, F_GETFL);
2719 if (flags == -1
2720 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2721 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2722 if (ofd != ifd) {
2723 flags = fcntl(ofd, F_GETFL);
2724 if (flags == -1
2725 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2726 warn("couldn't set stdout to nonblock: %m");
2729 nibuf = nobuf = 0;
2730 ibufp = obufp = NULL;
2732 ilevel = olevel = 0;
2733 (void) gettimeofday(&levelt, NULL);
2734 if (max_data_rate) {
2735 max_level = max_data_rate / 10;
2736 if (max_level < MAXLEVELMINSIZE)
2737 max_level = MAXLEVELMINSIZE;
2738 } else
2739 max_level = sizeof(inpacket_buf) + 1;
2741 nfds = (ofd > pty_master? ofd: pty_master) + 1;
2742 if (recordf != NULL) {
2743 (void) gettimeofday(&lasttime, NULL);
2744 (void) putc(RECMARK_TIMESTART, recordf); /* put start marker */
2745 (void) putc(lasttime.tv_sec >> 24, recordf);
2746 (void) putc(lasttime.tv_sec >> 16, recordf);
2747 (void) putc(lasttime.tv_sec >> 8, recordf);
2748 (void) putc(lasttime.tv_sec, recordf);
2749 lasttime.tv_usec = 0;
2752 while (nibuf != 0 || nobuf != 0 || ofd >= 0 || pty_master >= 0) {
2753 top = 0;
2754 tout.tv_sec = 0;
2755 tout.tv_usec = 10000;
2756 FD_ZERO(&ready);
2757 FD_ZERO(&writey);
2758 if (nibuf != 0) {
2759 if (ilevel >= max_level)
2760 top = &tout;
2761 else if (pty_master >= 0)
2762 FD_SET(pty_master, &writey);
2763 } else if (ifd >= 0)
2764 FD_SET(ifd, &ready);
2765 if (nobuf != 0) {
2766 if (olevel >= max_level)
2767 top = &tout;
2768 else if (ofd >= 0)
2769 FD_SET(ofd, &writey);
2770 } else {
2771 /* Don't read from pty if it's gone or it has closed. */
2772 if (pty_master >= 0 && ofd >= 0)
2773 FD_SET(pty_master, &ready);
2775 if (select(nfds, &ready, &writey, NULL, top) < 0) {
2776 if (errno != EINTR)
2777 fatal("select");
2778 continue;
2780 if (max_data_rate) {
2781 double dt;
2782 int nbt;
2783 struct timeval now;
2785 (void) gettimeofday(&now, NULL);
2786 dt = (now.tv_sec - levelt.tv_sec
2787 + (now.tv_usec - levelt.tv_usec) / 1e6);
2788 nbt = (int)(dt * max_data_rate);
2789 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2790 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2791 levelt = now;
2792 } else
2793 ilevel = olevel = 0;
2794 if (FD_ISSET(ifd, &ready)) {
2795 ibufp = inpacket_buf;
2796 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2797 if (nibuf < 0 && errno == EIO)
2798 nibuf = 0;
2799 if (nibuf < 0 || pty_master == -1) {
2800 if (errno != EINTR && errno != EAGAIN) {
2801 error("Error reading standard input: %m");
2802 break;
2804 nibuf = 0;
2805 } else if (nibuf == 0) {
2806 /* end of file from stdin */
2807 (void) close(pty_master);
2808 pty_master = -1;
2809 (void) close(ifd);
2810 ifd = -1;
2811 if (recordf)
2812 if (!record_write(recordf, RECMARK_ENDRECV, NULL, 0,
2813 &lasttime))
2814 recordf = NULL;
2815 } else {
2816 FD_SET(pty_master, &writey);
2817 if (recordf)
2818 if (!record_write(recordf, RECMARK_STARTRECV, ibufp, nibuf,
2819 &lasttime))
2820 recordf = NULL;
2823 if (ofd >= 0 && pty_master >= 0 && FD_ISSET(pty_master, &ready)) {
2824 obufp = outpacket_buf;
2825 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2826 if (nobuf < 0 && errno == EIO)
2827 nobuf = 0;
2828 if (nobuf < 0 || ofd == -1) {
2829 if (!(errno == EINTR || errno == EAGAIN)) {
2830 error("Error reading pseudo-tty master: %m");
2831 break;
2833 nobuf = 0;
2834 } else if (nobuf == 0) {
2835 /* end of file from the pty - slave side has closed */
2836 nibuf = 0;
2837 (void) close(ofd);
2838 ofd = -1;
2839 if (recordf)
2840 if (!record_write(recordf, RECMARK_ENDSEND, NULL, 0,
2841 &lasttime))
2842 recordf = NULL;
2843 } else {
2844 FD_SET(ofd, &writey);
2845 if (recordf)
2846 if (!record_write(recordf, RECMARK_STARTSEND, obufp, nobuf,
2847 &lasttime))
2848 recordf = NULL;
2851 if (ofd == -1)
2852 nobuf = 0;
2853 else if (FD_ISSET(ofd, &writey)) {
2854 n = nobuf;
2855 if (olevel + n > max_level)
2856 n = max_level - olevel;
2857 n = write(ofd, obufp, n);
2858 if (n < 0) {
2859 if (errno == EIO) {
2860 (void) close(ofd);
2861 ofd = -1;
2862 nobuf = 0;
2863 } else if (errno != EAGAIN && errno != EINTR) {
2864 error("Error writing standard output: %m");
2865 break;
2867 } else {
2868 obufp += n;
2869 nobuf -= n;
2870 olevel += n;
2873 if (pty_master == -1)
2874 nibuf = 0;
2875 else if (FD_ISSET(pty_master, &writey)) {
2876 n = nibuf;
2877 if (ilevel + n > max_level)
2878 n = max_level - ilevel;
2879 n = write(pty_master, ibufp, n);
2880 if (n < 0) {
2881 if (errno == EAGAIN || errno == EINTR)
2882 continue;
2883 if (errno != EIO) {
2884 error("Error writing pseudo-tty master: %m");
2885 break;
2887 (void) close(pty_master);
2888 pty_master = -1;
2889 nibuf = 0;
2890 } else {
2891 ibufp += n;
2892 nibuf -= n;
2893 ilevel += n;
2897 exit(0);
2900 static int
2901 record_write(f, code, buf, nb, tp)
2902 FILE *f;
2903 int code;
2904 u_char *buf;
2905 int nb;
2906 struct timeval *tp;
2908 struct timeval now;
2909 int diff;
2911 (void) gettimeofday(&now, NULL);
2912 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2913 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2914 if (diff > 0) {
2915 if (diff > 255) {
2916 (void) putc(RECMARK_TIMEDELTA32, f);
2917 (void) putc(diff >> 24, f);
2918 (void) putc(diff >> 16, f);
2919 (void) putc(diff >> 8, f);
2920 (void) putc(diff, f);
2921 } else {
2922 (void) putc(RECMARK_TIMEDELTA8, f);
2923 (void) putc(diff, f);
2925 *tp = now;
2927 (void) putc(code, f);
2928 if (buf != NULL) {
2929 (void) putc(nb >> 8, f);
2930 (void) putc(nb, f);
2931 (void) fwrite(buf, nb, 1, f);
2933 (void) fflush(f);
2934 if (ferror(f)) {
2935 error("Error writing record file: %m");
2936 return (0);
2938 return (1);