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