]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
df043dab3c2b172eab8bf7007a09be997da2f589
[ppp.git] / pppd / main.c
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright (c) 1989 Carnegie Mellon University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by Carnegie Mellon University.  The name of the
13  * University may not be used to endorse or promote products derived
14  * from this software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  */
19
20 #ifndef lint
21 static char rcsid[] = "$Id: main.c,v 1.61 1999/03/16 22:54:42 paulus Exp $";
22 #endif
23
24 #include <stdio.h>
25 #include <ctype.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <syslog.h>
33 #include <netdb.h>
34 #include <utmp.h>
35 #include <pwd.h>
36 #include <setjmp.h>
37 #include <sys/param.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <sys/time.h>
41 #include <sys/resource.h>
42 #include <sys/stat.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45
46 #include "pppd.h"
47 #include "magic.h"
48 #include "fsm.h"
49 #include "lcp.h"
50 #include "ipcp.h"
51 #include "upap.h"
52 #include "chap.h"
53 #include "ccp.h"
54 #include "pathnames.h"
55 #include "patchlevel.h"
56
57 #ifdef CBCP_SUPPORT
58 #include "cbcp.h"
59 #endif
60
61 #if defined(SUNOS4)
62 extern char *strerror();
63 #endif
64
65 #ifdef IPX_CHANGE
66 #include "ipxcp.h"
67 #endif /* IPX_CHANGE */
68 #ifdef AT_CHANGE
69 #include "atcp.h"
70 #endif
71
72 /* interface vars */
73 char ifname[32];                /* Interface name */
74 int ifunit;                     /* Interface unit number */
75
76 char *progname;                 /* Name of this program */
77 char hostname[MAXNAMELEN];      /* Our hostname */
78 static char pidfilename[MAXPATHLEN];    /* name of pid file */
79 static char default_devnam[MAXPATHLEN]; /* name of default device */
80 static pid_t pid;               /* Our pid */
81 static uid_t uid;               /* Our real user-id */
82 static int conn_running;        /* we have a [dis]connector running */
83
84 int ttyfd = -1;                 /* Serial port file descriptor */
85 mode_t tty_mode = -1;           /* Original access permissions to tty */
86 int baud_rate;                  /* Actual bits/second for serial device */
87 int hungup;                     /* terminal has been hung up */
88 int privileged;                 /* we're running as real uid root */
89 int need_holdoff;               /* need holdoff period before restarting */
90 int detached;                   /* have detached from terminal */
91 int log_to_stderr;              /* send log messages to stderr too */
92
93 static int fd_ppp;              /* fd for talking PPP */
94 static int fd_loop;             /* fd for getting demand-dial packets */
95
96 int phase;                      /* where the link is at */
97 int kill_link;
98 int open_ccp_flag;
99
100 static int waiting;
101 static sigjmp_buf sigjmp;
102
103 char **script_env;              /* Env. variable values for scripts */
104 int s_env_nalloc;               /* # words avail at script_env */
105
106 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
107 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
108
109 static int n_children;          /* # child processes still running */
110
111 static int locked;              /* lock() has succeeded */
112
113 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
114
115 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
116 int ngroups;                    /* How many groups valid in groups */
117
118 /* Prototypes for procedures local to this file. */
119
120 static void create_pidfile __P((void));
121 static void cleanup __P((void));
122 static void close_tty __P((void));
123 static void get_input __P((void));
124 static void calltimeout __P((void));
125 static struct timeval *timeleft __P((struct timeval *));
126 static void kill_my_pg __P((int));
127 static void hup __P((int));
128 static void term __P((int));
129 static void chld __P((int));
130 static void toggle_debug __P((int));
131 static void open_ccp __P((int));
132 static void bad_signal __P((int));
133 static void holdoff_end __P((void *));
134 static int device_script __P((char *, int, int));
135 static void reap_kids __P((void));
136 static void pr_log __P((void *, char *, ...));
137 static void logit __P((int, char *, va_list));
138 static void vslp_printer __P((void *, char *, ...));
139
140 extern  char    *ttyname __P((int));
141 extern  char    *getlogin __P((void));
142 int main __P((int, char *[]));
143
144 #ifdef ultrix
145 #undef  O_NONBLOCK
146 #define O_NONBLOCK      O_NDELAY
147 #endif
148
149 #ifdef ULTRIX
150 #define setlogmask(x)
151 #endif
152
153 /*
154  * PPP Data Link Layer "protocol" table.
155  * One entry per supported protocol.
156  * The last entry must be NULL.
157  */
158 struct protent *protocols[] = {
159     &lcp_protent,
160     &pap_protent,
161     &chap_protent,
162 #ifdef CBCP_SUPPORT
163     &cbcp_protent,
164 #endif
165     &ipcp_protent,
166     &ccp_protent,
167 #ifdef IPX_CHANGE
168     &ipxcp_protent,
169 #endif
170 #ifdef AT_CHANGE
171     &atcp_protent,
172 #endif
173     NULL
174 };
175
176 int
177 main(argc, argv)
178     int argc;
179     char *argv[];
180 {
181     int i, fdflags;
182     struct sigaction sa;
183     char *p;
184     struct passwd *pw;
185     struct timeval timo;
186     sigset_t mask;
187     struct protent *protp;
188     struct stat statbuf;
189     char numbuf[16];
190
191     phase = PHASE_INITIALIZE;
192     p = ttyname(0);
193     if (p)
194         strlcpy(devnam, sizeof(devnam), p);
195     strlcpy(default_devnam, sizeof(default_devnam), devnam);
196
197     script_env = NULL;
198
199     /* Initialize syslog facilities */
200 #ifdef ULTRIX
201     openlog("pppd", LOG_PID);
202 #else
203     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
204     setlogmask(LOG_UPTO(LOG_INFO));
205 #endif
206
207     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
208         option_error("Couldn't get hostname: %m");
209         exit(1);
210     }
211     hostname[MAXNAMELEN-1] = 0;
212
213     uid = getuid();
214     privileged = uid == 0;
215     slprintf(numbuf, sizeof(numbuf), "%d", uid);
216     script_setenv("ORIG_UID", numbuf);
217
218     ngroups = getgroups(NGROUPS_MAX, groups);
219
220     /*
221      * Initialize to the standard option set, then parse, in order,
222      * the system options file, the user's options file,
223      * the tty's options file, and the command line arguments.
224      */
225     for (i = 0; (protp = protocols[i]) != NULL; ++i)
226         (*protp->init)(0);
227
228     progname = *argv;
229
230     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
231         || !options_from_user())
232         exit(1);
233     scan_args(argc-1, argv+1);  /* look for tty name on command line */
234     if (!options_for_tty()
235         || !parse_args(argc-1, argv+1))
236         exit(1);
237
238     /*
239      * Check that we are running as root.
240      */
241     if (geteuid() != 0) {
242         option_error("must be root to run %s, since it is not setuid-root",
243                      argv[0]);
244         exit(1);
245     }
246
247     if (!ppp_available()) {
248         option_error(no_ppp_msg);
249         exit(1);
250     }
251
252     /*
253      * Check that the options given are valid and consistent.
254      */
255     if (!sys_check_options())
256         exit(1);
257     auth_check_options();
258     for (i = 0; (protp = protocols[i]) != NULL; ++i)
259         if (protp->check_options != NULL)
260             (*protp->check_options)();
261     if (demand && connector == 0) {
262         option_error("connect script is required for demand-dialling\n");
263         exit(1);
264     }
265
266     script_setenv("DEVICE", devnam);
267     slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
268     script_setenv("SPEED", numbuf);
269
270     /*
271      * If the user has specified the default device name explicitly,
272      * pretend they hadn't.
273      */
274     if (!default_device && strcmp(devnam, default_devnam) == 0)
275         default_device = 1;
276     if (default_device)
277         nodetach = 1;
278     log_to_stderr = !default_device;
279
280     /*
281      * Initialize system-dependent stuff and magic number package.
282      */
283     sys_init();
284     magic_init();
285     if (debug)
286         setlogmask(LOG_UPTO(LOG_DEBUG));
287
288     /*
289      * Detach ourselves from the terminal, if required,
290      * and identify who is running us.
291      */
292     if (!nodetach && !updetach)
293         detach();
294     pid = getpid();
295     p = getlogin();
296     if (p == NULL) {
297         pw = getpwuid(uid);
298         if (pw != NULL && pw->pw_name != NULL)
299             p = pw->pw_name;
300         else
301             p = "(unknown)";
302     }
303     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
304            VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
305   
306     /*
307      * Compute mask of all interesting signals and install signal handlers
308      * for each.  Only one signal handler may be active at a time.  Therefore,
309      * all other signals should be masked when any handler is executing.
310      */
311     sigemptyset(&mask);
312     sigaddset(&mask, SIGHUP);
313     sigaddset(&mask, SIGINT);
314     sigaddset(&mask, SIGTERM);
315     sigaddset(&mask, SIGCHLD);
316     sigaddset(&mask, SIGUSR2);
317
318 #define SIGNAL(s, handler)      do { \
319         sa.sa_handler = handler; \
320         if (sigaction(s, &sa, NULL) < 0) \
321             fatal("Couldn't establish signal handler (%d): %m", s); \
322     } while (0)
323
324     sa.sa_mask = mask;
325     sa.sa_flags = 0;
326     SIGNAL(SIGHUP, hup);                /* Hangup */
327     SIGNAL(SIGINT, term);               /* Interrupt */
328     SIGNAL(SIGTERM, term);              /* Terminate */
329     SIGNAL(SIGCHLD, chld);
330
331     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
332     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
333
334     /*
335      * Install a handler for other signals which would otherwise
336      * cause pppd to exit without cleaning up.
337      */
338     SIGNAL(SIGABRT, bad_signal);
339     SIGNAL(SIGALRM, bad_signal);
340     SIGNAL(SIGFPE, bad_signal);
341     SIGNAL(SIGILL, bad_signal);
342     SIGNAL(SIGPIPE, bad_signal);
343     SIGNAL(SIGQUIT, bad_signal);
344     SIGNAL(SIGSEGV, bad_signal);
345 #ifdef SIGBUS
346     SIGNAL(SIGBUS, bad_signal);
347 #endif
348 #ifdef SIGEMT
349     SIGNAL(SIGEMT, bad_signal);
350 #endif
351 #ifdef SIGPOLL
352     SIGNAL(SIGPOLL, bad_signal);
353 #endif
354 #ifdef SIGPROF
355     SIGNAL(SIGPROF, bad_signal);
356 #endif
357 #ifdef SIGSYS
358     SIGNAL(SIGSYS, bad_signal);
359 #endif
360 #ifdef SIGTRAP
361     SIGNAL(SIGTRAP, bad_signal);
362 #endif
363 #ifdef SIGVTALRM
364     SIGNAL(SIGVTALRM, bad_signal);
365 #endif
366 #ifdef SIGXCPU
367     SIGNAL(SIGXCPU, bad_signal);
368 #endif
369 #ifdef SIGXFSZ
370     SIGNAL(SIGXFSZ, bad_signal);
371 #endif
372
373     /*
374      * Apparently we can get a SIGPIPE when we call syslog, if
375      * syslogd has died and been restarted.  Ignoring it seems
376      * be sufficient.
377      */
378     signal(SIGPIPE, SIG_IGN);
379
380     waiting = 0;
381
382     /*
383      * If we're doing dial-on-demand, set up the interface now.
384      */
385     if (demand) {
386         /*
387          * Open the loopback channel and set it up to be the ppp interface.
388          */
389         fd_loop = open_ppp_loopback();
390
391         syslog(LOG_INFO, "Using interface ppp%d", ifunit);
392         slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
393         script_setenv("IFNAME", ifname);
394
395         create_pidfile();       /* write pid to file */
396
397         /*
398          * Configure the interface and mark it up, etc.
399          */
400         demand_conf();
401     }
402
403     for (;;) {
404
405         need_holdoff = 1;
406
407         if (demand) {
408             /*
409              * Don't do anything until we see some activity.
410              */
411             kill_link = 0;
412             phase = PHASE_DORMANT;
413             demand_unblock();
414             add_fd(fd_loop);
415             for (;;) {
416                 if (sigsetjmp(sigjmp, 1) == 0) {
417                     sigprocmask(SIG_BLOCK, &mask, NULL);
418                     if (kill_link) {
419                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
420                     } else {
421                         waiting = 1;
422                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
423                         wait_input(timeleft(&timo));
424                     }
425                 }
426                 waiting = 0;
427                 calltimeout();
428                 if (kill_link) {
429                     if (!persist)
430                         break;
431                     kill_link = 0;
432                 }
433                 if (get_loop_output())
434                     break;
435                 reap_kids();
436             }
437             remove_fd(fd_loop);
438             if (kill_link && !persist)
439                 break;
440
441             /*
442              * Now we want to bring up the link.
443              */
444             demand_block();
445             info("Starting link");
446         }
447
448         /*
449          * Lock the device if we've been asked to.
450          */
451         if (lockflag && !default_device) {
452             if (lock(devnam) < 0)
453                 goto fail;
454             locked = 1;
455         }
456
457         /*
458          * Open the serial device and set it up to be the ppp interface.
459          * First we open it in non-blocking mode so we can set the
460          * various termios flags appropriately.  If we aren't dialling
461          * out and we want to use the modem lines, we reopen it later
462          * in order to wait for the carrier detect signal from the modem.
463          */
464         hungup = 0;
465         kill_link = 0;
466         for (;;) {
467             /* If the user specified the device name, become the
468                user before opening it. */
469             if (!devnam_info.priv)
470                 seteuid(uid);
471             ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
472             if (!devnam_info.priv)
473                 seteuid(0);
474             if (ttyfd >= 0)
475                 break;
476             if (errno != EINTR)
477                 error("Failed to open %s: %m", devnam);
478             if (!persist || errno != EINTR)
479                 goto fail;
480         }
481         if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
482             || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
483             warn("Couldn't reset non-blocking mode on device: %m");
484
485         /*
486          * Do the equivalent of `mesg n' to stop broadcast messages.
487          */
488         if (fstat(ttyfd, &statbuf) < 0
489             || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
490             warn("Couldn't restrict write permissions to %s: %m", devnam);
491         } else
492             tty_mode = statbuf.st_mode;
493
494         /* run connection script */
495         if (connector && connector[0]) {
496             MAINDEBUG(("Connecting with <%s>", connector));
497
498             if (!default_device && modem) {
499                 hangup_modem(ttyfd);    /* in case modem is off hook */
500                 sleep(1);
501             }
502
503             /*
504              * Set line speed, flow control, etc.
505              * On most systems we set CLOCAL for now so that we can talk
506              * to the modem before carrier comes up.  But this has the
507              * side effect that we might miss it if CD drops before we
508              * get to clear CLOCAL below.  On systems where we can talk
509              * successfully to the modem with CLOCAL clear and CD down,
510              * we could clear CLOCAL at this point.
511              */
512             set_up_tty(ttyfd, 1);
513
514             if (device_script(connector, ttyfd, ttyfd) < 0) {
515                 error("Connect script failed");
516                 goto fail;
517             }
518
519             info("Serial connection established.");
520             sleep(1);           /* give it time to set up its terminal */
521         }
522
523         /* set line speed, flow control, etc.; clear CLOCAL if modem option */
524         set_up_tty(ttyfd, 0);
525
526         /* reopen tty if necessary to wait for carrier */
527         if (connector == NULL && modem) {
528             for (;;) {
529                 if ((i = open(devnam, O_RDWR)) >= 0)
530                     break;
531                 if (errno != EINTR)
532                     error("Failed to reopen %s: %m", devnam);
533                 if (!persist || errno != EINTR || hungup || kill_link)
534                     goto fail;
535             }
536             close(i);
537         }
538
539         /* run welcome script, if any */
540         if (welcomer && welcomer[0]) {
541             if (device_script(welcomer, ttyfd, ttyfd) < 0)
542                 warn("Welcome script failed");
543         }
544
545         /* set up the serial device as a ppp interface */
546         fd_ppp = establish_ppp(ttyfd);
547
548         if (!demand) {
549             
550             info("Using interface ppp%d", ifunit);
551             slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
552             script_setenv("IFNAME", ifname);
553
554             create_pidfile();   /* write pid to file */
555         }
556
557         /*
558          * Start opening the connection and wait for
559          * incoming events (reply, timeout, etc.).
560          */
561         notice("Connect: %s <--> %s", ifname, devnam);
562         lcp_lowerup(0);
563         lcp_open(0);            /* Start protocol */
564         open_ccp_flag = 0;
565         add_fd(fd_ppp);
566         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
567             if (sigsetjmp(sigjmp, 1) == 0) {
568                 sigprocmask(SIG_BLOCK, &mask, NULL);
569                 if (kill_link || open_ccp_flag) {
570                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
571                 } else {
572                     waiting = 1;
573                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
574                     wait_input(timeleft(&timo));
575                 }
576             }
577             waiting = 0;
578             calltimeout();
579             if (kill_link) {
580                 lcp_close(0, "User request");
581                 kill_link = 0;
582             }
583             get_input();
584             if (open_ccp_flag) {
585                 if (phase == PHASE_NETWORK) {
586                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
587                     (*ccp_protent.open)(0);
588                 }
589                 open_ccp_flag = 0;
590             }
591             reap_kids();        /* Don't leave dead kids lying around */
592         }
593
594         /*
595          * If we may want to bring the link up again, transfer
596          * the ppp unit back to the loopback.  Set the
597          * real serial device back to its normal mode of operation.
598          */
599         remove_fd(fd_ppp);
600         clean_check();
601         if (demand)
602             restore_loop();
603         disestablish_ppp(ttyfd);
604
605         /*
606          * Run disconnector script, if requested.
607          * XXX we may not be able to do this if the line has hung up!
608          */
609         if (disconnector && !hungup) {
610             set_up_tty(ttyfd, 1);
611             if (device_script(disconnector, ttyfd, ttyfd) < 0) {
612                 warn("disconnect script failed");
613             } else {
614                 info("Serial link disconnected.");
615             }
616         }
617         if (!hungup)
618             lcp_lowerdown(0);
619
620     fail:
621         if (ttyfd >= 0)
622             close_tty();
623         if (locked) {
624             unlock();
625             locked = 0;
626         }
627
628         if (!demand) {
629             if (pidfilename[0] != 0
630                 && unlink(pidfilename) < 0 && errno != ENOENT) 
631                 warn("unable to delete pid file: %m");
632             pidfilename[0] = 0;
633         }
634
635         if (!persist)
636             break;
637
638         kill_link = 0;
639         if (demand)
640             demand_discard();
641         if (holdoff > 0 && need_holdoff) {
642             phase = PHASE_HOLDOFF;
643             TIMEOUT(holdoff_end, NULL, holdoff);
644             do {
645                 if (sigsetjmp(sigjmp, 1) == 0) {
646                     sigprocmask(SIG_BLOCK, &mask, NULL);
647                     if (kill_link) {
648                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
649                     } else {
650                         waiting = 1;
651                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
652                         wait_input(timeleft(&timo));
653                     }
654                 }
655                 waiting = 0;
656                 calltimeout();
657                 if (kill_link) {
658                     kill_link = 0;
659                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
660                 }
661                 reap_kids();
662             } while (phase == PHASE_HOLDOFF);
663             if (!persist)
664                 break;
665         }
666     }
667
668     /* Wait for scripts to finish */
669     while (n_children > 0)
670         reap_kids();
671
672     die(0);
673     return 0;
674 }
675
676 /*
677  * detach - detach us from the controlling terminal.
678  */
679 void
680 detach()
681 {
682     if (detached)
683         return;
684     if (daemon(0, 0) < 0) {
685         perror("Couldn't detach from controlling terminal");
686         die(1);
687     }
688     detached = 1;
689     log_to_stderr = 0;
690     pid = getpid();
691     /* update pid file if it has been written already */
692     if (pidfilename[0])
693         create_pidfile();
694 }
695
696 /*
697  * Create a file containing our process ID.
698  */
699 static void
700 create_pidfile()
701 {
702     FILE *pidfile;
703     char numbuf[16];
704
705     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
706              _PATH_VARRUN, ifname);
707     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
708         fprintf(pidfile, "%d\n", pid);
709         (void) fclose(pidfile);
710     } else {
711         error("Failed to create pid file %s: %m", pidfilename);
712         pidfilename[0] = 0;
713     }
714     slprintf(numbuf, sizeof(numbuf), "%d", pid);
715     script_setenv("PPPD_PID", numbuf);
716 }
717
718 /*
719  * holdoff_end - called via a timeout when the holdoff period ends.
720  */
721 static void
722 holdoff_end(arg)
723     void *arg;
724 {
725     phase = PHASE_DORMANT;
726 }
727
728 /*
729  * get_input - called when incoming data is available.
730  */
731 static void
732 get_input()
733 {
734     int len, i;
735     u_char *p;
736     u_short protocol;
737     struct protent *protp;
738
739     p = inpacket_buf;   /* point to beginning of packet buffer */
740
741     len = read_packet(inpacket_buf);
742     if (len < 0)
743         return;
744
745     if (len == 0) {
746         notice("Modem hangup");
747         hungup = 1;
748         lcp_lowerdown(0);       /* serial link is no longer available */
749         link_terminated(0);
750         return;
751     }
752
753     if (debug /*&& (debugflags & DBG_INPACKET)*/)
754         dbglog("rcvd %P", p, len);
755
756     if (len < PPP_HDRLEN) {
757         MAINDEBUG(("io(): Received short packet."));
758         return;
759     }
760
761     p += 2;                             /* Skip address and control */
762     GETSHORT(protocol, p);
763     len -= PPP_HDRLEN;
764
765     /*
766      * Toss all non-LCP packets unless LCP is OPEN.
767      */
768     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
769         MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
770         return;
771     }
772
773     /*
774      * Until we get past the authentication phase, toss all packets
775      * except LCP, LQR and authentication packets.
776      */
777     if (phase <= PHASE_AUTHENTICATE
778         && !(protocol == PPP_LCP || protocol == PPP_LQR
779              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
780         MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
781                    protocol, phase));
782         return;
783     }
784
785     /*
786      * Upcall the proper protocol input routine.
787      */
788     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
789         if (protp->protocol == protocol && protp->enabled_flag) {
790             (*protp->input)(0, p, len);
791             return;
792         }
793         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
794             && protp->datainput != NULL) {
795             (*protp->datainput)(0, p, len);
796             return;
797         }
798     }
799
800     if (debug)
801         warn("Unsupported protocol (0x%x) received", protocol);
802     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
803 }
804
805
806 /*
807  * quit - Clean up state and exit (with an error indication).
808  */
809 void 
810 quit()
811 {
812     die(1);
813 }
814
815 /*
816  * die - like quit, except we can specify an exit status.
817  */
818 void
819 die(status)
820     int status;
821 {
822     cleanup();
823     syslog(LOG_INFO, "Exit.");
824     exit(status);
825 }
826
827 /*
828  * cleanup - restore anything which needs to be restored before we exit
829  */
830 /* ARGSUSED */
831 static void
832 cleanup()
833 {
834     sys_cleanup();
835
836     if (ttyfd >= 0)
837         close_tty();
838
839     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
840         warn("unable to delete pid file: %m");
841     pidfilename[0] = 0;
842
843     if (locked)
844         unlock();
845 }
846
847 /*
848  * close_tty - restore the terminal device and close it.
849  */
850 static void
851 close_tty()
852 {
853     disestablish_ppp(ttyfd);
854
855     /* drop dtr to hang up */
856     if (!default_device && modem) {
857         hangup_modem(ttyfd);
858         /*
859          * This sleep is in case the serial port has CLOCAL set by default,
860          * and consequently will reassert DTR when we close the device.
861          */
862         sleep(1);
863     }
864
865     restore_tty(ttyfd);
866
867     if (tty_mode != (mode_t) -1) {
868         if (fchmod(ttyfd, tty_mode) != 0) {
869             /* XXX if devnam is a symlink, this will change the link */
870             chmod(devnam, tty_mode);
871         }
872     }
873
874     close(ttyfd);
875     ttyfd = -1;
876 }
877
878 /*
879  * hangup_modem - hang up the modem by clearing DTR.
880  */
881 void hangup_modem(ttyfd)
882     int ttyfd;
883 {
884     setdtr(ttyfd, 0);
885 }
886
887
888 struct  callout {
889     struct timeval      c_time;         /* time at which to call routine */
890     void                *c_arg;         /* argument to routine */
891     void                (*c_func) __P((void *)); /* routine */
892     struct              callout *c_next;
893 };
894
895 static struct callout *callout = NULL;  /* Callout list */
896 static struct timeval timenow;          /* Current time */
897
898 /*
899  * timeout - Schedule a timeout.
900  *
901  * Note that this timeout takes the number of seconds, NOT hz (as in
902  * the kernel).
903  */
904 void
905 timeout(func, arg, time)
906     void (*func) __P((void *));
907     void *arg;
908     int time;
909 {
910     struct callout *newp, *p, **pp;
911   
912     MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
913   
914     /*
915      * Allocate timeout.
916      */
917     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
918         fatal("Out of memory in timeout()!");
919     newp->c_arg = arg;
920     newp->c_func = func;
921     gettimeofday(&timenow, NULL);
922     newp->c_time.tv_sec = timenow.tv_sec + time;
923     newp->c_time.tv_usec = timenow.tv_usec;
924   
925     /*
926      * Find correct place and link it in.
927      */
928     for (pp = &callout; (p = *pp); pp = &p->c_next)
929         if (newp->c_time.tv_sec < p->c_time.tv_sec
930             || (newp->c_time.tv_sec == p->c_time.tv_sec
931                 && newp->c_time.tv_usec < p->c_time.tv_usec))
932             break;
933     newp->c_next = p;
934     *pp = newp;
935 }
936
937
938 /*
939  * untimeout - Unschedule a timeout.
940  */
941 void
942 untimeout(func, arg)
943     void (*func) __P((void *));
944     void *arg;
945 {
946     struct callout **copp, *freep;
947   
948     MAINDEBUG(("Untimeout %p:%p.", func, arg));
949   
950     /*
951      * Find first matching timeout and remove it from the list.
952      */
953     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
954         if (freep->c_func == func && freep->c_arg == arg) {
955             *copp = freep->c_next;
956             (void) free((char *) freep);
957             break;
958         }
959 }
960
961
962 /*
963  * calltimeout - Call any timeout routines which are now due.
964  */
965 static void
966 calltimeout()
967 {
968     struct callout *p;
969
970     while (callout != NULL) {
971         p = callout;
972
973         if (gettimeofday(&timenow, NULL) < 0)
974             fatal("Failed to get time of day: %m");
975         if (!(p->c_time.tv_sec < timenow.tv_sec
976               || (p->c_time.tv_sec == timenow.tv_sec
977                   && p->c_time.tv_usec <= timenow.tv_usec)))
978             break;              /* no, it's not time yet */
979
980         callout = p->c_next;
981         (*p->c_func)(p->c_arg);
982
983         free((char *) p);
984     }
985 }
986
987
988 /*
989  * timeleft - return the length of time until the next timeout is due.
990  */
991 static struct timeval *
992 timeleft(tvp)
993     struct timeval *tvp;
994 {
995     if (callout == NULL)
996         return NULL;
997
998     gettimeofday(&timenow, NULL);
999     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1000     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1001     if (tvp->tv_usec < 0) {
1002         tvp->tv_usec += 1000000;
1003         tvp->tv_sec -= 1;
1004     }
1005     if (tvp->tv_sec < 0)
1006         tvp->tv_sec = tvp->tv_usec = 0;
1007
1008     return tvp;
1009 }
1010
1011
1012 /*
1013  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1014  */
1015 static void
1016 kill_my_pg(sig)
1017     int sig;
1018 {
1019     struct sigaction act, oldact;
1020
1021     act.sa_handler = SIG_IGN;
1022     act.sa_flags = 0;
1023     kill(0, sig);
1024     sigaction(sig, &act, &oldact);
1025     sigaction(sig, &oldact, NULL);
1026 }
1027
1028
1029 /*
1030  * hup - Catch SIGHUP signal.
1031  *
1032  * Indicates that the physical layer has been disconnected.
1033  * We don't rely on this indication; if the user has sent this
1034  * signal, we just take the link down.
1035  */
1036 static void
1037 hup(sig)
1038     int sig;
1039 {
1040     info("Hangup (SIGHUP)");
1041     kill_link = 1;
1042     if (conn_running)
1043         /* Send the signal to the [dis]connector process(es) also */
1044         kill_my_pg(sig);
1045     if (waiting)
1046         siglongjmp(sigjmp, 1);
1047 }
1048
1049
1050 /*
1051  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1052  *
1053  * Indicates that we should initiate a graceful disconnect and exit.
1054  */
1055 /*ARGSUSED*/
1056 static void
1057 term(sig)
1058     int sig;
1059 {
1060     info("Terminating on signal %d.", sig);
1061     persist = 0;                /* don't try to restart */
1062     kill_link = 1;
1063     if (conn_running)
1064         /* Send the signal to the [dis]connector process(es) also */
1065         kill_my_pg(sig);
1066     if (waiting)
1067         siglongjmp(sigjmp, 1);
1068 }
1069
1070
1071 /*
1072  * chld - Catch SIGCHLD signal.
1073  * Calls reap_kids to get status for any dead kids.
1074  */
1075 static void
1076 chld(sig)
1077     int sig;
1078 {
1079     if (waiting)
1080         siglongjmp(sigjmp, 1);
1081 }
1082
1083
1084 /*
1085  * toggle_debug - Catch SIGUSR1 signal.
1086  *
1087  * Toggle debug flag.
1088  */
1089 /*ARGSUSED*/
1090 static void
1091 toggle_debug(sig)
1092     int sig;
1093 {
1094     debug = !debug;
1095     if (debug) {
1096         setlogmask(LOG_UPTO(LOG_DEBUG));
1097     } else {
1098         setlogmask(LOG_UPTO(LOG_WARNING));
1099     }
1100 }
1101
1102
1103 /*
1104  * open_ccp - Catch SIGUSR2 signal.
1105  *
1106  * Try to (re)negotiate compression.
1107  */
1108 /*ARGSUSED*/
1109 static void
1110 open_ccp(sig)
1111     int sig;
1112 {
1113     open_ccp_flag = 1;
1114     if (waiting)
1115         siglongjmp(sigjmp, 1);
1116 }
1117
1118
1119 /*
1120  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1121  */
1122 static void
1123 bad_signal(sig)
1124     int sig;
1125 {
1126     static int crashed = 0;
1127
1128     if (crashed)
1129         _exit(127);
1130     crashed = 1;
1131     error("Fatal signal %d", sig);
1132     if (conn_running)
1133         kill_my_pg(SIGTERM);
1134     die(1);
1135 }
1136
1137
1138 /*
1139  * device_script - run a program to connect or disconnect the
1140  * serial device.
1141  */
1142 static int
1143 device_script(program, in, out)
1144     char *program;
1145     int in, out;
1146 {
1147     int pid;
1148     int status;
1149     int errfd;
1150
1151     conn_running = 1;
1152     pid = fork();
1153
1154     if (pid < 0) {
1155         conn_running = 0;
1156         fatal("Failed to create child process: %m");
1157     }
1158
1159     if (pid == 0) {
1160         sys_close();
1161         closelog();
1162         if (in == out) {
1163             if (in != 0) {
1164                 dup2(in, 0);
1165                 close(in);
1166             }
1167             dup2(0, 1);
1168         } else {
1169             if (out == 0)
1170                 out = dup(out);
1171             if (in != 0) {
1172                 dup2(in, 0);
1173                 close(in);
1174             }
1175             if (out != 1) {
1176                 dup2(out, 1);
1177                 close(out);
1178             }
1179         }
1180         if (!nodetach && !updetach) {
1181             close(2);
1182             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1183             if (errfd >= 0 && errfd != 2) {
1184                 dup2(errfd, 2);
1185                 close(errfd);
1186             }
1187         }
1188         setuid(uid);
1189         if (getuid() != uid) {
1190             error("setuid failed");
1191             exit(1);
1192         }
1193         setgid(getgid());
1194         execl("/bin/sh", "sh", "-c", program, (char *)0);
1195         error("could not exec /bin/sh: %m");
1196         exit(99);
1197         /* NOTREACHED */
1198     }
1199
1200     while (waitpid(pid, &status, 0) < 0) {
1201         if (errno == EINTR)
1202             continue;
1203         fatal("error waiting for (dis)connection process: %m");
1204     }
1205     conn_running = 0;
1206
1207     return (status == 0 ? 0 : -1);
1208 }
1209
1210
1211 /*
1212  * We maintain a list of child process pids and
1213  * functions to call when they exit.
1214  */
1215 struct subprocess {
1216     pid_t       pid;
1217     char        *prog;
1218     void        (*done) __P((void *));
1219     void        *arg;
1220     struct subprocess *next;
1221 };
1222
1223 struct subprocess *children;
1224
1225 /*
1226  * run-program - execute a program with given arguments,
1227  * but don't wait for it.
1228  * If the program can't be executed, logs an error unless
1229  * must_exist is 0 and the program file doesn't exist.
1230  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1231  * or isn't an executable plain file, or the process ID of the child.
1232  * If done != NULL, (*done)(arg) will be called later (within
1233  * reap_kids) iff the return value is > 0.
1234  */
1235 pid_t
1236 run_program(prog, args, must_exist, done, arg)
1237     char *prog;
1238     char **args;
1239     int must_exist;
1240     void (*done) __P((void *));
1241     void *arg;
1242 {
1243     int pid;
1244     struct subprocess *chp;
1245     struct stat sbuf;
1246
1247     /*
1248      * First check if the file exists and is executable.
1249      * We don't use access() because that would use the
1250      * real user-id, which might not be root, and the script
1251      * might be accessible only to root.
1252      */
1253     errno = EINVAL;
1254     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1255         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1256         if (must_exist || errno != ENOENT)
1257             warn("Can't execute %s: %m", prog);
1258         return 0;
1259     }
1260
1261     pid = fork();
1262     if (pid == -1)
1263         fatal("Failed to create child process for %s: %m", prog);
1264     if (pid == 0) {
1265         int new_fd;
1266
1267         /* Leave the current location */
1268         (void) setsid();        /* No controlling tty. */
1269         (void) umask (S_IRWXG|S_IRWXO);
1270         (void) chdir ("/");     /* no current directory. */
1271         setuid(0);              /* set real UID = root */
1272         setgid(getegid());
1273
1274         /* Ensure that nothing of our device environment is inherited. */
1275         sys_close();
1276         closelog();
1277         close (0);
1278         close (1);
1279         close (2);
1280         close (ttyfd);  /* tty interface to the ppp device */
1281
1282         /* Don't pass handles to the PPP device, even by accident. */
1283         new_fd = open (_PATH_DEVNULL, O_RDWR);
1284         if (new_fd >= 0) {
1285             if (new_fd != 0) {
1286                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1287                 close (new_fd);
1288             }
1289             dup2 (0, 1); /* stdout -> /dev/null */
1290             dup2 (0, 2); /* stderr -> /dev/null */
1291         }
1292
1293 #ifdef BSD
1294         /* Force the priority back to zero if pppd is running higher. */
1295         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1296             warn("can't reset priority to 0: %m"); 
1297 #endif
1298
1299         /* SysV recommends a second fork at this point. */
1300
1301         /* run the program */
1302         execve(prog, args, script_env);
1303         if (must_exist || errno != ENOENT)
1304             warn("Can't execute %s: %m", prog);
1305         _exit(-1);
1306     }
1307
1308     if (debug)
1309         dbglog("Script %s started; pid = %d", prog, pid);
1310     ++n_children;
1311
1312     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1313     if (chp == NULL) {
1314         warn("losing track of %s process", prog);
1315     } else {
1316         chp->pid = pid;
1317         chp->prog = prog;
1318         chp->done = done;
1319         chp->arg = arg;
1320         chp->next = children;
1321         children = chp;
1322     }
1323
1324     return pid;
1325 }
1326
1327
1328 /*
1329  * reap_kids - get status from any dead child processes,
1330  * and log a message for abnormal terminations.
1331  */
1332 static void
1333 reap_kids()
1334 {
1335     int pid, status;
1336     struct subprocess *chp, **prevp;
1337
1338     if (n_children == 0)
1339         return;
1340     while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1341         --n_children;
1342         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1343             if (chp->pid == pid)
1344                 break;
1345         if (debug)
1346             dbglog("process %d (%s) finished, status = 0x%x",
1347                    pid, (chp? chp->prog: "??"), status);
1348         if (WIFSIGNALED(status)) {
1349             warn("Child process %s (pid %d) terminated with signal %d",
1350                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1351         }
1352         if (chp && chp->done)
1353             (*chp->done)(chp->arg);
1354     }
1355     if (pid == -1 && errno != ECHILD)
1356         error("Error waiting for child process: %m");
1357 }
1358
1359
1360 /*
1361  * log_packet - format a packet and log it.
1362  */
1363
1364 char line[256];                 /* line to be logged accumulated here */
1365 char *linep;
1366
1367 void
1368 log_packet(p, len, prefix, level)
1369     u_char *p;
1370     int len;
1371     char *prefix;
1372     int level;
1373 {
1374     strlcpy(line, sizeof(line), prefix);
1375     linep = line + strlen(line);
1376     format_packet(p, len, pr_log, NULL);
1377     if (linep != line)
1378         syslog(level, "%s", line);
1379 }
1380
1381 /*
1382  * format_packet - make a readable representation of a packet,
1383  * calling `printer(arg, format, ...)' to output it.
1384  */
1385 void
1386 format_packet(p, len, printer, arg)
1387     u_char *p;
1388     int len;
1389     void (*printer) __P((void *, char *, ...));
1390     void *arg;
1391 {
1392     int i, n;
1393     u_short proto;
1394     struct protent *protp;
1395
1396     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1397         p += 2;
1398         GETSHORT(proto, p);
1399         len -= PPP_HDRLEN;
1400         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1401             if (proto == protp->protocol)
1402                 break;
1403         if (protp != NULL) {
1404             printer(arg, "[%s", protp->name);
1405             n = (*protp->printpkt)(p, len, printer, arg);
1406             printer(arg, "]");
1407             p += n;
1408             len -= n;
1409         } else {
1410             for (i = 0; (protp = protocols[i]) != NULL; ++i)
1411                 if (proto == (protp->protocol & ~0x8000))
1412                     break;
1413             if (protp != 0 && protp->data_name != 0) {
1414                 printer(arg, "[%s data]", protp->data_name);
1415                 if (len > 8)
1416                     printer(arg, "%.8B ...", p);
1417                 else
1418                     printer(arg, "%.*B", len, p);
1419                 len = 0;
1420             } else
1421                 printer(arg, "[proto=0x%x]", proto);
1422         }
1423     }
1424
1425     if (len > 32)
1426         printer(arg, "%.32B ...", p);
1427     else
1428         printer(arg, "%.*B", len, p);
1429 }
1430
1431 static void
1432 pr_log __V((void *arg, char *fmt, ...))
1433 {
1434     int n;
1435     va_list pvar;
1436     char buf[256];
1437
1438 #if __STDC__
1439     va_start(pvar, fmt);
1440 #else
1441     void *arg;
1442     char *fmt;
1443     va_start(pvar);
1444     arg = va_arg(pvar, void *);
1445     fmt = va_arg(pvar, char *);
1446 #endif
1447
1448     n = vslprintf(buf, sizeof(buf), fmt, pvar);
1449     va_end(pvar);
1450
1451     if (linep + n + 1 > line + sizeof(line)) {
1452         syslog(LOG_DEBUG, "%s", line);
1453         linep = line;
1454     }
1455     strlcpy(linep, line + sizeof(line) - linep, buf);
1456     linep += n;
1457 }
1458
1459 /*
1460  * vslp_printer - used in processing a %P format
1461  */
1462 struct buffer_info {
1463     char *ptr;
1464     int len;
1465 };
1466
1467 static void
1468 vslp_printer __V((void *arg, char *fmt, ...))
1469 {
1470     int n;
1471     va_list pvar;
1472     struct buffer_info *bi;
1473
1474 #if __STDC__
1475     va_start(pvar, fmt);
1476 #else
1477     void *arg;
1478     char *fmt;
1479     va_start(pvar);
1480     arg = va_arg(pvar, void *);
1481     fmt = va_arg(pvar, char *);
1482 #endif
1483
1484     bi = (struct buffer_info *) arg;
1485     n = vslprintf(bi->ptr, bi->len, fmt, pvar);
1486     va_end(pvar);
1487
1488     bi->ptr += n;
1489     bi->len -= n;
1490 }
1491
1492 /*
1493  * print_string - print a readable representation of a string using
1494  * printer.
1495  */
1496 void
1497 print_string(p, len, printer, arg)
1498     char *p;
1499     int len;
1500     void (*printer) __P((void *, char *, ...));
1501     void *arg;
1502 {
1503     int c;
1504
1505     printer(arg, "\"");
1506     for (; len > 0; --len) {
1507         c = *p++;
1508         if (' ' <= c && c <= '~') {
1509             if (c == '\\' || c == '"')
1510                 printer(arg, "\\");
1511             printer(arg, "%c", c);
1512         } else {
1513             switch (c) {
1514             case '\n':
1515                 printer(arg, "\\n");
1516                 break;
1517             case '\r':
1518                 printer(arg, "\\r");
1519                 break;
1520             case '\t':
1521                 printer(arg, "\\t");
1522                 break;
1523             default:
1524                 printer(arg, "\\%.3o", c);
1525             }
1526         }
1527     }
1528     printer(arg, "\"");
1529 }
1530
1531 /*
1532  * novm - log an error message saying we ran out of memory, and die.
1533  */
1534 void
1535 novm(msg)
1536     char *msg;
1537 {
1538     fatal("Virtual memory exhausted allocating %s\n", msg);
1539 }
1540
1541 /*
1542  * slprintf - format a message into a buffer.  Like sprintf except we
1543  * also specify the length of the output buffer, and we handle
1544  * %r (recursive format), %m (error message), %v (visible string),
1545  * %q (quoted string), %t (current time) and %I (IP address) formats.
1546  * Doesn't do floating-point formats.
1547  * Returns the number of chars put into buf.
1548  */
1549 int
1550 slprintf __V((char *buf, int buflen, char *fmt, ...))
1551 {
1552     va_list args;
1553     int n;
1554
1555 #if __STDC__
1556     va_start(args, fmt);
1557 #else
1558     char *buf;
1559     int buflen;
1560     char *fmt;
1561     va_start(args);
1562     buf = va_arg(args, char *);
1563     buflen = va_arg(args, int);
1564     fmt = va_arg(args, char *);
1565 #endif
1566     n = vslprintf(buf, buflen, fmt, args);
1567     va_end(args);
1568     return n;
1569 }
1570
1571 /*
1572  * vslprintf - like slprintf, takes a va_list instead of a list of args.
1573  */
1574 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1575
1576 int
1577 vslprintf(buf, buflen, fmt, args)
1578     char *buf;
1579     int buflen;
1580     char *fmt;
1581     va_list args;
1582 {
1583     int c, i, n;
1584     int width, prec, fillch;
1585     int base, len, neg, quoted;
1586     unsigned long val = 0;
1587     char *str, *f, *buf0;
1588     unsigned char *p;
1589     char num[32];
1590     time_t t;
1591     u_int32_t ip;
1592     static char hexchars[] = "0123456789abcdef";
1593     struct buffer_info bufinfo;
1594
1595     buf0 = buf;
1596     --buflen;
1597     while (buflen > 0) {
1598         for (f = fmt; *f != '%' && *f != 0; ++f)
1599             ;
1600         if (f > fmt) {
1601             len = f - fmt;
1602             if (len > buflen)
1603                 len = buflen;
1604             memcpy(buf, fmt, len);
1605             buf += len;
1606             buflen -= len;
1607             fmt = f;
1608         }
1609         if (*fmt == 0)
1610             break;
1611         c = *++fmt;
1612         width = prec = 0;
1613         fillch = ' ';
1614         if (c == '0') {
1615             fillch = '0';
1616             c = *++fmt;
1617         }
1618         if (c == '*') {
1619             width = va_arg(args, int);
1620             c = *++fmt;
1621         } else {
1622             while (isdigit(c)) {
1623                 width = width * 10 + c - '0';
1624                 c = *++fmt;
1625             }
1626         }
1627         if (c == '.') {
1628             c = *++fmt;
1629             if (c == '*') {
1630                 prec = va_arg(args, int);
1631                 c = *++fmt;
1632             } else {
1633                 while (isdigit(c)) {
1634                     prec = prec * 10 + c - '0';
1635                     c = *++fmt;
1636                 }
1637             }
1638         }
1639         str = 0;
1640         base = 0;
1641         neg = 0;
1642         ++fmt;
1643         switch (c) {
1644         case 'd':
1645             i = va_arg(args, int);
1646             if (i < 0) {
1647                 neg = 1;
1648                 val = -i;
1649             } else
1650                 val = i;
1651             base = 10;
1652             break;
1653         case 'o':
1654             val = va_arg(args, unsigned int);
1655             base = 8;
1656             break;
1657         case 'x':
1658         case 'X':
1659             val = va_arg(args, unsigned int);
1660             base = 16;
1661             break;
1662         case 'p':
1663             val = (unsigned long) va_arg(args, void *);
1664             base = 16;
1665             neg = 2;
1666             break;
1667         case 's':
1668             str = va_arg(args, char *);
1669             break;
1670         case 'c':
1671             num[0] = va_arg(args, int);
1672             num[1] = 0;
1673             str = num;
1674             break;
1675         case 'm':
1676             str = strerror(errno);
1677             break;
1678         case 'I':
1679             ip = va_arg(args, u_int32_t);
1680             ip = ntohl(ip);
1681             slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
1682                      (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
1683             str = num;
1684             break;
1685         case 'r':
1686             f = va_arg(args, char *);
1687 #ifndef __powerpc__
1688             n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1689 #else
1690             /* On the powerpc, a va_list is an array of 1 structure */
1691             n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1692 #endif
1693             buf += n;
1694             buflen -= n;
1695             continue;
1696         case 't':
1697             time(&t);
1698             str = ctime(&t);
1699             str += 4;           /* chop off the day name */
1700             str[15] = 0;        /* chop off year and newline */
1701             break;
1702         case 'v':               /* "visible" string */
1703         case 'q':               /* quoted string */
1704             quoted = c == 'q';
1705             p = va_arg(args, unsigned char *);
1706             if (fillch == '0' && prec > 0) {
1707                 n = prec;
1708             } else {
1709                 n = strlen((char *)p);
1710                 if (prec > 0 && prec < n)
1711                     n = prec;
1712             }
1713             while (n > 0 && buflen > 0) {
1714                 c = *p++;
1715                 --n;
1716                 if (!quoted && c >= 0x80) {
1717                     OUTCHAR('M');
1718                     OUTCHAR('-');
1719                     c -= 0x80;
1720                 }
1721                 if (quoted && (c == '"' || c == '\\'))
1722                     OUTCHAR('\\');
1723                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1724                     if (quoted) {
1725                         OUTCHAR('\\');
1726                         switch (c) {
1727                         case '\t':      OUTCHAR('t');   break;
1728                         case '\n':      OUTCHAR('n');   break;
1729                         case '\b':      OUTCHAR('b');   break;
1730                         case '\f':      OUTCHAR('f');   break;
1731                         default:
1732                             OUTCHAR('x');
1733                             OUTCHAR(hexchars[c >> 4]);
1734                             OUTCHAR(hexchars[c & 0xf]);
1735                         }
1736                     } else {
1737                         if (c == '\t')
1738                             OUTCHAR(c);
1739                         else {
1740                             OUTCHAR('^');
1741                             OUTCHAR(c ^ 0x40);
1742                         }
1743                     }
1744                 } else
1745                     OUTCHAR(c);
1746             }
1747             continue;
1748         case 'P':               /* print PPP packet */
1749             bufinfo.ptr = buf;
1750             bufinfo.len = buflen + 1;
1751             p = va_arg(args, unsigned char *);
1752             n = va_arg(args, int);
1753             format_packet(p, n, vslp_printer, &bufinfo);
1754             buf = bufinfo.ptr;
1755             buflen = bufinfo.len - 1;
1756             continue;
1757         case 'B':
1758             p = va_arg(args, unsigned char *);
1759             for (n = prec; n > 0; --n) {
1760                 c = *p++;
1761                 if (fillch == ' ')
1762                     OUTCHAR(' ');
1763                 OUTCHAR(hexchars[(c >> 4) & 0xf]);
1764                 OUTCHAR(hexchars[c & 0xf]);
1765             }
1766             continue;
1767         default:
1768             *buf++ = '%';
1769             if (c != '%')
1770                 --fmt;          /* so %z outputs %z etc. */
1771             --buflen;
1772             continue;
1773         }
1774         if (base != 0) {
1775             str = num + sizeof(num);
1776             *--str = 0;
1777             while (str > num + neg) {
1778                 *--str = hexchars[val % base];
1779                 val = val / base;
1780                 if (--prec <= 0 && val == 0)
1781                     break;
1782             }
1783             switch (neg) {
1784             case 1:
1785                 *--str = '-';
1786                 break;
1787             case 2:
1788                 *--str = 'x';
1789                 *--str = '0';
1790                 break;
1791             }
1792             len = num + sizeof(num) - 1 - str;
1793         } else {
1794             len = strlen(str);
1795             if (prec > 0 && len > prec)
1796                 len = prec;
1797         }
1798         if (width > 0) {
1799             if (width > buflen)
1800                 width = buflen;
1801             if ((n = width - len) > 0) {
1802                 buflen -= n;
1803                 for (; n > 0; --n)
1804                     *buf++ = fillch;
1805             }
1806         }
1807         if (len > buflen)
1808             len = buflen;
1809         memcpy(buf, str, len);
1810         buf += len;
1811         buflen -= len;
1812     }
1813     *buf = 0;
1814     return buf - buf0;
1815 }
1816
1817 /*
1818  * script_setenv - set an environment variable value to be used
1819  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1820  */
1821 void
1822 script_setenv(var, value)
1823     char *var, *value;
1824 {
1825     size_t vl = strlen(var) + strlen(value) + 2;
1826     int i;
1827     char *p, *newstring;
1828
1829     newstring = (char *) malloc(vl);
1830     if (newstring == 0)
1831         return;
1832     slprintf(newstring, vl, "%s=%s", var, value);
1833
1834     /* check if this variable is already set */
1835     if (script_env != 0) {
1836         for (i = 0; (p = script_env[i]) != 0; ++i) {
1837             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1838                 free(p);
1839                 script_env[i] = newstring;
1840                 return;
1841             }
1842         }
1843     } else {
1844         i = 0;
1845         script_env = (char **) malloc(16 * sizeof(char *));
1846         if (script_env == 0)
1847             return;
1848         s_env_nalloc = 16;
1849     }
1850
1851     /* reallocate script_env with more space if needed */
1852     if (i + 1 >= s_env_nalloc) {
1853         int new_n = i + 17;
1854         char **newenv = (char **) realloc((void *)script_env,
1855                                           new_n * sizeof(char *));
1856         if (newenv == 0)
1857             return;
1858         script_env = newenv;
1859         s_env_nalloc = new_n;
1860     }
1861
1862     script_env[i] = newstring;
1863     script_env[i+1] = 0;
1864 }
1865
1866 /*
1867  * script_unsetenv - remove a variable from the environment
1868  * for scripts.
1869  */
1870 void
1871 script_unsetenv(var)
1872     char *var;
1873 {
1874     int vl = strlen(var);
1875     int i;
1876     char *p;
1877
1878     if (script_env == 0)
1879         return;
1880     for (i = 0; (p = script_env[i]) != 0; ++i) {
1881         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1882             free(p);
1883             while ((script_env[i] = script_env[i+1]) != 0)
1884                 ++i;
1885             break;
1886         }
1887     }
1888 }
1889
1890 /*
1891  * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
1892  * always leaves destination null-terminated (for len > 0).
1893  */
1894 void
1895 strlcpy(char *dest, size_t len, const char *src)
1896 {
1897     if (len == 0)
1898         return;
1899     if (strlen(src) < len)
1900         strcpy(dest, src);
1901     else {
1902         strncpy(dest, src, len - 1);
1903         dest[len-1] = 0;
1904     }
1905 }
1906
1907 /*
1908  * strlcat - like strcat/strncat, doesn't overflow destination buffer,
1909  * always leaves destination null-terminated (for len > 0).
1910  */
1911 void
1912 strlcat(char *dest, size_t len, const char *src)
1913 {
1914     size_t dlen;
1915
1916     if (len == 0)
1917         return;
1918     dlen = strlen(dest);
1919     if (dlen < len - 1)
1920         strlcpy(dest + dlen, len - dlen, src);
1921 }
1922
1923 /*
1924  * logit - does the hard work for fatal et al.
1925  */
1926 static void
1927 logit(level, fmt, args)
1928     int level;
1929     char *fmt;
1930     va_list args;
1931 {
1932     int n;
1933     char buf[256];
1934     static char nl = '\n';
1935
1936     n = vslprintf(buf, sizeof(buf), fmt, args);
1937     syslog(level, "%s", buf);
1938     if (log_to_stderr && (level != LOG_DEBUG || debug)) {
1939         if (write(2, buf, n) != n
1940             || (buf[n-1] != '\n' && write(2, &nl, 1) != 1))
1941             log_to_stderr = 0;
1942     }
1943 }
1944
1945 /*
1946  * fatal - log an error message and die horribly.
1947  */
1948 void
1949 fatal __V((char *fmt, ...))
1950 {
1951     va_list pvar;
1952
1953 #if __STDC__
1954     va_start(pvar, fmt);
1955 #else
1956     char *fmt;
1957     va_start(pvar);
1958     fmt = va_arg(pvar, char *);
1959 #endif
1960
1961     logit(LOG_ERR, fmt, pvar);
1962     va_end(pvar);
1963
1964     die(1);                     /* as promised */
1965 }
1966
1967 /*
1968  * error - log an error message.
1969  */
1970 void
1971 error __V((char *fmt, ...))
1972 {
1973     va_list pvar;
1974
1975 #if __STDC__
1976     va_start(pvar, fmt);
1977 #else
1978     char *fmt;
1979     va_start(pvar);
1980     fmt = va_arg(pvar, char *);
1981 #endif
1982
1983     logit(LOG_ERR, fmt, pvar);
1984     va_end(pvar);
1985 }
1986
1987 /*
1988  * warn - log a warning message.
1989  */
1990 void
1991 warn __V((char *fmt, ...))
1992 {
1993     va_list pvar;
1994
1995 #if __STDC__
1996     va_start(pvar, fmt);
1997 #else
1998     char *fmt;
1999     va_start(pvar);
2000     fmt = va_arg(pvar, char *);
2001 #endif
2002
2003     logit(LOG_WARNING, fmt, pvar);
2004     va_end(pvar);
2005 }
2006
2007 /*
2008  * notice - log a notice-level message.
2009  */
2010 void
2011 notice __V((char *fmt, ...))
2012 {
2013     va_list pvar;
2014
2015 #if __STDC__
2016     va_start(pvar, fmt);
2017 #else
2018     char *fmt;
2019     va_start(pvar);
2020     fmt = va_arg(pvar, char *);
2021 #endif
2022
2023     logit(LOG_NOTICE, fmt, pvar);
2024     va_end(pvar);
2025 }
2026
2027 /*
2028  * info - log an informational message.
2029  */
2030 void
2031 info __V((char *fmt, ...))
2032 {
2033     va_list pvar;
2034
2035 #if __STDC__
2036     va_start(pvar, fmt);
2037 #else
2038     char *fmt;
2039     va_start(pvar);
2040     fmt = va_arg(pvar, char *);
2041 #endif
2042
2043     logit(LOG_INFO, fmt, pvar);
2044     va_end(pvar);
2045 }
2046
2047 /*
2048  * dbglog - log a debug message.
2049  */
2050 void
2051 dbglog __V((char *fmt, ...))
2052 {
2053     va_list pvar;
2054
2055 #if __STDC__
2056     va_start(pvar, fmt);
2057 #else
2058     char *fmt;
2059     va_start(pvar);
2060     fmt = va_arg(pvar, char *);
2061 #endif
2062
2063     logit(LOG_DEBUG, fmt, pvar);
2064     va_end(pvar);
2065 }