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