]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
use fchmod rather than chmod to restore device permissions
[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.52 1999/01/19 23:59:39 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         while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
452             if (errno != EINTR)
453                 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
454             if (!persist || errno != EINTR)
455                 goto fail;
456         }
457         sigprocmask(SIG_BLOCK, &mask, NULL);
458         if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
459             || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
460             syslog(LOG_WARNING,
461                    "Couldn't reset non-blocking mode on device: %m");
462
463         /*
464          * Do the equivalent of `mesg n' to stop broadcast messages.
465          */
466         if (fstat(ttyfd, &statbuf) < 0
467             || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
468             syslog(LOG_WARNING,
469                    "Couldn't restrict write permissions to %s: %m", devnam);
470         } else
471             tty_mode = statbuf.st_mode;
472
473         /* run connection script */
474         if (connector && connector[0]) {
475             MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
476
477             if (!default_device && modem) {
478                 hangup_modem(ttyfd);    /* in case modem is off hook */
479                 sleep(1);
480             }
481
482             /*
483              * Set line speed, flow control, etc.
484              * On most systems we set CLOCAL for now so that we can talk
485              * to the modem before carrier comes up.  But this has the
486              * side effect that we might miss it if CD drops before we
487              * get to clear CLOCAL below.  On systems where we can talk
488              * successfully to the modem with CLOCAL clear and CD down,
489              * we could clear CLOCAL at this point.
490              */
491             set_up_tty(ttyfd, 1);
492
493             if (device_script(connector, ttyfd, ttyfd) < 0) {
494                 syslog(LOG_ERR, "Connect script failed");
495                 goto fail;
496             }
497
498             syslog(LOG_INFO, "Serial connection established.");
499             sleep(1);           /* give it time to set up its terminal */
500         }
501
502         /* set line speed, flow control, etc.; clear CLOCAL if modem option */
503         set_up_tty(ttyfd, 0);
504
505         /* reopen tty if necessary to wait for carrier */
506         if (connector == NULL && modem) {
507             while ((i = open(devnam, O_RDWR)) < 0) {
508                 if (errno != EINTR)
509                     syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
510                 if (!persist || errno != EINTR || hungup || kill_link)
511                     goto fail;
512             }
513             close(i);
514         }
515
516         /* run welcome script, if any */
517         if (welcomer && welcomer[0]) {
518             if (device_script(welcomer, ttyfd, ttyfd) < 0)
519                 syslog(LOG_WARNING, "Welcome script failed");
520         }
521
522         /* set up the serial device as a ppp interface */
523         establish_ppp(ttyfd);
524
525         if (!demand) {
526             
527             syslog(LOG_INFO, "Using interface ppp%d", ifunit);
528             (void) sprintf(ifname, "ppp%d", ifunit);
529             script_setenv("IFNAME", ifname);
530
531             create_pidfile();   /* write pid to file */
532         }
533
534         /*
535          * Start opening the connection and wait for
536          * incoming events (reply, timeout, etc.).
537          */
538         syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
539         lcp_lowerup(0);
540         lcp_open(0);            /* Start protocol */
541         open_ccp_flag = 0;
542         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
543             if (setjmp(sigjmp) == 0) {
544                 waiting = 1;
545                 sigprocmask(SIG_UNBLOCK, &mask, NULL);
546                 wait_input(timeleft(&timo));
547             }
548             sigprocmask(SIG_BLOCK, &mask, NULL);
549             waiting = 0;
550             calltimeout();
551             if (kill_link) {
552                 lcp_close(0, "User request");
553                 kill_link = 0;
554             }
555             get_input();
556             if (open_ccp_flag) {
557                 if (phase == PHASE_NETWORK) {
558                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
559                     (*ccp_protent.open)(0);
560                 }
561                 open_ccp_flag = 0;
562             }
563             reap_kids();        /* Don't leave dead kids lying around */
564         }
565
566         /*
567          * If we may want to bring the link up again, transfer
568          * the ppp unit back to the loopback.  Set the
569          * real serial device back to its normal mode of operation.
570          */
571         clean_check();
572         if (demand)
573             restore_loop();
574         disestablish_ppp(ttyfd);
575
576         /*
577          * Run disconnector script, if requested.
578          * XXX we may not be able to do this if the line has hung up!
579          */
580         if (disconnector && !hungup) {
581             set_up_tty(ttyfd, 1);
582             if (device_script(disconnector, ttyfd, ttyfd) < 0) {
583                 syslog(LOG_WARNING, "disconnect script failed");
584             } else {
585                 syslog(LOG_INFO, "Serial link disconnected.");
586             }
587         }
588
589     fail:
590         if (ttyfd >= 0)
591             close_tty();
592         if (locked) {
593             unlock();
594             locked = 0;
595         }
596
597         if (!demand) {
598             if (pidfilename[0] != 0
599                 && unlink(pidfilename) < 0 && errno != ENOENT) 
600                 syslog(LOG_WARNING, "unable to delete pid file: %m");
601             pidfilename[0] = 0;
602         }
603
604         if (!persist)
605             break;
606
607         if (demand)
608             demand_discard();
609         if (holdoff > 0 && need_holdoff) {
610             phase = PHASE_HOLDOFF;
611             TIMEOUT(holdoff_end, NULL, holdoff);
612             do {
613                 if (setjmp(sigjmp) == 0) {
614                     waiting = 1;
615                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
616                     wait_time(timeleft(&timo));
617                 }
618                 sigprocmask(SIG_BLOCK, &mask, NULL);
619                 waiting = 0;
620                 calltimeout();
621                 if (kill_link) {
622                     kill_link = 0;
623                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
624                 }
625                 reap_kids();
626             } while (phase == PHASE_HOLDOFF);
627             if (!persist)
628                 break;
629         }
630     }
631
632     /* Wait for scripts to finish */
633     while (n_children > 0)
634         reap_kids();
635
636     die(0);
637     return 0;
638 }
639
640 /*
641  * detach - detach us from the controlling terminal.
642  */
643 void
644 detach()
645 {
646     if (detached)
647         return;
648     if (daemon(0, 0) < 0) {
649         perror("Couldn't detach from controlling terminal");
650         die(1);
651     }
652     detached = 1;
653     pid = getpid();
654     /* update pid file if it has been written already */
655     if (pidfilename[0])
656         create_pidfile();
657 }
658
659 /*
660  * Create a file containing our process ID.
661  */
662 static void
663 create_pidfile()
664 {
665     FILE *pidfile;
666     char numbuf[16];
667
668     (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
669     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
670         fprintf(pidfile, "%d\n", pid);
671         (void) fclose(pidfile);
672     } else {
673         syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
674         pidfilename[0] = 0;
675     }
676     sprintf(numbuf, "%d", pid);
677     script_setenv("PPPD_PID", numbuf);
678 }
679
680 /*
681  * holdoff_end - called via a timeout when the holdoff period ends.
682  */
683 static void
684 holdoff_end(arg)
685     void *arg;
686 {
687     phase = PHASE_DORMANT;
688 }
689
690 /*
691  * get_input - called when incoming data is available.
692  */
693 static void
694 get_input()
695 {
696     int len, i;
697     u_char *p;
698     u_short protocol;
699     struct protent *protp;
700
701     p = inpacket_buf;   /* point to beginning of packet buffer */
702
703     len = read_packet(inpacket_buf);
704     if (len < 0)
705         return;
706
707     if (len == 0) {
708         syslog(LOG_NOTICE, "Modem hangup");
709         hungup = 1;
710         lcp_lowerdown(0);       /* serial link is no longer available */
711         link_terminated(0);
712         return;
713     }
714
715     if (debug /*&& (debugflags & DBG_INPACKET)*/)
716         log_packet(p, len, "rcvd ", LOG_DEBUG);
717
718     if (len < PPP_HDRLEN) {
719         MAINDEBUG((LOG_INFO, "io(): Received short packet."));
720         return;
721     }
722
723     p += 2;                             /* Skip address and control */
724     GETSHORT(protocol, p);
725     len -= PPP_HDRLEN;
726
727     /*
728      * Toss all non-LCP packets unless LCP is OPEN.
729      */
730     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
731         MAINDEBUG((LOG_INFO,
732                    "get_input: Received non-LCP packet when LCP not open."));
733         return;
734     }
735
736     /*
737      * Until we get past the authentication phase, toss all packets
738      * except LCP, LQR and authentication packets.
739      */
740     if (phase <= PHASE_AUTHENTICATE
741         && !(protocol == PPP_LCP || protocol == PPP_LQR
742              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
743         MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
744                    protocol, phase));
745         return;
746     }
747
748     /*
749      * Upcall the proper protocol input routine.
750      */
751     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
752         if (protp->protocol == protocol && protp->enabled_flag) {
753             (*protp->input)(0, p, len);
754             return;
755         }
756         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
757             && protp->datainput != NULL) {
758             (*protp->datainput)(0, p, len);
759             return;
760         }
761     }
762
763     if (debug)
764         syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
765     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
766 }
767
768
769 /*
770  * quit - Clean up state and exit (with an error indication).
771  */
772 void 
773 quit()
774 {
775     die(1);
776 }
777
778 /*
779  * die - like quit, except we can specify an exit status.
780  */
781 void
782 die(status)
783     int status;
784 {
785     cleanup();
786     syslog(LOG_INFO, "Exit.");
787     exit(status);
788 }
789
790 /*
791  * cleanup - restore anything which needs to be restored before we exit
792  */
793 /* ARGSUSED */
794 static void
795 cleanup()
796 {
797     sys_cleanup();
798
799     if (ttyfd >= 0)
800         close_tty();
801
802     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
803         syslog(LOG_WARNING, "unable to delete pid file: %m");
804     pidfilename[0] = 0;
805
806     if (locked)
807         unlock();
808 }
809
810 /*
811  * close_tty - restore the terminal device and close it.
812  */
813 static void
814 close_tty()
815 {
816     disestablish_ppp(ttyfd);
817
818     /* drop dtr to hang up */
819     if (!default_device && modem) {
820         hangup_modem(ttyfd);
821         /*
822          * This sleep is in case the serial port has CLOCAL set by default,
823          * and consequently will reassert DTR when we close the device.
824          */
825         sleep(1);
826     }
827
828     restore_tty(ttyfd);
829
830     if (tty_mode != (mode_t) -1) {
831         if (fchmod(devnam, tty_mode) != 0) {
832             /* XXX if devnam is a symlink, this will change the link */
833             chmod(devnam, tty_mode);
834         }
835     }
836
837     close(ttyfd);
838     ttyfd = -1;
839 }
840
841
842 struct  callout {
843     struct timeval      c_time;         /* time at which to call routine */
844     void                *c_arg;         /* argument to routine */
845     void                (*c_func) __P((void *)); /* routine */
846     struct              callout *c_next;
847 };
848
849 static struct callout *callout = NULL;  /* Callout list */
850 static struct timeval timenow;          /* Current time */
851
852 /*
853  * timeout - Schedule a timeout.
854  *
855  * Note that this timeout takes the number of seconds, NOT hz (as in
856  * the kernel).
857  */
858 void
859 timeout(func, arg, time)
860     void (*func) __P((void *));
861     void *arg;
862     int time;
863 {
864     struct callout *newp, *p, **pp;
865   
866     MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
867                (long) func, (long) arg, time));
868   
869     /*
870      * Allocate timeout.
871      */
872     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
873         syslog(LOG_ERR, "Out of memory in timeout()!");
874         die(1);
875     }
876     newp->c_arg = arg;
877     newp->c_func = func;
878     gettimeofday(&timenow, NULL);
879     newp->c_time.tv_sec = timenow.tv_sec + time;
880     newp->c_time.tv_usec = timenow.tv_usec;
881   
882     /*
883      * Find correct place and link it in.
884      */
885     for (pp = &callout; (p = *pp); pp = &p->c_next)
886         if (newp->c_time.tv_sec < p->c_time.tv_sec
887             || (newp->c_time.tv_sec == p->c_time.tv_sec
888                 && newp->c_time.tv_usec < p->c_time.tv_usec))
889             break;
890     newp->c_next = p;
891     *pp = newp;
892 }
893
894
895 /*
896  * untimeout - Unschedule a timeout.
897  */
898 void
899 untimeout(func, arg)
900     void (*func) __P((void *));
901     void *arg;
902 {
903     struct callout **copp, *freep;
904   
905     MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
906   
907     /*
908      * Find first matching timeout and remove it from the list.
909      */
910     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
911         if (freep->c_func == func && freep->c_arg == arg) {
912             *copp = freep->c_next;
913             (void) free((char *) freep);
914             break;
915         }
916 }
917
918
919 /*
920  * calltimeout - Call any timeout routines which are now due.
921  */
922 static void
923 calltimeout()
924 {
925     struct callout *p;
926
927     while (callout != NULL) {
928         p = callout;
929
930         if (gettimeofday(&timenow, NULL) < 0) {
931             syslog(LOG_ERR, "Failed to get time of day: %m");
932             die(1);
933         }
934         if (!(p->c_time.tv_sec < timenow.tv_sec
935               || (p->c_time.tv_sec == timenow.tv_sec
936                   && p->c_time.tv_usec <= timenow.tv_usec)))
937             break;              /* no, it's not time yet */
938
939         callout = p->c_next;
940         (*p->c_func)(p->c_arg);
941
942         free((char *) p);
943     }
944 }
945
946
947 /*
948  * timeleft - return the length of time until the next timeout is due.
949  */
950 static struct timeval *
951 timeleft(tvp)
952     struct timeval *tvp;
953 {
954     if (callout == NULL)
955         return NULL;
956
957     gettimeofday(&timenow, NULL);
958     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
959     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
960     if (tvp->tv_usec < 0) {
961         tvp->tv_usec += 1000000;
962         tvp->tv_sec -= 1;
963     }
964     if (tvp->tv_sec < 0)
965         tvp->tv_sec = tvp->tv_usec = 0;
966
967     return tvp;
968 }
969
970
971 /*
972  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
973  */
974 static void
975 kill_my_pg(sig)
976     int sig;
977 {
978     struct sigaction act, oldact;
979
980     act.sa_handler = SIG_IGN;
981     act.sa_flags = 0;
982     kill(0, sig);
983     sigaction(sig, &act, &oldact);
984     sigaction(sig, &oldact, NULL);
985 }
986
987
988 /*
989  * hup - Catch SIGHUP signal.
990  *
991  * Indicates that the physical layer has been disconnected.
992  * We don't rely on this indication; if the user has sent this
993  * signal, we just take the link down.
994  */
995 static void
996 hup(sig)
997     int sig;
998 {
999     syslog(LOG_INFO, "Hangup (SIGHUP)");
1000     kill_link = 1;
1001     if (conn_running)
1002         /* Send the signal to the [dis]connector process(es) also */
1003         kill_my_pg(sig);
1004     if (waiting)
1005         longjmp(sigjmp, 1);
1006 }
1007
1008
1009 /*
1010  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1011  *
1012  * Indicates that we should initiate a graceful disconnect and exit.
1013  */
1014 /*ARGSUSED*/
1015 static void
1016 term(sig)
1017     int sig;
1018 {
1019     syslog(LOG_INFO, "Terminating on signal %d.", sig);
1020     persist = 0;                /* don't try to restart */
1021     kill_link = 1;
1022     if (conn_running)
1023         /* Send the signal to the [dis]connector process(es) also */
1024         kill_my_pg(sig);
1025     if (waiting)
1026         longjmp(sigjmp, 1);
1027 }
1028
1029
1030 /*
1031  * chld - Catch SIGCHLD signal.
1032  * Calls reap_kids to get status for any dead kids.
1033  */
1034 static void
1035 chld(sig)
1036     int sig;
1037 {
1038     if (waiting)
1039         longjmp(sigjmp, 1);
1040 }
1041
1042
1043 /*
1044  * toggle_debug - Catch SIGUSR1 signal.
1045  *
1046  * Toggle debug flag.
1047  */
1048 /*ARGSUSED*/
1049 static void
1050 toggle_debug(sig)
1051     int sig;
1052 {
1053     debug = !debug;
1054     if (debug) {
1055         setlogmask(LOG_UPTO(LOG_DEBUG));
1056     } else {
1057         setlogmask(LOG_UPTO(LOG_WARNING));
1058     }
1059 }
1060
1061
1062 /*
1063  * open_ccp - Catch SIGUSR2 signal.
1064  *
1065  * Try to (re)negotiate compression.
1066  */
1067 /*ARGSUSED*/
1068 static void
1069 open_ccp(sig)
1070     int sig;
1071 {
1072     open_ccp_flag = 1;
1073     if (waiting)
1074         longjmp(sigjmp, 1);
1075 }
1076
1077
1078 /*
1079  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1080  */
1081 static void
1082 bad_signal(sig)
1083     int sig;
1084 {
1085     static int crashed = 0;
1086
1087     if (crashed)
1088         _exit(127);
1089     crashed = 1;
1090     syslog(LOG_ERR, "Fatal signal %d", sig);
1091     if (conn_running)
1092         kill_my_pg(SIGTERM);
1093     die(1);
1094 }
1095
1096
1097 /*
1098  * device_script - run a program to connect or disconnect the
1099  * serial device.
1100  */
1101 static int
1102 device_script(program, in, out)
1103     char *program;
1104     int in, out;
1105 {
1106     int pid;
1107     int status;
1108     int errfd;
1109
1110     conn_running = 1;
1111     pid = fork();
1112
1113     if (pid < 0) {
1114         conn_running = 0;
1115         syslog(LOG_ERR, "Failed to create child process: %m");
1116         die(1);
1117     }
1118
1119     if (pid == 0) {
1120         sys_close();
1121         closelog();
1122         if (in == out) {
1123             if (in != 0) {
1124                 dup2(in, 0);
1125                 close(in);
1126             }
1127             dup2(0, 1);
1128         } else {
1129             if (out == 0)
1130                 out = dup(out);
1131             if (in != 0) {
1132                 dup2(in, 0);
1133                 close(in);
1134             }
1135             if (out != 1) {
1136                 dup2(out, 1);
1137                 close(out);
1138             }
1139         }
1140         if (!nodetach && !updetach) {
1141             close(2);
1142             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1143             if (errfd >= 0 && errfd != 2) {
1144                 dup2(errfd, 2);
1145                 close(errfd);
1146             }
1147         }
1148         setuid(getuid());
1149         setgid(getgid());
1150         execl("/bin/sh", "sh", "-c", program, (char *)0);
1151         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1152         _exit(99);
1153         /* NOTREACHED */
1154     }
1155
1156     while (waitpid(pid, &status, 0) < 0) {
1157         if (errno == EINTR)
1158             continue;
1159         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1160         die(1);
1161     }
1162     conn_running = 0;
1163
1164     return (status == 0 ? 0 : -1);
1165 }
1166
1167
1168 /*
1169  * We maintain a list of child process pids and
1170  * functions to call when they exit.
1171  */
1172 struct subprocess {
1173     pid_t       pid;
1174     char        *prog;
1175     void        (*done) __P((void *));
1176     void        *arg;
1177     struct subprocess *next;
1178 };
1179
1180 struct subprocess *children;
1181
1182 /*
1183  * run-program - execute a program with given arguments,
1184  * but don't wait for it.
1185  * If the program can't be executed, logs an error unless
1186  * must_exist is 0 and the program file doesn't exist.
1187  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1188  * or isn't an executable plain file, or the process ID of the child.
1189  * If done != NULL, (*done)(arg) will be called later (within
1190  * reap_kids) iff the return value is > 0.
1191  */
1192 pid_t
1193 run_program(prog, args, must_exist, done, arg)
1194     char *prog;
1195     char **args;
1196     int must_exist;
1197     void (*done) __P((void *));
1198     void *arg;
1199 {
1200     int pid;
1201     struct subprocess *chp;
1202     struct stat sbuf;
1203
1204     /*
1205      * First check if the file exists and is executable.
1206      * We don't use access() because that would use the
1207      * real user-id, which might not be root, and the script
1208      * might be accessible only to root.
1209      */
1210     errno = EINVAL;
1211     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1212         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1213         if (must_exist || errno != ENOENT)
1214             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1215         return 0;
1216     }
1217
1218     pid = fork();
1219     if (pid == -1) {
1220         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1221         die(1);
1222     }
1223     if (pid == 0) {
1224         int new_fd;
1225
1226         /* Leave the current location */
1227         (void) setsid();    /* No controlling tty. */
1228         (void) umask (S_IRWXG|S_IRWXO);
1229         (void) chdir ("/"); /* no current directory. */
1230         setuid(geteuid());
1231         setgid(getegid());
1232
1233         /* Ensure that nothing of our device environment is inherited. */
1234         sys_close();
1235         closelog();
1236         close (0);
1237         close (1);
1238         close (2);
1239         close (ttyfd);  /* tty interface to the ppp device */
1240
1241         /* Don't pass handles to the PPP device, even by accident. */
1242         new_fd = open (_PATH_DEVNULL, O_RDWR);
1243         if (new_fd >= 0) {
1244             if (new_fd != 0) {
1245                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1246                 close (new_fd);
1247             }
1248             dup2 (0, 1); /* stdout -> /dev/null */
1249             dup2 (0, 2); /* stderr -> /dev/null */
1250         }
1251
1252 #ifdef BSD
1253         /* Force the priority back to zero if pppd is running higher. */
1254         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1255             syslog (LOG_WARNING, "can't reset priority to 0: %m"); 
1256 #endif
1257
1258         /* SysV recommends a second fork at this point. */
1259
1260         /* run the program */
1261         execve(prog, args, script_env);
1262         if (must_exist || errno != ENOENT) {
1263             int i;
1264             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1265             for (i = 0; args[i]; ++i)
1266                 syslog(LOG_DEBUG, "args[%d] = '%s'", i, args[i]);
1267             for (i = 0; script_env[i]; ++i)
1268                 syslog(LOG_DEBUG, "env[%d] = '%s'", i, script_env[i]);
1269         }
1270         _exit(-1);
1271     }
1272
1273     if (debug)
1274         syslog(LOG_DEBUG, "Script %s started; pid = %d", prog, pid);
1275     ++n_children;
1276
1277     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1278     if (chp == NULL) {
1279         syslog(LOG_WARNING, "losing track of %s process", prog);
1280     } else {
1281         chp->pid = pid;
1282         chp->prog = prog;
1283         chp->done = done;
1284         chp->arg = arg;
1285         chp->next = children;
1286         children = chp;
1287     }
1288
1289     return pid;
1290 }
1291
1292
1293 /*
1294  * reap_kids - get status from any dead child processes,
1295  * and log a message for abnormal terminations.
1296  */
1297 static void
1298 reap_kids()
1299 {
1300     int pid, status;
1301     struct subprocess *chp, **prevp;
1302
1303     if (n_children == 0)
1304         return;
1305     while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1306         --n_children;
1307         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1308             if (chp->pid == pid)
1309                 break;
1310         if (debug)
1311             syslog(LOG_DEBUG, "process %d (%s) finished, status = 0x%x",
1312                    pid, (chp? chp->prog: "??"), status);
1313         if (WIFSIGNALED(status)) {
1314             syslog(LOG_WARNING,
1315                    "Child process %s (pid %d) terminated with signal %d",
1316                    (chp? chp->prog: "??"), pid, WTERMSIG(status));
1317         }
1318         if (chp && chp->done)
1319             (*chp->done)(chp->arg);
1320     }
1321     if (pid == -1 && errno != ECHILD)
1322         syslog(LOG_ERR, "Error waiting for child process: %m");
1323 }
1324
1325
1326 /*
1327  * log_packet - format a packet and log it.
1328  */
1329
1330 char line[256];                 /* line to be logged accumulated here */
1331 char *linep;
1332
1333 void
1334 log_packet(p, len, prefix, level)
1335     u_char *p;
1336     int len;
1337     char *prefix;
1338     int level;
1339 {
1340     strcpy(line, prefix);
1341     linep = line + strlen(line);
1342     format_packet(p, len, pr_log, NULL);
1343     if (linep != line)
1344         syslog(level, "%s", line);
1345 }
1346
1347 /*
1348  * format_packet - make a readable representation of a packet,
1349  * calling `printer(arg, format, ...)' to output it.
1350  */
1351 void
1352 format_packet(p, len, printer, arg)
1353     u_char *p;
1354     int len;
1355     void (*printer) __P((void *, char *, ...));
1356     void *arg;
1357 {
1358     int i, n;
1359     u_short proto;
1360     u_char x;
1361     struct protent *protp;
1362
1363     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1364         p += 2;
1365         GETSHORT(proto, p);
1366         len -= PPP_HDRLEN;
1367         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1368             if (proto == protp->protocol)
1369                 break;
1370         if (protp != NULL) {
1371             printer(arg, "[%s", protp->name);
1372             n = (*protp->printpkt)(p, len, printer, arg);
1373             printer(arg, "]");
1374             p += n;
1375             len -= n;
1376         } else {
1377             printer(arg, "[proto=0x%x]", proto);
1378         }
1379     }
1380
1381     for (; len > 0; --len) {
1382         GETCHAR(x, p);
1383         printer(arg, " %.2x", x);
1384     }
1385 }
1386
1387 static void
1388 pr_log __V((void *arg, char *fmt, ...))
1389 {
1390     int n;
1391     va_list pvar;
1392     char buf[256];
1393
1394 #if __STDC__
1395     va_start(pvar, fmt);
1396 #else
1397     void *arg;
1398     char *fmt;
1399     va_start(pvar);
1400     arg = va_arg(pvar, void *);
1401     fmt = va_arg(pvar, char *);
1402 #endif
1403
1404     n = vfmtmsg(buf, sizeof(buf), fmt, pvar);
1405     va_end(pvar);
1406
1407     if (linep + n + 1 > line + sizeof(line)) {
1408         syslog(LOG_DEBUG, "%s", line);
1409         linep = line;
1410     }
1411     strcpy(linep, buf);
1412     linep += n;
1413 }
1414
1415 /*
1416  * print_string - print a readable representation of a string using
1417  * printer.
1418  */
1419 void
1420 print_string(p, len, printer, arg)
1421     char *p;
1422     int len;
1423     void (*printer) __P((void *, char *, ...));
1424     void *arg;
1425 {
1426     int c;
1427
1428     printer(arg, "\"");
1429     for (; len > 0; --len) {
1430         c = *p++;
1431         if (' ' <= c && c <= '~') {
1432             if (c == '\\' || c == '"')
1433                 printer(arg, "\\");
1434             printer(arg, "%c", c);
1435         } else {
1436             switch (c) {
1437             case '\n':
1438                 printer(arg, "\\n");
1439                 break;
1440             case '\r':
1441                 printer(arg, "\\r");
1442                 break;
1443             case '\t':
1444                 printer(arg, "\\t");
1445                 break;
1446             default:
1447                 printer(arg, "\\%.3o", c);
1448             }
1449         }
1450     }
1451     printer(arg, "\"");
1452 }
1453
1454 /*
1455  * novm - log an error message saying we ran out of memory, and die.
1456  */
1457 void
1458 novm(msg)
1459     char *msg;
1460 {
1461     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1462     die(1);
1463 }
1464
1465 /*
1466  * fmtmsg - format a message into a buffer.  Like sprintf except we
1467  * also specify the length of the output buffer, and we handle
1468  * %r (recursive format), %m (error message) and %I (IP address) formats.
1469  * Doesn't do floating-point formats.
1470  * Returns the number of chars put into buf.
1471  */
1472 int
1473 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1474 {
1475     va_list args;
1476     int n;
1477
1478 #if __STDC__
1479     va_start(args, fmt);
1480 #else
1481     char *buf;
1482     int buflen;
1483     char *fmt;
1484     va_start(args);
1485     buf = va_arg(args, char *);
1486     buflen = va_arg(args, int);
1487     fmt = va_arg(args, char *);
1488 #endif
1489     n = vfmtmsg(buf, buflen, fmt, args);
1490     va_end(args);
1491     return n;
1492 }
1493
1494 /*
1495  * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1496  */
1497 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1498
1499 int
1500 vfmtmsg(buf, buflen, fmt, args)
1501     char *buf;
1502     int buflen;
1503     char *fmt;
1504     va_list args;
1505 {
1506     int c, i, n;
1507     int width, prec, fillch;
1508     int base, len, neg, quoted;
1509     unsigned long val = 0;
1510     char *str, *f, *buf0;
1511     unsigned char *p;
1512     char num[32];
1513     time_t t;
1514     static char hexchars[] = "0123456789abcdef";
1515
1516     buf0 = buf;
1517     --buflen;
1518     while (buflen > 0) {
1519         for (f = fmt; *f != '%' && *f != 0; ++f)
1520             ;
1521         if (f > fmt) {
1522             len = f - fmt;
1523             if (len > buflen)
1524                 len = buflen;
1525             memcpy(buf, fmt, len);
1526             buf += len;
1527             buflen -= len;
1528             fmt = f;
1529         }
1530         if (*fmt == 0)
1531             break;
1532         c = *++fmt;
1533         width = prec = 0;
1534         fillch = ' ';
1535         if (c == '0') {
1536             fillch = '0';
1537             c = *++fmt;
1538         }
1539         if (c == '*') {
1540             width = va_arg(args, int);
1541             c = *++fmt;
1542         } else {
1543             while (isdigit(c)) {
1544                 width = width * 10 + c - '0';
1545                 c = *++fmt;
1546             }
1547         }
1548         if (c == '.') {
1549             c = *++fmt;
1550             if (c == '*') {
1551                 prec = va_arg(args, int);
1552                 c = *++fmt;
1553             } else {
1554                 while (isdigit(c)) {
1555                     prec = prec * 10 + c - '0';
1556                     c = *++fmt;
1557                 }
1558             }
1559         }
1560         str = 0;
1561         base = 0;
1562         neg = 0;
1563         ++fmt;
1564         switch (c) {
1565         case 'd':
1566             i = va_arg(args, int);
1567             if (i < 0) {
1568                 neg = 1;
1569                 val = -i;
1570             } else
1571                 val = i;
1572             base = 10;
1573             break;
1574         case 'o':
1575             val = va_arg(args, unsigned int);
1576             base = 8;
1577             break;
1578         case 'x':
1579             val = va_arg(args, unsigned int);
1580             base = 16;
1581             break;
1582         case 'p':
1583             val = (unsigned long) va_arg(args, void *);
1584             base = 16;
1585             neg = 2;
1586             break;
1587         case 's':
1588             str = va_arg(args, char *);
1589             break;
1590         case 'c':
1591             num[0] = va_arg(args, int);
1592             num[1] = 0;
1593             str = num;
1594             break;
1595         case 'm':
1596             str = strerror(errno);
1597             break;
1598         case 'I':
1599             str = ip_ntoa(va_arg(args, u_int32_t));
1600             break;
1601         case 'r':
1602             f = va_arg(args, char *);
1603 #ifndef __powerpc__
1604             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1605 #else
1606             /* On the powerpc, a va_list is an array of 1 structure */
1607             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1608 #endif
1609             buf += n;
1610             buflen -= n;
1611             continue;
1612         case 't':
1613             time(&t);
1614             str = ctime(&t);
1615             str += 4;           /* chop off the day name */
1616             str[15] = 0;        /* chop off year and newline */
1617             break;
1618         case 'v':               /* "visible" string */
1619         case 'q':               /* quoted string */
1620             quoted = c == 'q';
1621             p = va_arg(args, unsigned char *);
1622             if (fillch == '0' && prec > 0) {
1623                 n = prec;
1624             } else {
1625                 n = strlen((char *)p);
1626                 if (prec > 0 && prec < n)
1627                     n = prec;
1628             }
1629             while (n > 0 && buflen > 0) {
1630                 c = *p++;
1631                 --n;
1632                 if (!quoted && c >= 0x80) {
1633                     OUTCHAR('M');
1634                     OUTCHAR('-');
1635                     c -= 0x80;
1636                 }
1637                 if (quoted && (c == '"' || c == '\\'))
1638                     OUTCHAR('\\');
1639                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1640                     if (quoted) {
1641                         OUTCHAR('\\');
1642                         switch (c) {
1643                         case '\t':      OUTCHAR('t');   break;
1644                         case '\n':      OUTCHAR('n');   break;
1645                         case '\b':      OUTCHAR('b');   break;
1646                         case '\f':      OUTCHAR('f');   break;
1647                         default:
1648                             OUTCHAR('x');
1649                             OUTCHAR(hexchars[c >> 4]);
1650                             OUTCHAR(hexchars[c & 0xf]);
1651                         }
1652                     } else {
1653                         if (c == '\t')
1654                             OUTCHAR(c);
1655                         else {
1656                             OUTCHAR('^');
1657                             OUTCHAR(c ^ 0x40);
1658                         }
1659                     }
1660                 } else
1661                     OUTCHAR(c);
1662             }
1663             continue;
1664         default:
1665             *buf++ = '%';
1666             if (c != '%')
1667                 --fmt;          /* so %z outputs %z etc. */
1668             --buflen;
1669             continue;
1670         }
1671         if (base != 0) {
1672             str = num + sizeof(num);
1673             *--str = 0;
1674             while (str > num + neg) {
1675                 *--str = hexchars[val % base];
1676                 val = val / base;
1677                 if (--prec <= 0 && val == 0)
1678                     break;
1679             }
1680             switch (neg) {
1681             case 1:
1682                 *--str = '-';
1683                 break;
1684             case 2:
1685                 *--str = 'x';
1686                 *--str = '0';
1687                 break;
1688             }
1689             len = num + sizeof(num) - 1 - str;
1690         } else {
1691             len = strlen(str);
1692             if (prec > 0 && len > prec)
1693                 len = prec;
1694         }
1695         if (width > 0) {
1696             if (width > buflen)
1697                 width = buflen;
1698             if ((n = width - len) > 0) {
1699                 buflen -= n;
1700                 for (; n > 0; --n)
1701                     *buf++ = fillch;
1702             }
1703         }
1704         if (len > buflen)
1705             len = buflen;
1706         memcpy(buf, str, len);
1707         buf += len;
1708         buflen -= len;
1709     }
1710     *buf = 0;
1711     return buf - buf0;
1712 }
1713
1714 /*
1715  * script_setenv - set an environment variable value to be used
1716  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1717  */
1718 void
1719 script_setenv(var, value)
1720     char *var, *value;
1721 {
1722     int vl = strlen(var);
1723     int i;
1724     char *p, *newstring;
1725
1726     newstring = (char *) malloc(vl + strlen(value) + 2);
1727     if (newstring == 0)
1728         return;
1729     strcpy(newstring, var);
1730     newstring[vl] = '=';
1731     strcpy(newstring+vl+1, value);
1732
1733     /* check if this variable is already set */
1734     if (script_env != 0) {
1735         for (i = 0; (p = script_env[i]) != 0; ++i) {
1736             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1737                 free(p);
1738                 script_env[i] = newstring;
1739                 return;
1740             }
1741         }
1742     } else {
1743         i = 0;
1744         script_env = (char **) malloc(16 * sizeof(char *));
1745         if (script_env == 0)
1746             return;
1747         s_env_nalloc = 16;
1748     }
1749
1750     /* reallocate script_env with more space if needed */
1751     if (i + 1 >= s_env_nalloc) {
1752         int new_n = i + 17;
1753         char **newenv = (char **) realloc((void *)script_env,
1754                                           new_n * sizeof(char *));
1755         if (newenv == 0)
1756             return;
1757         script_env = newenv;
1758         s_env_nalloc = new_n;
1759     }
1760
1761     script_env[i] = newstring;
1762     script_env[i+1] = 0;
1763 }
1764
1765 /*
1766  * script_unsetenv - remove a variable from the environment
1767  * for scripts.
1768  */
1769 void
1770 script_unsetenv(var)
1771     char *var;
1772 {
1773     int vl = strlen(var);
1774     int i;
1775     char *p;
1776
1777     if (script_env == 0)
1778         return;
1779     for (i = 0; (p = script_env[i]) != 0; ++i) {
1780         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1781             free(p);
1782             while ((script_env[i] = script_env[i+1]) != 0)
1783                 ++i;
1784             break;
1785         }
1786     }
1787 }