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