]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
092195471e35c730287e5b80e9cf3e0f80e890c1
[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.57 1999/03/08 05:34:43 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  * hangup_modem - hang up the modem by clearing DTR.
859  */
860 void hangup_modem(ttyfd)
861     int ttyfd;
862 {
863     setdtr(ttyfd, 0);
864 }
865
866
867 struct  callout {
868     struct timeval      c_time;         /* time at which to call routine */
869     void                *c_arg;         /* argument to routine */
870     void                (*c_func) __P((void *)); /* routine */
871     struct              callout *c_next;
872 };
873
874 static struct callout *callout = NULL;  /* Callout list */
875 static struct timeval timenow;          /* Current time */
876
877 /*
878  * timeout - Schedule a timeout.
879  *
880  * Note that this timeout takes the number of seconds, NOT hz (as in
881  * the kernel).
882  */
883 void
884 timeout(func, arg, time)
885     void (*func) __P((void *));
886     void *arg;
887     int time;
888 {
889     struct callout *newp, *p, **pp;
890   
891     MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
892                (long) func, (long) arg, time));
893   
894     /*
895      * Allocate timeout.
896      */
897     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
898         syslog(LOG_ERR, "Out of memory in timeout()!");
899         die(1);
900     }
901     newp->c_arg = arg;
902     newp->c_func = func;
903     gettimeofday(&timenow, NULL);
904     newp->c_time.tv_sec = timenow.tv_sec + time;
905     newp->c_time.tv_usec = timenow.tv_usec;
906   
907     /*
908      * Find correct place and link it in.
909      */
910     for (pp = &callout; (p = *pp); pp = &p->c_next)
911         if (newp->c_time.tv_sec < p->c_time.tv_sec
912             || (newp->c_time.tv_sec == p->c_time.tv_sec
913                 && newp->c_time.tv_usec < p->c_time.tv_usec))
914             break;
915     newp->c_next = p;
916     *pp = newp;
917 }
918
919
920 /*
921  * untimeout - Unschedule a timeout.
922  */
923 void
924 untimeout(func, arg)
925     void (*func) __P((void *));
926     void *arg;
927 {
928     struct callout **copp, *freep;
929   
930     MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
931   
932     /*
933      * Find first matching timeout and remove it from the list.
934      */
935     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
936         if (freep->c_func == func && freep->c_arg == arg) {
937             *copp = freep->c_next;
938             (void) free((char *) freep);
939             break;
940         }
941 }
942
943
944 /*
945  * calltimeout - Call any timeout routines which are now due.
946  */
947 static void
948 calltimeout()
949 {
950     struct callout *p;
951
952     while (callout != NULL) {
953         p = callout;
954
955         if (gettimeofday(&timenow, NULL) < 0) {
956             syslog(LOG_ERR, "Failed to get time of day: %m");
957             die(1);
958         }
959         if (!(p->c_time.tv_sec < timenow.tv_sec
960               || (p->c_time.tv_sec == timenow.tv_sec
961                   && p->c_time.tv_usec <= timenow.tv_usec)))
962             break;              /* no, it's not time yet */
963
964         callout = p->c_next;
965         (*p->c_func)(p->c_arg);
966
967         free((char *) p);
968     }
969 }
970
971
972 /*
973  * timeleft - return the length of time until the next timeout is due.
974  */
975 static struct timeval *
976 timeleft(tvp)
977     struct timeval *tvp;
978 {
979     if (callout == NULL)
980         return NULL;
981
982     gettimeofday(&timenow, NULL);
983     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
984     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
985     if (tvp->tv_usec < 0) {
986         tvp->tv_usec += 1000000;
987         tvp->tv_sec -= 1;
988     }
989     if (tvp->tv_sec < 0)
990         tvp->tv_sec = tvp->tv_usec = 0;
991
992     return tvp;
993 }
994
995
996 /*
997  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
998  */
999 static void
1000 kill_my_pg(sig)
1001     int sig;
1002 {
1003     struct sigaction act, oldact;
1004
1005     act.sa_handler = SIG_IGN;
1006     act.sa_flags = 0;
1007     kill(0, sig);
1008     sigaction(sig, &act, &oldact);
1009     sigaction(sig, &oldact, NULL);
1010 }
1011
1012
1013 /*
1014  * hup - Catch SIGHUP signal.
1015  *
1016  * Indicates that the physical layer has been disconnected.
1017  * We don't rely on this indication; if the user has sent this
1018  * signal, we just take the link down.
1019  */
1020 static void
1021 hup(sig)
1022     int sig;
1023 {
1024     syslog(LOG_INFO, "Hangup (SIGHUP)");
1025     kill_link = 1;
1026     if (conn_running)
1027         /* Send the signal to the [dis]connector process(es) also */
1028         kill_my_pg(sig);
1029     if (waiting)
1030         longjmp(sigjmp, 1);
1031 }
1032
1033
1034 /*
1035  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1036  *
1037  * Indicates that we should initiate a graceful disconnect and exit.
1038  */
1039 /*ARGSUSED*/
1040 static void
1041 term(sig)
1042     int sig;
1043 {
1044     syslog(LOG_INFO, "Terminating on signal %d.", sig);
1045     persist = 0;                /* don't try to restart */
1046     kill_link = 1;
1047     if (conn_running)
1048         /* Send the signal to the [dis]connector process(es) also */
1049         kill_my_pg(sig);
1050     if (waiting)
1051         longjmp(sigjmp, 1);
1052 }
1053
1054
1055 /*
1056  * chld - Catch SIGCHLD signal.
1057  * Calls reap_kids to get status for any dead kids.
1058  */
1059 static void
1060 chld(sig)
1061     int sig;
1062 {
1063     if (waiting)
1064         longjmp(sigjmp, 1);
1065 }
1066
1067
1068 /*
1069  * toggle_debug - Catch SIGUSR1 signal.
1070  *
1071  * Toggle debug flag.
1072  */
1073 /*ARGSUSED*/
1074 static void
1075 toggle_debug(sig)
1076     int sig;
1077 {
1078     debug = !debug;
1079     if (debug) {
1080         setlogmask(LOG_UPTO(LOG_DEBUG));
1081     } else {
1082         setlogmask(LOG_UPTO(LOG_WARNING));
1083     }
1084 }
1085
1086
1087 /*
1088  * open_ccp - Catch SIGUSR2 signal.
1089  *
1090  * Try to (re)negotiate compression.
1091  */
1092 /*ARGSUSED*/
1093 static void
1094 open_ccp(sig)
1095     int sig;
1096 {
1097     open_ccp_flag = 1;
1098     if (waiting)
1099         longjmp(sigjmp, 1);
1100 }
1101
1102
1103 /*
1104  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1105  */
1106 static void
1107 bad_signal(sig)
1108     int sig;
1109 {
1110     static int crashed = 0;
1111
1112     if (crashed)
1113         _exit(127);
1114     crashed = 1;
1115     syslog(LOG_ERR, "Fatal signal %d", sig);
1116     if (conn_running)
1117         kill_my_pg(SIGTERM);
1118     die(1);
1119 }
1120
1121
1122 /*
1123  * device_script - run a program to connect or disconnect the
1124  * serial device.
1125  */
1126 static int
1127 device_script(program, in, out)
1128     char *program;
1129     int in, out;
1130 {
1131     int pid;
1132     int status;
1133     int errfd;
1134
1135     conn_running = 1;
1136     pid = fork();
1137
1138     if (pid < 0) {
1139         conn_running = 0;
1140         syslog(LOG_ERR, "Failed to create child process: %m");
1141         die(1);
1142     }
1143
1144     if (pid == 0) {
1145         sys_close();
1146         closelog();
1147         if (in == out) {
1148             if (in != 0) {
1149                 dup2(in, 0);
1150                 close(in);
1151             }
1152             dup2(0, 1);
1153         } else {
1154             if (out == 0)
1155                 out = dup(out);
1156             if (in != 0) {
1157                 dup2(in, 0);
1158                 close(in);
1159             }
1160             if (out != 1) {
1161                 dup2(out, 1);
1162                 close(out);
1163             }
1164         }
1165         if (!nodetach && !updetach) {
1166             close(2);
1167             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1168             if (errfd >= 0 && errfd != 2) {
1169                 dup2(errfd, 2);
1170                 close(errfd);
1171             }
1172         }
1173         setuid(uid);
1174         setgid(getgid());
1175         execl("/bin/sh", "sh", "-c", program, (char *)0);
1176         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1177         _exit(99);
1178         /* NOTREACHED */
1179     }
1180
1181     while (waitpid(pid, &status, 0) < 0) {
1182         if (errno == EINTR)
1183             continue;
1184         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1185         die(1);
1186     }
1187     conn_running = 0;
1188
1189     return (status == 0 ? 0 : -1);
1190 }
1191
1192
1193 /*
1194  * We maintain a list of child process pids and
1195  * functions to call when they exit.
1196  */
1197 struct subprocess {
1198     pid_t       pid;
1199     char        *prog;
1200     void        (*done) __P((void *));
1201     void        *arg;
1202     struct subprocess *next;
1203 };
1204
1205 struct subprocess *children;
1206
1207 /*
1208  * run-program - execute a program with given arguments,
1209  * but don't wait for it.
1210  * If the program can't be executed, logs an error unless
1211  * must_exist is 0 and the program file doesn't exist.
1212  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1213  * or isn't an executable plain file, or the process ID of the child.
1214  * If done != NULL, (*done)(arg) will be called later (within
1215  * reap_kids) iff the return value is > 0.
1216  */
1217 pid_t
1218 run_program(prog, args, must_exist, done, arg)
1219     char *prog;
1220     char **args;
1221     int must_exist;
1222     void (*done) __P((void *));
1223     void *arg;
1224 {
1225     int pid;
1226     struct subprocess *chp;
1227     struct stat sbuf;
1228
1229     /*
1230      * First check if the file exists and is executable.
1231      * We don't use access() because that would use the
1232      * real user-id, which might not be root, and the script
1233      * might be accessible only to root.
1234      */
1235     errno = EINVAL;
1236     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1237         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1238         if (must_exist || errno != ENOENT)
1239             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1240         return 0;
1241     }
1242
1243     pid = fork();
1244     if (pid == -1) {
1245         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1246         die(1);
1247     }
1248     if (pid == 0) {
1249         int new_fd;
1250
1251         /* Leave the current location */
1252         (void) setsid();        /* No controlling tty. */
1253         (void) umask (S_IRWXG|S_IRWXO);
1254         (void) chdir ("/");     /* no current directory. */
1255         setuid(0);              /* set real UID = root */
1256         setgid(getegid());
1257
1258         /* Ensure that nothing of our device environment is inherited. */
1259         sys_close();
1260         closelog();
1261         close (0);
1262         close (1);
1263         close (2);
1264         close (ttyfd);  /* tty interface to the ppp device */
1265
1266         /* Don't pass handles to the PPP device, even by accident. */
1267         new_fd = open (_PATH_DEVNULL, O_RDWR);
1268         if (new_fd >= 0) {
1269             if (new_fd != 0) {
1270                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1271                 close (new_fd);
1272             }
1273             dup2 (0, 1); /* stdout -> /dev/null */
1274             dup2 (0, 2); /* stderr -> /dev/null */
1275         }
1276
1277 #ifdef BSD
1278         /* Force the priority back to zero if pppd is running higher. */
1279         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1280             syslog (LOG_WARNING, "can't reset priority to 0: %m"); 
1281 #endif
1282
1283         /* SysV recommends a second fork at this point. */
1284
1285         /* run the program */
1286         execve(prog, args, script_env);
1287         if (must_exist || errno != ENOENT) {
1288             int i;
1289             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1290             for (i = 0; args[i]; ++i)
1291                 syslog(LOG_DEBUG, "args[%d] = '%s'", i, args[i]);
1292             for (i = 0; script_env[i]; ++i)
1293                 syslog(LOG_DEBUG, "env[%d] = '%s'", i, script_env[i]);
1294         }
1295         _exit(-1);
1296     }
1297
1298     if (debug)
1299         syslog(LOG_DEBUG, "Script %s started; pid = %d", prog, pid);
1300     ++n_children;
1301
1302     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1303     if (chp == NULL) {
1304         syslog(LOG_WARNING, "losing track of %s process", prog);
1305     } else {
1306         chp->pid = pid;
1307         chp->prog = prog;
1308         chp->done = done;
1309         chp->arg = arg;
1310         chp->next = children;
1311         children = chp;
1312     }
1313
1314     return pid;
1315 }
1316
1317
1318 /*
1319  * reap_kids - get status from any dead child processes,
1320  * and log a message for abnormal terminations.
1321  */
1322 static void
1323 reap_kids()
1324 {
1325     int pid, status;
1326     struct subprocess *chp, **prevp;
1327
1328     if (n_children == 0)
1329         return;
1330     while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1331         --n_children;
1332         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1333             if (chp->pid == pid)
1334                 break;
1335         if (debug)
1336             syslog(LOG_DEBUG, "process %d (%s) finished, status = 0x%x",
1337                    pid, (chp? chp->prog: "??"), status);
1338         if (WIFSIGNALED(status)) {
1339             syslog(LOG_WARNING,
1340                    "Child process %s (pid %d) terminated with signal %d",
1341                    (chp? chp->prog: "??"), pid, WTERMSIG(status));
1342         }
1343         if (chp && chp->done)
1344             (*chp->done)(chp->arg);
1345     }
1346     if (pid == -1 && errno != ECHILD)
1347         syslog(LOG_ERR, "Error waiting for child process: %m");
1348 }
1349
1350
1351 /*
1352  * log_packet - format a packet and log it.
1353  */
1354
1355 char line[256];                 /* line to be logged accumulated here */
1356 char *linep;
1357
1358 void
1359 log_packet(p, len, prefix, level)
1360     u_char *p;
1361     int len;
1362     char *prefix;
1363     int level;
1364 {
1365     strcpy(line, prefix);
1366     linep = line + strlen(line);
1367     format_packet(p, len, pr_log, NULL);
1368     if (linep != line)
1369         syslog(level, "%s", line);
1370 }
1371
1372 /*
1373  * format_packet - make a readable representation of a packet,
1374  * calling `printer(arg, format, ...)' to output it.
1375  */
1376 void
1377 format_packet(p, len, printer, arg)
1378     u_char *p;
1379     int len;
1380     void (*printer) __P((void *, char *, ...));
1381     void *arg;
1382 {
1383     int i, n;
1384     u_short proto;
1385     u_char x;
1386     struct protent *protp;
1387
1388     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1389         p += 2;
1390         GETSHORT(proto, p);
1391         len -= PPP_HDRLEN;
1392         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1393             if (proto == protp->protocol)
1394                 break;
1395         if (protp != NULL) {
1396             printer(arg, "[%s", protp->name);
1397             n = (*protp->printpkt)(p, len, printer, arg);
1398             printer(arg, "]");
1399             p += n;
1400             len -= n;
1401         } else {
1402             printer(arg, "[proto=0x%x]", proto);
1403         }
1404     }
1405
1406     for (i = 0; i < len && i < 32; ++i) {
1407         GETCHAR(x, p);
1408         printer(arg, " %.2x", x);
1409     }
1410     if (i < len)
1411         printer(arg, " ...");
1412 }
1413
1414 static void
1415 pr_log __V((void *arg, char *fmt, ...))
1416 {
1417     int n;
1418     va_list pvar;
1419     char buf[256];
1420
1421 #if __STDC__
1422     va_start(pvar, fmt);
1423 #else
1424     void *arg;
1425     char *fmt;
1426     va_start(pvar);
1427     arg = va_arg(pvar, void *);
1428     fmt = va_arg(pvar, char *);
1429 #endif
1430
1431     n = vfmtmsg(buf, sizeof(buf), fmt, pvar);
1432     va_end(pvar);
1433
1434     if (linep + n + 1 > line + sizeof(line)) {
1435         syslog(LOG_DEBUG, "%s", line);
1436         linep = line;
1437     }
1438     strcpy(linep, buf);
1439     linep += n;
1440 }
1441
1442 /*
1443  * print_string - print a readable representation of a string using
1444  * printer.
1445  */
1446 void
1447 print_string(p, len, printer, arg)
1448     char *p;
1449     int len;
1450     void (*printer) __P((void *, char *, ...));
1451     void *arg;
1452 {
1453     int c;
1454
1455     printer(arg, "\"");
1456     for (; len > 0; --len) {
1457         c = *p++;
1458         if (' ' <= c && c <= '~') {
1459             if (c == '\\' || c == '"')
1460                 printer(arg, "\\");
1461             printer(arg, "%c", c);
1462         } else {
1463             switch (c) {
1464             case '\n':
1465                 printer(arg, "\\n");
1466                 break;
1467             case '\r':
1468                 printer(arg, "\\r");
1469                 break;
1470             case '\t':
1471                 printer(arg, "\\t");
1472                 break;
1473             default:
1474                 printer(arg, "\\%.3o", c);
1475             }
1476         }
1477     }
1478     printer(arg, "\"");
1479 }
1480
1481 /*
1482  * novm - log an error message saying we ran out of memory, and die.
1483  */
1484 void
1485 novm(msg)
1486     char *msg;
1487 {
1488     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1489     die(1);
1490 }
1491
1492 /*
1493  * fmtmsg - format a message into a buffer.  Like sprintf except we
1494  * also specify the length of the output buffer, and we handle
1495  * %r (recursive format), %m (error message) and %I (IP address) formats.
1496  * Doesn't do floating-point formats.
1497  * Returns the number of chars put into buf.
1498  */
1499 int
1500 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1501 {
1502     va_list args;
1503     int n;
1504
1505 #if __STDC__
1506     va_start(args, fmt);
1507 #else
1508     char *buf;
1509     int buflen;
1510     char *fmt;
1511     va_start(args);
1512     buf = va_arg(args, char *);
1513     buflen = va_arg(args, int);
1514     fmt = va_arg(args, char *);
1515 #endif
1516     n = vfmtmsg(buf, buflen, fmt, args);
1517     va_end(args);
1518     return n;
1519 }
1520
1521 /*
1522  * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1523  */
1524 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1525
1526 int
1527 vfmtmsg(buf, buflen, fmt, args)
1528     char *buf;
1529     int buflen;
1530     char *fmt;
1531     va_list args;
1532 {
1533     int c, i, n;
1534     int width, prec, fillch;
1535     int base, len, neg, quoted;
1536     unsigned long val = 0;
1537     char *str, *f, *buf0;
1538     unsigned char *p;
1539     char num[32];
1540     time_t t;
1541     static char hexchars[] = "0123456789abcdef";
1542
1543     buf0 = buf;
1544     --buflen;
1545     while (buflen > 0) {
1546         for (f = fmt; *f != '%' && *f != 0; ++f)
1547             ;
1548         if (f > fmt) {
1549             len = f - fmt;
1550             if (len > buflen)
1551                 len = buflen;
1552             memcpy(buf, fmt, len);
1553             buf += len;
1554             buflen -= len;
1555             fmt = f;
1556         }
1557         if (*fmt == 0)
1558             break;
1559         c = *++fmt;
1560         width = prec = 0;
1561         fillch = ' ';
1562         if (c == '0') {
1563             fillch = '0';
1564             c = *++fmt;
1565         }
1566         if (c == '*') {
1567             width = va_arg(args, int);
1568             c = *++fmt;
1569         } else {
1570             while (isdigit(c)) {
1571                 width = width * 10 + c - '0';
1572                 c = *++fmt;
1573             }
1574         }
1575         if (c == '.') {
1576             c = *++fmt;
1577             if (c == '*') {
1578                 prec = va_arg(args, int);
1579                 c = *++fmt;
1580             } else {
1581                 while (isdigit(c)) {
1582                     prec = prec * 10 + c - '0';
1583                     c = *++fmt;
1584                 }
1585             }
1586         }
1587         str = 0;
1588         base = 0;
1589         neg = 0;
1590         ++fmt;
1591         switch (c) {
1592         case 'd':
1593             i = va_arg(args, int);
1594             if (i < 0) {
1595                 neg = 1;
1596                 val = -i;
1597             } else
1598                 val = i;
1599             base = 10;
1600             break;
1601         case 'o':
1602             val = va_arg(args, unsigned int);
1603             base = 8;
1604             break;
1605         case 'x':
1606             val = va_arg(args, unsigned int);
1607             base = 16;
1608             break;
1609         case 'p':
1610             val = (unsigned long) va_arg(args, void *);
1611             base = 16;
1612             neg = 2;
1613             break;
1614         case 's':
1615             str = va_arg(args, char *);
1616             break;
1617         case 'c':
1618             num[0] = va_arg(args, int);
1619             num[1] = 0;
1620             str = num;
1621             break;
1622         case 'm':
1623             str = strerror(errno);
1624             break;
1625         case 'I':
1626             str = ip_ntoa(va_arg(args, u_int32_t));
1627             break;
1628         case 'r':
1629             f = va_arg(args, char *);
1630 #ifndef __powerpc__
1631             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1632 #else
1633             /* On the powerpc, a va_list is an array of 1 structure */
1634             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1635 #endif
1636             buf += n;
1637             buflen -= n;
1638             continue;
1639         case 't':
1640             time(&t);
1641             str = ctime(&t);
1642             str += 4;           /* chop off the day name */
1643             str[15] = 0;        /* chop off year and newline */
1644             break;
1645         case 'v':               /* "visible" string */
1646         case 'q':               /* quoted string */
1647             quoted = c == 'q';
1648             p = va_arg(args, unsigned char *);
1649             if (fillch == '0' && prec > 0) {
1650                 n = prec;
1651             } else {
1652                 n = strlen((char *)p);
1653                 if (prec > 0 && prec < n)
1654                     n = prec;
1655             }
1656             while (n > 0 && buflen > 0) {
1657                 c = *p++;
1658                 --n;
1659                 if (!quoted && c >= 0x80) {
1660                     OUTCHAR('M');
1661                     OUTCHAR('-');
1662                     c -= 0x80;
1663                 }
1664                 if (quoted && (c == '"' || c == '\\'))
1665                     OUTCHAR('\\');
1666                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1667                     if (quoted) {
1668                         OUTCHAR('\\');
1669                         switch (c) {
1670                         case '\t':      OUTCHAR('t');   break;
1671                         case '\n':      OUTCHAR('n');   break;
1672                         case '\b':      OUTCHAR('b');   break;
1673                         case '\f':      OUTCHAR('f');   break;
1674                         default:
1675                             OUTCHAR('x');
1676                             OUTCHAR(hexchars[c >> 4]);
1677                             OUTCHAR(hexchars[c & 0xf]);
1678                         }
1679                     } else {
1680                         if (c == '\t')
1681                             OUTCHAR(c);
1682                         else {
1683                             OUTCHAR('^');
1684                             OUTCHAR(c ^ 0x40);
1685                         }
1686                     }
1687                 } else
1688                     OUTCHAR(c);
1689             }
1690             continue;
1691         default:
1692             *buf++ = '%';
1693             if (c != '%')
1694                 --fmt;          /* so %z outputs %z etc. */
1695             --buflen;
1696             continue;
1697         }
1698         if (base != 0) {
1699             str = num + sizeof(num);
1700             *--str = 0;
1701             while (str > num + neg) {
1702                 *--str = hexchars[val % base];
1703                 val = val / base;
1704                 if (--prec <= 0 && val == 0)
1705                     break;
1706             }
1707             switch (neg) {
1708             case 1:
1709                 *--str = '-';
1710                 break;
1711             case 2:
1712                 *--str = 'x';
1713                 *--str = '0';
1714                 break;
1715             }
1716             len = num + sizeof(num) - 1 - str;
1717         } else {
1718             len = strlen(str);
1719             if (prec > 0 && len > prec)
1720                 len = prec;
1721         }
1722         if (width > 0) {
1723             if (width > buflen)
1724                 width = buflen;
1725             if ((n = width - len) > 0) {
1726                 buflen -= n;
1727                 for (; n > 0; --n)
1728                     *buf++ = fillch;
1729             }
1730         }
1731         if (len > buflen)
1732             len = buflen;
1733         memcpy(buf, str, len);
1734         buf += len;
1735         buflen -= len;
1736     }
1737     *buf = 0;
1738     return buf - buf0;
1739 }
1740
1741 /*
1742  * script_setenv - set an environment variable value to be used
1743  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1744  */
1745 void
1746 script_setenv(var, value)
1747     char *var, *value;
1748 {
1749     int vl = strlen(var);
1750     int i;
1751     char *p, *newstring;
1752
1753     newstring = (char *) malloc(vl + strlen(value) + 2);
1754     if (newstring == 0)
1755         return;
1756     strcpy(newstring, var);
1757     newstring[vl] = '=';
1758     strcpy(newstring+vl+1, value);
1759
1760     /* check if this variable is already set */
1761     if (script_env != 0) {
1762         for (i = 0; (p = script_env[i]) != 0; ++i) {
1763             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1764                 free(p);
1765                 script_env[i] = newstring;
1766                 return;
1767             }
1768         }
1769     } else {
1770         i = 0;
1771         script_env = (char **) malloc(16 * sizeof(char *));
1772         if (script_env == 0)
1773             return;
1774         s_env_nalloc = 16;
1775     }
1776
1777     /* reallocate script_env with more space if needed */
1778     if (i + 1 >= s_env_nalloc) {
1779         int new_n = i + 17;
1780         char **newenv = (char **) realloc((void *)script_env,
1781                                           new_n * sizeof(char *));
1782         if (newenv == 0)
1783             return;
1784         script_env = newenv;
1785         s_env_nalloc = new_n;
1786     }
1787
1788     script_env[i] = newstring;
1789     script_env[i+1] = 0;
1790 }
1791
1792 /*
1793  * script_unsetenv - remove a variable from the environment
1794  * for scripts.
1795  */
1796 void
1797 script_unsetenv(var)
1798     char *var;
1799 {
1800     int vl = strlen(var);
1801     int i;
1802     char *p;
1803
1804     if (script_env == 0)
1805         return;
1806     for (i = 0; (p = script_env[i]) != 0; ++i) {
1807         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1808             free(p);
1809             while ((script_env[i] = script_env[i+1]) != 0)
1810                 ++i;
1811             break;
1812         }
1813     }
1814 }