]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
open the device as the user unless the device name came from a
[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.55 1999/03/02 05:59:21 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 int conn_running;        /* we have a [dis]connector running */
81
82 int ttyfd = -1;                 /* Serial port file descriptor */
83 mode_t tty_mode = -1;           /* Original access permissions to tty */
84 int baud_rate;                  /* Actual bits/second for serial device */
85 int hungup;                     /* terminal has been hung up */
86 int privileged;                 /* we're running as real uid root */
87 int uid;                        /* real user ID of the user */
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     setuid(0);                  /* make real uid = root */
235
236     if (!ppp_available()) {
237         option_error(no_ppp_msg);
238         exit(1);
239     }
240
241     /*
242      * Check that the options given are valid and consistent.
243      */
244     if (!sys_check_options())
245         exit(1);
246     auth_check_options();
247     for (i = 0; (protp = protocols[i]) != NULL; ++i)
248         if (protp->check_options != NULL)
249             (*protp->check_options)();
250     if (demand && connector == 0) {
251         option_error("connect script is required for demand-dialling\n");
252         exit(1);
253     }
254
255     script_setenv("DEVICE", devnam);
256     sprintf(numbuf, "%d", baud_rate);
257     script_setenv("SPEED", numbuf);
258
259     /*
260      * If the user has specified the default device name explicitly,
261      * pretend they hadn't.
262      */
263     if (!default_device && strcmp(devnam, default_devnam) == 0)
264         default_device = 1;
265     if (default_device)
266         nodetach = 1;
267
268     /*
269      * Initialize system-dependent stuff and magic number package.
270      */
271     sys_init();
272     magic_init();
273     if (debug)
274         setlogmask(LOG_UPTO(LOG_DEBUG));
275
276     /*
277      * Detach ourselves from the terminal, if required,
278      * and identify who is running us.
279      */
280     if (!nodetach && !updetach)
281         detach();
282     pid = getpid();
283     p = getlogin();
284     if (p == NULL) {
285         pw = getpwuid(uid);
286         if (pw != NULL && pw->pw_name != NULL)
287             p = pw->pw_name;
288         else
289             p = "(unknown)";
290     }
291     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
292            VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
293   
294     /*
295      * Compute mask of all interesting signals and install signal handlers
296      * for each.  Only one signal handler may be active at a time.  Therefore,
297      * all other signals should be masked when any handler is executing.
298      */
299     sigemptyset(&mask);
300     sigaddset(&mask, SIGHUP);
301     sigaddset(&mask, SIGINT);
302     sigaddset(&mask, SIGTERM);
303     sigaddset(&mask, SIGCHLD);
304     sigaddset(&mask, SIGUSR2);
305
306 #define SIGNAL(s, handler)      { \
307         sa.sa_handler = handler; \
308         if (sigaction(s, &sa, NULL) < 0) { \
309             syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
310             exit(1); \
311         } \
312     }
313
314     sa.sa_mask = mask;
315     sa.sa_flags = 0;
316     SIGNAL(SIGHUP, hup);                /* Hangup */
317     SIGNAL(SIGINT, term);               /* Interrupt */
318     SIGNAL(SIGTERM, term);              /* Terminate */
319     SIGNAL(SIGCHLD, chld);
320
321     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
322     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
323
324     /*
325      * Install a handler for other signals which would otherwise
326      * cause pppd to exit without cleaning up.
327      */
328     SIGNAL(SIGABRT, bad_signal);
329     SIGNAL(SIGALRM, bad_signal);
330     SIGNAL(SIGFPE, bad_signal);
331     SIGNAL(SIGILL, bad_signal);
332     SIGNAL(SIGPIPE, bad_signal);
333     SIGNAL(SIGQUIT, bad_signal);
334     SIGNAL(SIGSEGV, bad_signal);
335 #ifdef SIGBUS
336     SIGNAL(SIGBUS, bad_signal);
337 #endif
338 #ifdef SIGEMT
339     SIGNAL(SIGEMT, bad_signal);
340 #endif
341 #ifdef SIGPOLL
342     SIGNAL(SIGPOLL, bad_signal);
343 #endif
344 #ifdef SIGPROF
345     SIGNAL(SIGPROF, bad_signal);
346 #endif
347 #ifdef SIGSYS
348     SIGNAL(SIGSYS, bad_signal);
349 #endif
350 #ifdef SIGTRAP
351     SIGNAL(SIGTRAP, bad_signal);
352 #endif
353 #ifdef SIGVTALRM
354     SIGNAL(SIGVTALRM, bad_signal);
355 #endif
356 #ifdef SIGXCPU
357     SIGNAL(SIGXCPU, bad_signal);
358 #endif
359 #ifdef SIGXFSZ
360     SIGNAL(SIGXFSZ, bad_signal);
361 #endif
362
363     /*
364      * Apparently we can get a SIGPIPE when we call syslog, if
365      * syslogd has died and been restarted.  Ignoring it seems
366      * be sufficient.
367      */
368     signal(SIGPIPE, SIG_IGN);
369
370     waiting = 0;
371     sigprocmask(SIG_BLOCK, &mask, NULL);
372
373     /*
374      * If we're doing dial-on-demand, set up the interface now.
375      */
376     if (demand) {
377         /*
378          * Open the loopback channel and set it up to be the ppp interface.
379          */
380         open_ppp_loopback();
381
382         syslog(LOG_INFO, "Using interface ppp%d", ifunit);
383         (void) sprintf(ifname, "ppp%d", ifunit);
384         script_setenv("IFNAME", ifname);
385
386         create_pidfile();       /* write pid to file */
387
388         /*
389          * Configure the interface and mark it up, etc.
390          */
391         demand_conf();
392     }
393
394     for (;;) {
395
396         need_holdoff = 1;
397
398         if (demand) {
399             /*
400              * Don't do anything until we see some activity.
401              */
402             phase = PHASE_DORMANT;
403             kill_link = 0;
404             demand_unblock();
405             for (;;) {
406                 if (setjmp(sigjmp) == 0) {
407                     waiting = 1;
408                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
409                     wait_loop_output(timeleft(&timo));
410                 }
411                 sigprocmask(SIG_BLOCK, &mask, NULL);
412                 waiting = 0;
413                 calltimeout();
414                 if (kill_link) {
415                     if (!persist)
416                         break;
417                     kill_link = 0;
418                 }
419                 if (get_loop_output())
420                     break;
421                 reap_kids();
422             }
423             if (kill_link)
424                 break;
425
426             /*
427              * Now we want to bring up the link.
428              */
429             demand_block();
430             syslog(LOG_INFO, "Starting link");
431         }
432
433         /*
434          * Lock the device if we've been asked to.
435          */
436         if (lockflag && !default_device) {
437             if (lock(devnam) < 0)
438                 goto fail;
439             locked = 1;
440         }
441
442         /*
443          * Open the serial device and set it up to be the ppp interface.
444          * First we open it in non-blocking mode so we can set the
445          * various termios flags appropriately.  If we aren't dialling
446          * out and we want to use the modem lines, we reopen it later
447          * in order to wait for the carrier detect signal from the modem.
448          */
449         hungup = 0;
450         kill_link = 0;
451         sigprocmask(SIG_UNBLOCK, &mask, NULL);
452         for (;;) {
453             /* If the user specified the device name, become the
454                user before opening it. */
455             if (!devnam_info.priv)
456                 seteuid(uid);
457             ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
458             if (!devnam_info.priv)
459                 seteuid(0);
460             if (ttyfd >= 0)
461                 break;
462             if (errno != EINTR)
463                 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
464             if (!persist || errno != EINTR)
465                 goto fail;
466         }
467         sigprocmask(SIG_BLOCK, &mask, NULL);
468         if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
469             || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
470             syslog(LOG_WARNING,
471                    "Couldn't reset non-blocking mode on device: %m");
472
473         /*
474          * Do the equivalent of `mesg n' to stop broadcast messages.
475          */
476         if (fstat(ttyfd, &statbuf) < 0
477             || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
478             syslog(LOG_WARNING,
479                    "Couldn't restrict write permissions to %s: %m", devnam);
480         } else
481             tty_mode = statbuf.st_mode;
482
483         /* run connection script */
484         if (connector && connector[0]) {
485             MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
486
487             if (!default_device && modem) {
488                 hangup_modem(ttyfd);    /* in case modem is off hook */
489                 sleep(1);
490             }
491
492             /*
493              * Set line speed, flow control, etc.
494              * On most systems we set CLOCAL for now so that we can talk
495              * to the modem before carrier comes up.  But this has the
496              * side effect that we might miss it if CD drops before we
497              * get to clear CLOCAL below.  On systems where we can talk
498              * successfully to the modem with CLOCAL clear and CD down,
499              * we could clear CLOCAL at this point.
500              */
501             set_up_tty(ttyfd, 1);
502
503             if (device_script(connector, ttyfd, ttyfd) < 0) {
504                 syslog(LOG_ERR, "Connect script failed");
505                 goto fail;
506             }
507
508             syslog(LOG_INFO, "Serial connection established.");
509             sleep(1);           /* give it time to set up its terminal */
510         }
511
512         /* set line speed, flow control, etc.; clear CLOCAL if modem option */
513         set_up_tty(ttyfd, 0);
514
515         /* reopen tty if necessary to wait for carrier */
516         if (connector == NULL && modem) {
517             for (;;) {
518                 if (!devnam_info.priv)
519                     seteuid(uid);
520                 i = open(devnam, O_RDWR);
521                 if (!devnam_info.priv)
522                     seteuid(0);
523                 if (i >= 0)
524                     break;
525                 if (errno != EINTR)
526                     syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
527                 if (!persist || errno != EINTR || hungup || kill_link)
528                     goto fail;
529             }
530             close(i);
531         }
532
533         /* run welcome script, if any */
534         if (welcomer && welcomer[0]) {
535             if (device_script(welcomer, ttyfd, ttyfd) < 0)
536                 syslog(LOG_WARNING, "Welcome script failed");
537         }
538
539         /* set up the serial device as a ppp interface */
540         establish_ppp(ttyfd);
541
542         if (!demand) {
543             
544             syslog(LOG_INFO, "Using interface ppp%d", ifunit);
545             (void) sprintf(ifname, "ppp%d", ifunit);
546             script_setenv("IFNAME", ifname);
547
548             create_pidfile();   /* write pid to file */
549         }
550
551         /*
552          * Start opening the connection and wait for
553          * incoming events (reply, timeout, etc.).
554          */
555         syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
556         lcp_lowerup(0);
557         lcp_open(0);            /* Start protocol */
558         open_ccp_flag = 0;
559         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
560             if (setjmp(sigjmp) == 0) {
561                 waiting = 1;
562                 sigprocmask(SIG_UNBLOCK, &mask, NULL);
563                 wait_input(timeleft(&timo));
564             }
565             sigprocmask(SIG_BLOCK, &mask, NULL);
566             waiting = 0;
567             calltimeout();
568             if (kill_link) {
569                 lcp_close(0, "User request");
570                 kill_link = 0;
571             }
572             get_input();
573             if (open_ccp_flag) {
574                 if (phase == PHASE_NETWORK) {
575                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
576                     (*ccp_protent.open)(0);
577                 }
578                 open_ccp_flag = 0;
579             }
580             reap_kids();        /* Don't leave dead kids lying around */
581         }
582
583         /*
584          * If we may want to bring the link up again, transfer
585          * the ppp unit back to the loopback.  Set the
586          * real serial device back to its normal mode of operation.
587          */
588         clean_check();
589         if (demand)
590             restore_loop();
591         disestablish_ppp(ttyfd);
592
593         /*
594          * Run disconnector script, if requested.
595          * XXX we may not be able to do this if the line has hung up!
596          */
597         if (disconnector && !hungup) {
598             set_up_tty(ttyfd, 1);
599             if (device_script(disconnector, ttyfd, ttyfd) < 0) {
600                 syslog(LOG_WARNING, "disconnect script failed");
601             } else {
602                 syslog(LOG_INFO, "Serial link disconnected.");
603             }
604         }
605
606     fail:
607         if (ttyfd >= 0)
608             close_tty();
609         if (locked) {
610             unlock();
611             locked = 0;
612         }
613
614         if (!demand) {
615             if (pidfilename[0] != 0
616                 && unlink(pidfilename) < 0 && errno != ENOENT) 
617                 syslog(LOG_WARNING, "unable to delete pid file: %m");
618             pidfilename[0] = 0;
619         }
620
621         if (!persist)
622             break;
623
624         if (demand)
625             demand_discard();
626         if (holdoff > 0 && need_holdoff) {
627             phase = PHASE_HOLDOFF;
628             TIMEOUT(holdoff_end, NULL, holdoff);
629             do {
630                 if (setjmp(sigjmp) == 0) {
631                     waiting = 1;
632                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
633                     wait_time(timeleft(&timo));
634                 }
635                 sigprocmask(SIG_BLOCK, &mask, NULL);
636                 waiting = 0;
637                 calltimeout();
638                 if (kill_link) {
639                     kill_link = 0;
640                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
641                 }
642                 reap_kids();
643             } while (phase == PHASE_HOLDOFF);
644             if (!persist)
645                 break;
646         }
647     }
648
649     /* Wait for scripts to finish */
650     while (n_children > 0)
651         reap_kids();
652
653     die(0);
654     return 0;
655 }
656
657 /*
658  * detach - detach us from the controlling terminal.
659  */
660 void
661 detach()
662 {
663     if (detached)
664         return;
665     if (daemon(0, 0) < 0) {
666         perror("Couldn't detach from controlling terminal");
667         die(1);
668     }
669     detached = 1;
670     pid = getpid();
671     /* update pid file if it has been written already */
672     if (pidfilename[0])
673         create_pidfile();
674 }
675
676 /*
677  * Create a file containing our process ID.
678  */
679 static void
680 create_pidfile()
681 {
682     FILE *pidfile;
683     char numbuf[16];
684
685     (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
686     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
687         fprintf(pidfile, "%d\n", pid);
688         (void) fclose(pidfile);
689     } else {
690         syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
691         pidfilename[0] = 0;
692     }
693     sprintf(numbuf, "%d", pid);
694     script_setenv("PPPD_PID", numbuf);
695 }
696
697 /*
698  * holdoff_end - called via a timeout when the holdoff period ends.
699  */
700 static void
701 holdoff_end(arg)
702     void *arg;
703 {
704     phase = PHASE_DORMANT;
705 }
706
707 /*
708  * get_input - called when incoming data is available.
709  */
710 static void
711 get_input()
712 {
713     int len, i;
714     u_char *p;
715     u_short protocol;
716     struct protent *protp;
717
718     p = inpacket_buf;   /* point to beginning of packet buffer */
719
720     len = read_packet(inpacket_buf);
721     if (len < 0)
722         return;
723
724     if (len == 0) {
725         syslog(LOG_NOTICE, "Modem hangup");
726         hungup = 1;
727         lcp_lowerdown(0);       /* serial link is no longer available */
728         link_terminated(0);
729         return;
730     }
731
732     if (debug /*&& (debugflags & DBG_INPACKET)*/)
733         log_packet(p, len, "rcvd ", LOG_DEBUG);
734
735     if (len < PPP_HDRLEN) {
736         MAINDEBUG((LOG_INFO, "io(): Received short packet."));
737         return;
738     }
739
740     p += 2;                             /* Skip address and control */
741     GETSHORT(protocol, p);
742     len -= PPP_HDRLEN;
743
744     /*
745      * Toss all non-LCP packets unless LCP is OPEN.
746      */
747     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
748         MAINDEBUG((LOG_INFO,
749                    "get_input: Received non-LCP packet when LCP not open."));
750         return;
751     }
752
753     /*
754      * Until we get past the authentication phase, toss all packets
755      * except LCP, LQR and authentication packets.
756      */
757     if (phase <= PHASE_AUTHENTICATE
758         && !(protocol == PPP_LCP || protocol == PPP_LQR
759              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
760         MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
761                    protocol, phase));
762         return;
763     }
764
765     /*
766      * Upcall the proper protocol input routine.
767      */
768     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
769         if (protp->protocol == protocol && protp->enabled_flag) {
770             (*protp->input)(0, p, len);
771             return;
772         }
773         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
774             && protp->datainput != NULL) {
775             (*protp->datainput)(0, p, len);
776             return;
777         }
778     }
779
780     if (debug)
781         syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
782     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
783 }
784
785
786 /*
787  * quit - Clean up state and exit (with an error indication).
788  */
789 void 
790 quit()
791 {
792     die(1);
793 }
794
795 /*
796  * die - like quit, except we can specify an exit status.
797  */
798 void
799 die(status)
800     int status;
801 {
802     cleanup();
803     syslog(LOG_INFO, "Exit.");
804     exit(status);
805 }
806
807 /*
808  * cleanup - restore anything which needs to be restored before we exit
809  */
810 /* ARGSUSED */
811 static void
812 cleanup()
813 {
814     sys_cleanup();
815
816     if (ttyfd >= 0)
817         close_tty();
818
819     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
820         syslog(LOG_WARNING, "unable to delete pid file: %m");
821     pidfilename[0] = 0;
822
823     if (locked)
824         unlock();
825 }
826
827 /*
828  * close_tty - restore the terminal device and close it.
829  */
830 static void
831 close_tty()
832 {
833     disestablish_ppp(ttyfd);
834
835     /* drop dtr to hang up */
836     if (!default_device && modem) {
837         hangup_modem(ttyfd);
838         /*
839          * This sleep is in case the serial port has CLOCAL set by default,
840          * and consequently will reassert DTR when we close the device.
841          */
842         sleep(1);
843     }
844
845     restore_tty(ttyfd);
846
847     if (tty_mode != (mode_t) -1) {
848         if (fchmod(ttyfd, tty_mode) != 0) {
849             /* XXX if devnam is a symlink, this will change the link */
850             chmod(devnam, tty_mode);
851         }
852     }
853
854     close(ttyfd);
855     ttyfd = -1;
856 }
857
858
859 struct  callout {
860     struct timeval      c_time;         /* time at which to call routine */
861     void                *c_arg;         /* argument to routine */
862     void                (*c_func) __P((void *)); /* routine */
863     struct              callout *c_next;
864 };
865
866 static struct callout *callout = NULL;  /* Callout list */
867 static struct timeval timenow;          /* Current time */
868
869 /*
870  * timeout - Schedule a timeout.
871  *
872  * Note that this timeout takes the number of seconds, NOT hz (as in
873  * the kernel).
874  */
875 void
876 timeout(func, arg, time)
877     void (*func) __P((void *));
878     void *arg;
879     int time;
880 {
881     struct callout *newp, *p, **pp;
882   
883     MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
884                (long) func, (long) arg, time));
885   
886     /*
887      * Allocate timeout.
888      */
889     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
890         syslog(LOG_ERR, "Out of memory in timeout()!");
891         die(1);
892     }
893     newp->c_arg = arg;
894     newp->c_func = func;
895     gettimeofday(&timenow, NULL);
896     newp->c_time.tv_sec = timenow.tv_sec + time;
897     newp->c_time.tv_usec = timenow.tv_usec;
898   
899     /*
900      * Find correct place and link it in.
901      */
902     for (pp = &callout; (p = *pp); pp = &p->c_next)
903         if (newp->c_time.tv_sec < p->c_time.tv_sec
904             || (newp->c_time.tv_sec == p->c_time.tv_sec
905                 && newp->c_time.tv_usec < p->c_time.tv_usec))
906             break;
907     newp->c_next = p;
908     *pp = newp;
909 }
910
911
912 /*
913  * untimeout - Unschedule a timeout.
914  */
915 void
916 untimeout(func, arg)
917     void (*func) __P((void *));
918     void *arg;
919 {
920     struct callout **copp, *freep;
921   
922     MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
923   
924     /*
925      * Find first matching timeout and remove it from the list.
926      */
927     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
928         if (freep->c_func == func && freep->c_arg == arg) {
929             *copp = freep->c_next;
930             (void) free((char *) freep);
931             break;
932         }
933 }
934
935
936 /*
937  * calltimeout - Call any timeout routines which are now due.
938  */
939 static void
940 calltimeout()
941 {
942     struct callout *p;
943
944     while (callout != NULL) {
945         p = callout;
946
947         if (gettimeofday(&timenow, NULL) < 0) {
948             syslog(LOG_ERR, "Failed to get time of day: %m");
949             die(1);
950         }
951         if (!(p->c_time.tv_sec < timenow.tv_sec
952               || (p->c_time.tv_sec == timenow.tv_sec
953                   && p->c_time.tv_usec <= timenow.tv_usec)))
954             break;              /* no, it's not time yet */
955
956         callout = p->c_next;
957         (*p->c_func)(p->c_arg);
958
959         free((char *) p);
960     }
961 }
962
963
964 /*
965  * timeleft - return the length of time until the next timeout is due.
966  */
967 static struct timeval *
968 timeleft(tvp)
969     struct timeval *tvp;
970 {
971     if (callout == NULL)
972         return NULL;
973
974     gettimeofday(&timenow, NULL);
975     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
976     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
977     if (tvp->tv_usec < 0) {
978         tvp->tv_usec += 1000000;
979         tvp->tv_sec -= 1;
980     }
981     if (tvp->tv_sec < 0)
982         tvp->tv_sec = tvp->tv_usec = 0;
983
984     return tvp;
985 }
986
987
988 /*
989  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
990  */
991 static void
992 kill_my_pg(sig)
993     int sig;
994 {
995     struct sigaction act, oldact;
996
997     act.sa_handler = SIG_IGN;
998     act.sa_flags = 0;
999     kill(0, sig);
1000     sigaction(sig, &act, &oldact);
1001     sigaction(sig, &oldact, NULL);
1002 }
1003
1004
1005 /*
1006  * hup - Catch SIGHUP signal.
1007  *
1008  * Indicates that the physical layer has been disconnected.
1009  * We don't rely on this indication; if the user has sent this
1010  * signal, we just take the link down.
1011  */
1012 static void
1013 hup(sig)
1014     int sig;
1015 {
1016     syslog(LOG_INFO, "Hangup (SIGHUP)");
1017     kill_link = 1;
1018     if (conn_running)
1019         /* Send the signal to the [dis]connector process(es) also */
1020         kill_my_pg(sig);
1021     if (waiting)
1022         longjmp(sigjmp, 1);
1023 }
1024
1025
1026 /*
1027  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1028  *
1029  * Indicates that we should initiate a graceful disconnect and exit.
1030  */
1031 /*ARGSUSED*/
1032 static void
1033 term(sig)
1034     int sig;
1035 {
1036     syslog(LOG_INFO, "Terminating on signal %d.", sig);
1037     persist = 0;                /* don't try to restart */
1038     kill_link = 1;
1039     if (conn_running)
1040         /* Send the signal to the [dis]connector process(es) also */
1041         kill_my_pg(sig);
1042     if (waiting)
1043         longjmp(sigjmp, 1);
1044 }
1045
1046
1047 /*
1048  * chld - Catch SIGCHLD signal.
1049  * Calls reap_kids to get status for any dead kids.
1050  */
1051 static void
1052 chld(sig)
1053     int sig;
1054 {
1055     if (waiting)
1056         longjmp(sigjmp, 1);
1057 }
1058
1059
1060 /*
1061  * toggle_debug - Catch SIGUSR1 signal.
1062  *
1063  * Toggle debug flag.
1064  */
1065 /*ARGSUSED*/
1066 static void
1067 toggle_debug(sig)
1068     int sig;
1069 {
1070     debug = !debug;
1071     if (debug) {
1072         setlogmask(LOG_UPTO(LOG_DEBUG));
1073     } else {
1074         setlogmask(LOG_UPTO(LOG_WARNING));
1075     }
1076 }
1077
1078
1079 /*
1080  * open_ccp - Catch SIGUSR2 signal.
1081  *
1082  * Try to (re)negotiate compression.
1083  */
1084 /*ARGSUSED*/
1085 static void
1086 open_ccp(sig)
1087     int sig;
1088 {
1089     open_ccp_flag = 1;
1090     if (waiting)
1091         longjmp(sigjmp, 1);
1092 }
1093
1094
1095 /*
1096  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1097  */
1098 static void
1099 bad_signal(sig)
1100     int sig;
1101 {
1102     static int crashed = 0;
1103
1104     if (crashed)
1105         _exit(127);
1106     crashed = 1;
1107     syslog(LOG_ERR, "Fatal signal %d", sig);
1108     if (conn_running)
1109         kill_my_pg(SIGTERM);
1110     die(1);
1111 }
1112
1113
1114 /*
1115  * device_script - run a program to connect or disconnect the
1116  * serial device.
1117  */
1118 static int
1119 device_script(program, in, out)
1120     char *program;
1121     int in, out;
1122 {
1123     int pid;
1124     int status;
1125     int errfd;
1126
1127     conn_running = 1;
1128     pid = fork();
1129
1130     if (pid < 0) {
1131         conn_running = 0;
1132         syslog(LOG_ERR, "Failed to create child process: %m");
1133         die(1);
1134     }
1135
1136     if (pid == 0) {
1137         sys_close();
1138         closelog();
1139         if (in == out) {
1140             if (in != 0) {
1141                 dup2(in, 0);
1142                 close(in);
1143             }
1144             dup2(0, 1);
1145         } else {
1146             if (out == 0)
1147                 out = dup(out);
1148             if (in != 0) {
1149                 dup2(in, 0);
1150                 close(in);
1151             }
1152             if (out != 1) {
1153                 dup2(out, 1);
1154                 close(out);
1155             }
1156         }
1157         if (!nodetach && !updetach) {
1158             close(2);
1159             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1160             if (errfd >= 0 && errfd != 2) {
1161                 dup2(errfd, 2);
1162                 close(errfd);
1163             }
1164         }
1165         setuid(uid);
1166         setgid(getgid());
1167         execl("/bin/sh", "sh", "-c", program, (char *)0);
1168         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1169         _exit(99);
1170         /* NOTREACHED */
1171     }
1172
1173     while (waitpid(pid, &status, 0) < 0) {
1174         if (errno == EINTR)
1175             continue;
1176         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1177         die(1);
1178     }
1179     conn_running = 0;
1180
1181     return (status == 0 ? 0 : -1);
1182 }
1183
1184
1185 /*
1186  * We maintain a list of child process pids and
1187  * functions to call when they exit.
1188  */
1189 struct subprocess {
1190     pid_t       pid;
1191     char        *prog;
1192     void        (*done) __P((void *));
1193     void        *arg;
1194     struct subprocess *next;
1195 };
1196
1197 struct subprocess *children;
1198
1199 /*
1200  * run-program - execute a program with given arguments,
1201  * but don't wait for it.
1202  * If the program can't be executed, logs an error unless
1203  * must_exist is 0 and the program file doesn't exist.
1204  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1205  * or isn't an executable plain file, or the process ID of the child.
1206  * If done != NULL, (*done)(arg) will be called later (within
1207  * reap_kids) iff the return value is > 0.
1208  */
1209 pid_t
1210 run_program(prog, args, must_exist, done, arg)
1211     char *prog;
1212     char **args;
1213     int must_exist;
1214     void (*done) __P((void *));
1215     void *arg;
1216 {
1217     int pid;
1218     struct subprocess *chp;
1219     struct stat sbuf;
1220
1221     /*
1222      * First check if the file exists and is executable.
1223      * We don't use access() because that would use the
1224      * real user-id, which might not be root, and the script
1225      * might be accessible only to root.
1226      */
1227     errno = EINVAL;
1228     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1229         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1230         if (must_exist || errno != ENOENT)
1231             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1232         return 0;
1233     }
1234
1235     pid = fork();
1236     if (pid == -1) {
1237         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1238         die(1);
1239     }
1240     if (pid == 0) {
1241         int new_fd;
1242
1243         /* Leave the current location */
1244         (void) setsid();    /* No controlling tty. */
1245         (void) umask (S_IRWXG|S_IRWXO);
1246         (void) chdir ("/"); /* no current directory. */
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 }