]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
syslog -> notice/error/etc.
[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.60 1999/03/16 03:14:50 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
618     fail:
619         if (ttyfd >= 0)
620             close_tty();
621         if (locked) {
622             unlock();
623             locked = 0;
624         }
625
626         if (!demand) {
627             if (pidfilename[0] != 0
628                 && unlink(pidfilename) < 0 && errno != ENOENT) 
629                 warn("unable to delete pid file: %m");
630             pidfilename[0] = 0;
631         }
632
633         if (!persist)
634             break;
635
636         kill_link = 0;
637         if (demand)
638             demand_discard();
639         if (holdoff > 0 && need_holdoff) {
640             phase = PHASE_HOLDOFF;
641             TIMEOUT(holdoff_end, NULL, holdoff);
642             do {
643                 if (sigsetjmp(sigjmp, 1) == 0) {
644                     sigprocmask(SIG_BLOCK, &mask, NULL);
645                     if (kill_link) {
646                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
647                     } else {
648                         waiting = 1;
649                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
650                         wait_input(timeleft(&timo));
651                     }
652                 }
653                 waiting = 0;
654                 calltimeout();
655                 if (kill_link) {
656                     kill_link = 0;
657                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
658                 }
659                 reap_kids();
660             } while (phase == PHASE_HOLDOFF);
661             if (!persist)
662                 break;
663         }
664     }
665
666     /* Wait for scripts to finish */
667     while (n_children > 0)
668         reap_kids();
669
670     die(0);
671     return 0;
672 }
673
674 /*
675  * detach - detach us from the controlling terminal.
676  */
677 void
678 detach()
679 {
680     if (detached)
681         return;
682     if (daemon(0, 0) < 0) {
683         perror("Couldn't detach from controlling terminal");
684         die(1);
685     }
686     detached = 1;
687     log_to_stderr = 0;
688     pid = getpid();
689     /* update pid file if it has been written already */
690     if (pidfilename[0])
691         create_pidfile();
692 }
693
694 /*
695  * Create a file containing our process ID.
696  */
697 static void
698 create_pidfile()
699 {
700     FILE *pidfile;
701     char numbuf[16];
702
703     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
704              _PATH_VARRUN, ifname);
705     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
706         fprintf(pidfile, "%d\n", pid);
707         (void) fclose(pidfile);
708     } else {
709         error("Failed to create pid file %s: %m", pidfilename);
710         pidfilename[0] = 0;
711     }
712     slprintf(numbuf, sizeof(numbuf), "%d", pid);
713     script_setenv("PPPD_PID", numbuf);
714 }
715
716 /*
717  * holdoff_end - called via a timeout when the holdoff period ends.
718  */
719 static void
720 holdoff_end(arg)
721     void *arg;
722 {
723     phase = PHASE_DORMANT;
724 }
725
726 /*
727  * get_input - called when incoming data is available.
728  */
729 static void
730 get_input()
731 {
732     int len, i;
733     u_char *p;
734     u_short protocol;
735     struct protent *protp;
736
737     p = inpacket_buf;   /* point to beginning of packet buffer */
738
739     len = read_packet(inpacket_buf);
740     if (len < 0)
741         return;
742
743     if (len == 0) {
744         notice("Modem hangup");
745         hungup = 1;
746         lcp_lowerdown(0);       /* serial link is no longer available */
747         link_terminated(0);
748         return;
749     }
750
751     if (debug /*&& (debugflags & DBG_INPACKET)*/)
752         dbglog("rcvd %P", p, len);
753
754     if (len < PPP_HDRLEN) {
755         MAINDEBUG(("io(): Received short packet."));
756         return;
757     }
758
759     p += 2;                             /* Skip address and control */
760     GETSHORT(protocol, p);
761     len -= PPP_HDRLEN;
762
763     /*
764      * Toss all non-LCP packets unless LCP is OPEN.
765      */
766     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
767         MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
768         return;
769     }
770
771     /*
772      * Until we get past the authentication phase, toss all packets
773      * except LCP, LQR and authentication packets.
774      */
775     if (phase <= PHASE_AUTHENTICATE
776         && !(protocol == PPP_LCP || protocol == PPP_LQR
777              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
778         MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
779                    protocol, phase));
780         return;
781     }
782
783     /*
784      * Upcall the proper protocol input routine.
785      */
786     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
787         if (protp->protocol == protocol && protp->enabled_flag) {
788             (*protp->input)(0, p, len);
789             return;
790         }
791         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
792             && protp->datainput != NULL) {
793             (*protp->datainput)(0, p, len);
794             return;
795         }
796     }
797
798     if (debug)
799         warn("Unsupported protocol (0x%x) received", protocol);
800     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
801 }
802
803
804 /*
805  * quit - Clean up state and exit (with an error indication).
806  */
807 void 
808 quit()
809 {
810     die(1);
811 }
812
813 /*
814  * die - like quit, except we can specify an exit status.
815  */
816 void
817 die(status)
818     int status;
819 {
820     cleanup();
821     syslog(LOG_INFO, "Exit.");
822     exit(status);
823 }
824
825 /*
826  * cleanup - restore anything which needs to be restored before we exit
827  */
828 /* ARGSUSED */
829 static void
830 cleanup()
831 {
832     sys_cleanup();
833
834     if (ttyfd >= 0)
835         close_tty();
836
837     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
838         warn("unable to delete pid file: %m");
839     pidfilename[0] = 0;
840
841     if (locked)
842         unlock();
843 }
844
845 /*
846  * close_tty - restore the terminal device and close it.
847  */
848 static void
849 close_tty()
850 {
851     disestablish_ppp(ttyfd);
852
853     /* drop dtr to hang up */
854     if (!default_device && modem) {
855         hangup_modem(ttyfd);
856         /*
857          * This sleep is in case the serial port has CLOCAL set by default,
858          * and consequently will reassert DTR when we close the device.
859          */
860         sleep(1);
861     }
862
863     restore_tty(ttyfd);
864
865     if (tty_mode != (mode_t) -1) {
866         if (fchmod(ttyfd, tty_mode) != 0) {
867             /* XXX if devnam is a symlink, this will change the link */
868             chmod(devnam, tty_mode);
869         }
870     }
871
872     close(ttyfd);
873     ttyfd = -1;
874 }
875
876 /*
877  * hangup_modem - hang up the modem by clearing DTR.
878  */
879 void hangup_modem(ttyfd)
880     int ttyfd;
881 {
882     setdtr(ttyfd, 0);
883 }
884
885
886 struct  callout {
887     struct timeval      c_time;         /* time at which to call routine */
888     void                *c_arg;         /* argument to routine */
889     void                (*c_func) __P((void *)); /* routine */
890     struct              callout *c_next;
891 };
892
893 static struct callout *callout = NULL;  /* Callout list */
894 static struct timeval timenow;          /* Current time */
895
896 /*
897  * timeout - Schedule a timeout.
898  *
899  * Note that this timeout takes the number of seconds, NOT hz (as in
900  * the kernel).
901  */
902 void
903 timeout(func, arg, time)
904     void (*func) __P((void *));
905     void *arg;
906     int time;
907 {
908     struct callout *newp, *p, **pp;
909   
910     MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
911   
912     /*
913      * Allocate timeout.
914      */
915     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
916         fatal("Out of memory in timeout()!");
917     newp->c_arg = arg;
918     newp->c_func = func;
919     gettimeofday(&timenow, NULL);
920     newp->c_time.tv_sec = timenow.tv_sec + time;
921     newp->c_time.tv_usec = timenow.tv_usec;
922   
923     /*
924      * Find correct place and link it in.
925      */
926     for (pp = &callout; (p = *pp); pp = &p->c_next)
927         if (newp->c_time.tv_sec < p->c_time.tv_sec
928             || (newp->c_time.tv_sec == p->c_time.tv_sec
929                 && newp->c_time.tv_usec < p->c_time.tv_usec))
930             break;
931     newp->c_next = p;
932     *pp = newp;
933 }
934
935
936 /*
937  * untimeout - Unschedule a timeout.
938  */
939 void
940 untimeout(func, arg)
941     void (*func) __P((void *));
942     void *arg;
943 {
944     struct callout **copp, *freep;
945   
946     MAINDEBUG(("Untimeout %p:%p.", func, arg));
947   
948     /*
949      * Find first matching timeout and remove it from the list.
950      */
951     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
952         if (freep->c_func == func && freep->c_arg == arg) {
953             *copp = freep->c_next;
954             (void) free((char *) freep);
955             break;
956         }
957 }
958
959
960 /*
961  * calltimeout - Call any timeout routines which are now due.
962  */
963 static void
964 calltimeout()
965 {
966     struct callout *p;
967
968     while (callout != NULL) {
969         p = callout;
970
971         if (gettimeofday(&timenow, NULL) < 0)
972             fatal("Failed to get time of day: %m");
973         if (!(p->c_time.tv_sec < timenow.tv_sec
974               || (p->c_time.tv_sec == timenow.tv_sec
975                   && p->c_time.tv_usec <= timenow.tv_usec)))
976             break;              /* no, it's not time yet */
977
978         callout = p->c_next;
979         (*p->c_func)(p->c_arg);
980
981         free((char *) p);
982     }
983 }
984
985
986 /*
987  * timeleft - return the length of time until the next timeout is due.
988  */
989 static struct timeval *
990 timeleft(tvp)
991     struct timeval *tvp;
992 {
993     if (callout == NULL)
994         return NULL;
995
996     gettimeofday(&timenow, NULL);
997     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
998     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
999     if (tvp->tv_usec < 0) {
1000         tvp->tv_usec += 1000000;
1001         tvp->tv_sec -= 1;
1002     }
1003     if (tvp->tv_sec < 0)
1004         tvp->tv_sec = tvp->tv_usec = 0;
1005
1006     return tvp;
1007 }
1008
1009
1010 /*
1011  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1012  */
1013 static void
1014 kill_my_pg(sig)
1015     int sig;
1016 {
1017     struct sigaction act, oldact;
1018
1019     act.sa_handler = SIG_IGN;
1020     act.sa_flags = 0;
1021     kill(0, sig);
1022     sigaction(sig, &act, &oldact);
1023     sigaction(sig, &oldact, NULL);
1024 }
1025
1026
1027 /*
1028  * hup - Catch SIGHUP signal.
1029  *
1030  * Indicates that the physical layer has been disconnected.
1031  * We don't rely on this indication; if the user has sent this
1032  * signal, we just take the link down.
1033  */
1034 static void
1035 hup(sig)
1036     int sig;
1037 {
1038     info("Hangup (SIGHUP)");
1039     kill_link = 1;
1040     if (conn_running)
1041         /* Send the signal to the [dis]connector process(es) also */
1042         kill_my_pg(sig);
1043     if (waiting)
1044         siglongjmp(sigjmp, 1);
1045 }
1046
1047
1048 /*
1049  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1050  *
1051  * Indicates that we should initiate a graceful disconnect and exit.
1052  */
1053 /*ARGSUSED*/
1054 static void
1055 term(sig)
1056     int sig;
1057 {
1058     info("Terminating on signal %d.", sig);
1059     persist = 0;                /* don't try to restart */
1060     kill_link = 1;
1061     if (conn_running)
1062         /* Send the signal to the [dis]connector process(es) also */
1063         kill_my_pg(sig);
1064     if (waiting)
1065         siglongjmp(sigjmp, 1);
1066 }
1067
1068
1069 /*
1070  * chld - Catch SIGCHLD signal.
1071  * Calls reap_kids to get status for any dead kids.
1072  */
1073 static void
1074 chld(sig)
1075     int sig;
1076 {
1077     if (waiting)
1078         siglongjmp(sigjmp, 1);
1079 }
1080
1081
1082 /*
1083  * toggle_debug - Catch SIGUSR1 signal.
1084  *
1085  * Toggle debug flag.
1086  */
1087 /*ARGSUSED*/
1088 static void
1089 toggle_debug(sig)
1090     int sig;
1091 {
1092     debug = !debug;
1093     if (debug) {
1094         setlogmask(LOG_UPTO(LOG_DEBUG));
1095     } else {
1096         setlogmask(LOG_UPTO(LOG_WARNING));
1097     }
1098 }
1099
1100
1101 /*
1102  * open_ccp - Catch SIGUSR2 signal.
1103  *
1104  * Try to (re)negotiate compression.
1105  */
1106 /*ARGSUSED*/
1107 static void
1108 open_ccp(sig)
1109     int sig;
1110 {
1111     open_ccp_flag = 1;
1112     if (waiting)
1113         siglongjmp(sigjmp, 1);
1114 }
1115
1116
1117 /*
1118  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1119  */
1120 static void
1121 bad_signal(sig)
1122     int sig;
1123 {
1124     static int crashed = 0;
1125
1126     if (crashed)
1127         _exit(127);
1128     crashed = 1;
1129     error("Fatal signal %d", sig);
1130     if (conn_running)
1131         kill_my_pg(SIGTERM);
1132     die(1);
1133 }
1134
1135
1136 /*
1137  * device_script - run a program to connect or disconnect the
1138  * serial device.
1139  */
1140 static int
1141 device_script(program, in, out)
1142     char *program;
1143     int in, out;
1144 {
1145     int pid;
1146     int status;
1147     int errfd;
1148
1149     conn_running = 1;
1150     pid = fork();
1151
1152     if (pid < 0) {
1153         conn_running = 0;
1154         fatal("Failed to create child process: %m");
1155     }
1156
1157     if (pid == 0) {
1158         sys_close();
1159         closelog();
1160         if (in == out) {
1161             if (in != 0) {
1162                 dup2(in, 0);
1163                 close(in);
1164             }
1165             dup2(0, 1);
1166         } else {
1167             if (out == 0)
1168                 out = dup(out);
1169             if (in != 0) {
1170                 dup2(in, 0);
1171                 close(in);
1172             }
1173             if (out != 1) {
1174                 dup2(out, 1);
1175                 close(out);
1176             }
1177         }
1178         if (!nodetach && !updetach) {
1179             close(2);
1180             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1181             if (errfd >= 0 && errfd != 2) {
1182                 dup2(errfd, 2);
1183                 close(errfd);
1184             }
1185         }
1186         setuid(uid);
1187         if (getuid() != uid) {
1188             error("setuid failed");
1189             exit(1);
1190         }
1191         setgid(getgid());
1192         execl("/bin/sh", "sh", "-c", program, (char *)0);
1193         error("could not exec /bin/sh: %m");
1194         exit(99);
1195         /* NOTREACHED */
1196     }
1197
1198     while (waitpid(pid, &status, 0) < 0) {
1199         if (errno == EINTR)
1200             continue;
1201         fatal("error waiting for (dis)connection process: %m");
1202     }
1203     conn_running = 0;
1204
1205     return (status == 0 ? 0 : -1);
1206 }
1207
1208
1209 /*
1210  * We maintain a list of child process pids and
1211  * functions to call when they exit.
1212  */
1213 struct subprocess {
1214     pid_t       pid;
1215     char        *prog;
1216     void        (*done) __P((void *));
1217     void        *arg;
1218     struct subprocess *next;
1219 };
1220
1221 struct subprocess *children;
1222
1223 /*
1224  * run-program - execute a program with given arguments,
1225  * but don't wait for it.
1226  * If the program can't be executed, logs an error unless
1227  * must_exist is 0 and the program file doesn't exist.
1228  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1229  * or isn't an executable plain file, or the process ID of the child.
1230  * If done != NULL, (*done)(arg) will be called later (within
1231  * reap_kids) iff the return value is > 0.
1232  */
1233 pid_t
1234 run_program(prog, args, must_exist, done, arg)
1235     char *prog;
1236     char **args;
1237     int must_exist;
1238     void (*done) __P((void *));
1239     void *arg;
1240 {
1241     int pid;
1242     struct subprocess *chp;
1243     struct stat sbuf;
1244
1245     /*
1246      * First check if the file exists and is executable.
1247      * We don't use access() because that would use the
1248      * real user-id, which might not be root, and the script
1249      * might be accessible only to root.
1250      */
1251     errno = EINVAL;
1252     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1253         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1254         if (must_exist || errno != ENOENT)
1255             warn("Can't execute %s: %m", prog);
1256         return 0;
1257     }
1258
1259     pid = fork();
1260     if (pid == -1)
1261         fatal("Failed to create child process for %s: %m", prog);
1262     if (pid == 0) {
1263         int new_fd;
1264
1265         /* Leave the current location */
1266         (void) setsid();        /* No controlling tty. */
1267         (void) umask (S_IRWXG|S_IRWXO);
1268         (void) chdir ("/");     /* no current directory. */
1269         setuid(0);              /* set real UID = root */
1270         setgid(getegid());
1271
1272         /* Ensure that nothing of our device environment is inherited. */
1273         sys_close();
1274         closelog();
1275         close (0);
1276         close (1);
1277         close (2);
1278         close (ttyfd);  /* tty interface to the ppp device */
1279
1280         /* Don't pass handles to the PPP device, even by accident. */
1281         new_fd = open (_PATH_DEVNULL, O_RDWR);
1282         if (new_fd >= 0) {
1283             if (new_fd != 0) {
1284                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1285                 close (new_fd);
1286             }
1287             dup2 (0, 1); /* stdout -> /dev/null */
1288             dup2 (0, 2); /* stderr -> /dev/null */
1289         }
1290
1291 #ifdef BSD
1292         /* Force the priority back to zero if pppd is running higher. */
1293         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1294             warn("can't reset priority to 0: %m"); 
1295 #endif
1296
1297         /* SysV recommends a second fork at this point. */
1298
1299         /* run the program */
1300         execve(prog, args, script_env);
1301         if (must_exist || errno != ENOENT)
1302             warn("Can't execute %s: %m", prog);
1303         _exit(-1);
1304     }
1305
1306     if (debug)
1307         dbglog("Script %s started; pid = %d", prog, pid);
1308     ++n_children;
1309
1310     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1311     if (chp == NULL) {
1312         warn("losing track of %s process", prog);
1313     } else {
1314         chp->pid = pid;
1315         chp->prog = prog;
1316         chp->done = done;
1317         chp->arg = arg;
1318         chp->next = children;
1319         children = chp;
1320     }
1321
1322     return pid;
1323 }
1324
1325
1326 /*
1327  * reap_kids - get status from any dead child processes,
1328  * and log a message for abnormal terminations.
1329  */
1330 static void
1331 reap_kids()
1332 {
1333     int pid, status;
1334     struct subprocess *chp, **prevp;
1335
1336     if (n_children == 0)
1337         return;
1338     while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1339         --n_children;
1340         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1341             if (chp->pid == pid)
1342                 break;
1343         if (debug)
1344             dbglog("process %d (%s) finished, status = 0x%x",
1345                    pid, (chp? chp->prog: "??"), status);
1346         if (WIFSIGNALED(status)) {
1347             warn("Child process %s (pid %d) terminated with signal %d",
1348                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1349         }
1350         if (chp && chp->done)
1351             (*chp->done)(chp->arg);
1352     }
1353     if (pid == -1 && errno != ECHILD)
1354         error("Error waiting for child process: %m");
1355 }
1356
1357
1358 /*
1359  * log_packet - format a packet and log it.
1360  */
1361
1362 char line[256];                 /* line to be logged accumulated here */
1363 char *linep;
1364
1365 void
1366 log_packet(p, len, prefix, level)
1367     u_char *p;
1368     int len;
1369     char *prefix;
1370     int level;
1371 {
1372     strlcpy(line, sizeof(line), prefix);
1373     linep = line + strlen(line);
1374     format_packet(p, len, pr_log, NULL);
1375     if (linep != line)
1376         syslog(level, "%s", line);
1377 }
1378
1379 /*
1380  * format_packet - make a readable representation of a packet,
1381  * calling `printer(arg, format, ...)' to output it.
1382  */
1383 void
1384 format_packet(p, len, printer, arg)
1385     u_char *p;
1386     int len;
1387     void (*printer) __P((void *, char *, ...));
1388     void *arg;
1389 {
1390     int i, n;
1391     u_short proto;
1392     u_char x;
1393     struct protent *protp;
1394
1395     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1396         p += 2;
1397         GETSHORT(proto, p);
1398         len -= PPP_HDRLEN;
1399         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1400             if (proto == protp->protocol)
1401                 break;
1402         if (protp != NULL) {
1403             printer(arg, "[%s", protp->name);
1404             n = (*protp->printpkt)(p, len, printer, arg);
1405             printer(arg, "]");
1406             p += n;
1407             len -= n;
1408         } else {
1409             printer(arg, "[proto=0x%x]", proto);
1410         }
1411     }
1412
1413     for (i = 0; i < len && i < 32; ++i) {
1414         GETCHAR(x, p);
1415         printer(arg, " %.2x", x);
1416     }
1417     if (i < len)
1418         printer(arg, " ...");
1419 }
1420
1421 static void
1422 pr_log __V((void *arg, char *fmt, ...))
1423 {
1424     int n;
1425     va_list pvar;
1426     char buf[256];
1427
1428 #if __STDC__
1429     va_start(pvar, fmt);
1430 #else
1431     void *arg;
1432     char *fmt;
1433     va_start(pvar);
1434     arg = va_arg(pvar, void *);
1435     fmt = va_arg(pvar, char *);
1436 #endif
1437
1438     n = vslprintf(buf, sizeof(buf), fmt, pvar);
1439     va_end(pvar);
1440
1441     if (linep + n + 1 > line + sizeof(line)) {
1442         syslog(LOG_DEBUG, "%s", line);
1443         linep = line;
1444     }
1445     strlcpy(linep, line + sizeof(line) - linep, buf);
1446     linep += n;
1447 }
1448
1449 /*
1450  * vslp_printer - used in processing a %P format
1451  */
1452 struct buffer_info {
1453     char *ptr;
1454     int len;
1455 };
1456
1457 static void
1458 vslp_printer __V((void *arg, char *fmt, ...))
1459 {
1460     int n;
1461     va_list pvar;
1462     struct buffer_info *bi;
1463
1464 #if __STDC__
1465     va_start(pvar, fmt);
1466 #else
1467     void *arg;
1468     char *fmt;
1469     va_start(pvar);
1470     arg = va_arg(pvar, void *);
1471     fmt = va_arg(pvar, char *);
1472 #endif
1473
1474     bi = (struct buffer_info *) arg;
1475     n = vslprintf(bi->ptr, bi->len, fmt, pvar);
1476     va_end(pvar);
1477
1478     bi->ptr += n;
1479     bi->len -= n;
1480 }
1481
1482 /*
1483  * print_string - print a readable representation of a string using
1484  * printer.
1485  */
1486 void
1487 print_string(p, len, printer, arg)
1488     char *p;
1489     int len;
1490     void (*printer) __P((void *, char *, ...));
1491     void *arg;
1492 {
1493     int c;
1494
1495     printer(arg, "\"");
1496     for (; len > 0; --len) {
1497         c = *p++;
1498         if (' ' <= c && c <= '~') {
1499             if (c == '\\' || c == '"')
1500                 printer(arg, "\\");
1501             printer(arg, "%c", c);
1502         } else {
1503             switch (c) {
1504             case '\n':
1505                 printer(arg, "\\n");
1506                 break;
1507             case '\r':
1508                 printer(arg, "\\r");
1509                 break;
1510             case '\t':
1511                 printer(arg, "\\t");
1512                 break;
1513             default:
1514                 printer(arg, "\\%.3o", c);
1515             }
1516         }
1517     }
1518     printer(arg, "\"");
1519 }
1520
1521 /*
1522  * novm - log an error message saying we ran out of memory, and die.
1523  */
1524 void
1525 novm(msg)
1526     char *msg;
1527 {
1528     fatal("Virtual memory exhausted allocating %s\n", msg);
1529 }
1530
1531 /*
1532  * slprintf - format a message into a buffer.  Like sprintf except we
1533  * also specify the length of the output buffer, and we handle
1534  * %r (recursive format), %m (error message), %v (visible string),
1535  * %q (quoted string), %t (current time) and %I (IP address) formats.
1536  * Doesn't do floating-point formats.
1537  * Returns the number of chars put into buf.
1538  */
1539 int
1540 slprintf __V((char *buf, int buflen, char *fmt, ...))
1541 {
1542     va_list args;
1543     int n;
1544
1545 #if __STDC__
1546     va_start(args, fmt);
1547 #else
1548     char *buf;
1549     int buflen;
1550     char *fmt;
1551     va_start(args);
1552     buf = va_arg(args, char *);
1553     buflen = va_arg(args, int);
1554     fmt = va_arg(args, char *);
1555 #endif
1556     n = vslprintf(buf, buflen, fmt, args);
1557     va_end(args);
1558     return n;
1559 }
1560
1561 /*
1562  * vslprintf - like slprintf, takes a va_list instead of a list of args.
1563  */
1564 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1565
1566 int
1567 vslprintf(buf, buflen, fmt, args)
1568     char *buf;
1569     int buflen;
1570     char *fmt;
1571     va_list args;
1572 {
1573     int c, i, n;
1574     int width, prec, fillch;
1575     int base, len, neg, quoted;
1576     unsigned long val = 0;
1577     char *str, *f, *buf0;
1578     unsigned char *p;
1579     char num[32];
1580     time_t t;
1581     u_int32_t ip;
1582     static char hexchars[] = "0123456789abcdef";
1583     struct buffer_info bufinfo;
1584
1585     buf0 = buf;
1586     --buflen;
1587     while (buflen > 0) {
1588         for (f = fmt; *f != '%' && *f != 0; ++f)
1589             ;
1590         if (f > fmt) {
1591             len = f - fmt;
1592             if (len > buflen)
1593                 len = buflen;
1594             memcpy(buf, fmt, len);
1595             buf += len;
1596             buflen -= len;
1597             fmt = f;
1598         }
1599         if (*fmt == 0)
1600             break;
1601         c = *++fmt;
1602         width = prec = 0;
1603         fillch = ' ';
1604         if (c == '0') {
1605             fillch = '0';
1606             c = *++fmt;
1607         }
1608         if (c == '*') {
1609             width = va_arg(args, int);
1610             c = *++fmt;
1611         } else {
1612             while (isdigit(c)) {
1613                 width = width * 10 + c - '0';
1614                 c = *++fmt;
1615             }
1616         }
1617         if (c == '.') {
1618             c = *++fmt;
1619             if (c == '*') {
1620                 prec = va_arg(args, int);
1621                 c = *++fmt;
1622             } else {
1623                 while (isdigit(c)) {
1624                     prec = prec * 10 + c - '0';
1625                     c = *++fmt;
1626                 }
1627             }
1628         }
1629         str = 0;
1630         base = 0;
1631         neg = 0;
1632         ++fmt;
1633         switch (c) {
1634         case 'd':
1635             i = va_arg(args, int);
1636             if (i < 0) {
1637                 neg = 1;
1638                 val = -i;
1639             } else
1640                 val = i;
1641             base = 10;
1642             break;
1643         case 'o':
1644             val = va_arg(args, unsigned int);
1645             base = 8;
1646             break;
1647         case 'x':
1648         case 'X':
1649             val = va_arg(args, unsigned int);
1650             base = 16;
1651             break;
1652         case 'p':
1653             val = (unsigned long) va_arg(args, void *);
1654             base = 16;
1655             neg = 2;
1656             break;
1657         case 's':
1658             str = va_arg(args, char *);
1659             break;
1660         case 'c':
1661             num[0] = va_arg(args, int);
1662             num[1] = 0;
1663             str = num;
1664             break;
1665         case 'm':
1666             str = strerror(errno);
1667             break;
1668         case 'I':
1669             ip = va_arg(args, u_int32_t);
1670             ip = ntohl(ip);
1671             slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
1672                      (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
1673             str = num;
1674             break;
1675         case 'r':
1676             f = va_arg(args, char *);
1677 #ifndef __powerpc__
1678             n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1679 #else
1680             /* On the powerpc, a va_list is an array of 1 structure */
1681             n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1682 #endif
1683             buf += n;
1684             buflen -= n;
1685             continue;
1686         case 't':
1687             time(&t);
1688             str = ctime(&t);
1689             str += 4;           /* chop off the day name */
1690             str[15] = 0;        /* chop off year and newline */
1691             break;
1692         case 'v':               /* "visible" string */
1693         case 'q':               /* quoted string */
1694             quoted = c == 'q';
1695             p = va_arg(args, unsigned char *);
1696             if (fillch == '0' && prec > 0) {
1697                 n = prec;
1698             } else {
1699                 n = strlen((char *)p);
1700                 if (prec > 0 && prec < n)
1701                     n = prec;
1702             }
1703             while (n > 0 && buflen > 0) {
1704                 c = *p++;
1705                 --n;
1706                 if (!quoted && c >= 0x80) {
1707                     OUTCHAR('M');
1708                     OUTCHAR('-');
1709                     c -= 0x80;
1710                 }
1711                 if (quoted && (c == '"' || c == '\\'))
1712                     OUTCHAR('\\');
1713                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1714                     if (quoted) {
1715                         OUTCHAR('\\');
1716                         switch (c) {
1717                         case '\t':      OUTCHAR('t');   break;
1718                         case '\n':      OUTCHAR('n');   break;
1719                         case '\b':      OUTCHAR('b');   break;
1720                         case '\f':      OUTCHAR('f');   break;
1721                         default:
1722                             OUTCHAR('x');
1723                             OUTCHAR(hexchars[c >> 4]);
1724                             OUTCHAR(hexchars[c & 0xf]);
1725                         }
1726                     } else {
1727                         if (c == '\t')
1728                             OUTCHAR(c);
1729                         else {
1730                             OUTCHAR('^');
1731                             OUTCHAR(c ^ 0x40);
1732                         }
1733                     }
1734                 } else
1735                     OUTCHAR(c);
1736             }
1737             continue;
1738         case 'P':               /* print PPP packet */
1739             bufinfo.ptr = buf;
1740             bufinfo.len = buflen + 1;
1741             p = va_arg(args, unsigned char *);
1742             n = va_arg(args, int);
1743             format_packet(p, n, vslp_printer, &bufinfo);
1744             buf = bufinfo.ptr;
1745             buflen = bufinfo.len - 1;
1746             continue;
1747         case 'B':
1748             p = va_arg(args, unsigned char *);
1749             for (n = prec; n > 0; --n) {
1750                 c = *p++;
1751                 if (fillch == ' ')
1752                     OUTCHAR(' ');
1753                 OUTCHAR(hexchars[(c >> 4) & 0xf]);
1754                 OUTCHAR(hexchars[c & 0xf]);
1755             }
1756             continue;
1757         default:
1758             *buf++ = '%';
1759             if (c != '%')
1760                 --fmt;          /* so %z outputs %z etc. */
1761             --buflen;
1762             continue;
1763         }
1764         if (base != 0) {
1765             str = num + sizeof(num);
1766             *--str = 0;
1767             while (str > num + neg) {
1768                 *--str = hexchars[val % base];
1769                 val = val / base;
1770                 if (--prec <= 0 && val == 0)
1771                     break;
1772             }
1773             switch (neg) {
1774             case 1:
1775                 *--str = '-';
1776                 break;
1777             case 2:
1778                 *--str = 'x';
1779                 *--str = '0';
1780                 break;
1781             }
1782             len = num + sizeof(num) - 1 - str;
1783         } else {
1784             len = strlen(str);
1785             if (prec > 0 && len > prec)
1786                 len = prec;
1787         }
1788         if (width > 0) {
1789             if (width > buflen)
1790                 width = buflen;
1791             if ((n = width - len) > 0) {
1792                 buflen -= n;
1793                 for (; n > 0; --n)
1794                     *buf++ = fillch;
1795             }
1796         }
1797         if (len > buflen)
1798             len = buflen;
1799         memcpy(buf, str, len);
1800         buf += len;
1801         buflen -= len;
1802     }
1803     *buf = 0;
1804     return buf - buf0;
1805 }
1806
1807 /*
1808  * script_setenv - set an environment variable value to be used
1809  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1810  */
1811 void
1812 script_setenv(var, value)
1813     char *var, *value;
1814 {
1815     size_t vl = strlen(var) + strlen(value) + 2;
1816     int i;
1817     char *p, *newstring;
1818
1819     newstring = (char *) malloc(vl);
1820     if (newstring == 0)
1821         return;
1822     slprintf(newstring, vl, "%s=%s", var, value);
1823
1824     /* check if this variable is already set */
1825     if (script_env != 0) {
1826         for (i = 0; (p = script_env[i]) != 0; ++i) {
1827             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1828                 free(p);
1829                 script_env[i] = newstring;
1830                 return;
1831             }
1832         }
1833     } else {
1834         i = 0;
1835         script_env = (char **) malloc(16 * sizeof(char *));
1836         if (script_env == 0)
1837             return;
1838         s_env_nalloc = 16;
1839     }
1840
1841     /* reallocate script_env with more space if needed */
1842     if (i + 1 >= s_env_nalloc) {
1843         int new_n = i + 17;
1844         char **newenv = (char **) realloc((void *)script_env,
1845                                           new_n * sizeof(char *));
1846         if (newenv == 0)
1847             return;
1848         script_env = newenv;
1849         s_env_nalloc = new_n;
1850     }
1851
1852     script_env[i] = newstring;
1853     script_env[i+1] = 0;
1854 }
1855
1856 /*
1857  * script_unsetenv - remove a variable from the environment
1858  * for scripts.
1859  */
1860 void
1861 script_unsetenv(var)
1862     char *var;
1863 {
1864     int vl = strlen(var);
1865     int i;
1866     char *p;
1867
1868     if (script_env == 0)
1869         return;
1870     for (i = 0; (p = script_env[i]) != 0; ++i) {
1871         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1872             free(p);
1873             while ((script_env[i] = script_env[i+1]) != 0)
1874                 ++i;
1875             break;
1876         }
1877     }
1878 }
1879
1880 /*
1881  * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
1882  * always leaves destination null-terminated (for len > 0).
1883  */
1884 void
1885 strlcpy(char *dest, size_t len, const char *src)
1886 {
1887     if (len == 0)
1888         return;
1889     if (strlen(src) < len)
1890         strcpy(dest, src);
1891     else {
1892         strncpy(dest, src, len - 1);
1893         dest[len-1] = 0;
1894     }
1895 }
1896
1897 /*
1898  * strlcat - like strcat/strncat, doesn't overflow destination buffer,
1899  * always leaves destination null-terminated (for len > 0).
1900  */
1901 void
1902 strlcat(char *dest, size_t len, const char *src)
1903 {
1904     size_t dlen;
1905
1906     if (len == 0)
1907         return;
1908     dlen = strlen(dest);
1909     if (dlen < len - 1)
1910         strlcpy(dest + dlen, len - dlen, src);
1911 }
1912
1913 /*
1914  * logit - does the hard work for fatal et al.
1915  */
1916 static void
1917 logit(level, fmt, args)
1918     int level;
1919     char *fmt;
1920     va_list args;
1921 {
1922     int n;
1923     char buf[256];
1924     static char nl = '\n';
1925
1926     n = vslprintf(buf, sizeof(buf), fmt, args);
1927     syslog(level, "%s", buf);
1928     if (log_to_stderr && (level != LOG_DEBUG || debug)) {
1929         if (write(2, buf, n) != n
1930             || (buf[n-1] != '\n' && write(2, &nl, 1) != 1))
1931             log_to_stderr = 0;
1932     }
1933 }
1934
1935 /*
1936  * fatal - log an error message and die horribly.
1937  */
1938 void
1939 fatal __V((char *fmt, ...))
1940 {
1941     va_list pvar;
1942
1943 #if __STDC__
1944     va_start(pvar, fmt);
1945 #else
1946     char *fmt;
1947     va_start(pvar);
1948     fmt = va_arg(pvar, char *);
1949 #endif
1950
1951     logit(LOG_ERR, fmt, pvar);
1952     va_end(pvar);
1953
1954     die(1);                     /* as promised */
1955 }
1956
1957 /*
1958  * error - log an error message.
1959  */
1960 void
1961 error __V((char *fmt, ...))
1962 {
1963     va_list pvar;
1964
1965 #if __STDC__
1966     va_start(pvar, fmt);
1967 #else
1968     char *fmt;
1969     va_start(pvar);
1970     fmt = va_arg(pvar, char *);
1971 #endif
1972
1973     logit(LOG_ERR, fmt, pvar);
1974     va_end(pvar);
1975 }
1976
1977 /*
1978  * warn - log a warning message.
1979  */
1980 void
1981 warn __V((char *fmt, ...))
1982 {
1983     va_list pvar;
1984
1985 #if __STDC__
1986     va_start(pvar, fmt);
1987 #else
1988     char *fmt;
1989     va_start(pvar);
1990     fmt = va_arg(pvar, char *);
1991 #endif
1992
1993     logit(LOG_WARNING, fmt, pvar);
1994     va_end(pvar);
1995 }
1996
1997 /*
1998  * notice - log a notice-level message.
1999  */
2000 void
2001 notice __V((char *fmt, ...))
2002 {
2003     va_list pvar;
2004
2005 #if __STDC__
2006     va_start(pvar, fmt);
2007 #else
2008     char *fmt;
2009     va_start(pvar);
2010     fmt = va_arg(pvar, char *);
2011 #endif
2012
2013     logit(LOG_NOTICE, fmt, pvar);
2014     va_end(pvar);
2015 }
2016
2017 /*
2018  * info - log an informational message.
2019  */
2020 void
2021 info __V((char *fmt, ...))
2022 {
2023     va_list pvar;
2024
2025 #if __STDC__
2026     va_start(pvar, fmt);
2027 #else
2028     char *fmt;
2029     va_start(pvar);
2030     fmt = va_arg(pvar, char *);
2031 #endif
2032
2033     logit(LOG_INFO, fmt, pvar);
2034     va_end(pvar);
2035 }
2036
2037 /*
2038  * dbglog - log a debug message.
2039  */
2040 void
2041 dbglog __V((char *fmt, ...))
2042 {
2043     va_list pvar;
2044
2045 #if __STDC__
2046     va_start(pvar, fmt);
2047 #else
2048     char *fmt;
2049     va_start(pvar);
2050     fmt = va_arg(pvar, char *);
2051 #endif
2052
2053     logit(LOG_DEBUG, fmt, pvar);
2054     va_end(pvar);
2055 }