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