Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / usr.sbin / 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  * $FreeBSD: src/usr.sbin/pppd/main.c,v 1.19.2.1 2002/07/30 03:50:40 peter Exp $
20  * $DragonFly: src/usr.sbin/pppd/main.c,v 1.2 2003/06/17 04:30:01 dillon Exp $
21  */
22
23 #include <stdio.h>
24 #include <ctype.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <signal.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <syslog.h>
32 #include <netdb.h>
33 #include <utmp.h>
34 #include <pwd.h>
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <sys/time.h>
39 #include <sys/resource.h>
40 #include <sys/stat.h>
41 #include <sys/socket.h>
42
43 #include "pppd.h"
44 #include "magic.h"
45 #include "fsm.h"
46 #include "lcp.h"
47 #include "ipcp.h"
48 #include "upap.h"
49 #include "chap.h"
50 #include "ccp.h"
51 #include "pathnames.h"
52 #include "patchlevel.h"
53
54 #ifdef CBCP_SUPPORT
55 #include "cbcp.h"
56 #endif
57
58 #if defined(SUNOS4)
59 extern char *strerror();
60 #endif
61
62 #ifdef IPX_CHANGE
63 #include "ipxcp.h"
64 #endif /* IPX_CHANGE */
65 #ifdef AT_CHANGE
66 #include "atcp.h"
67 #endif
68
69 /* interface vars */
70 char ifname[32];                /* Interface name */
71 int ifunit;                     /* Interface unit number */
72
73 char *progname;                 /* Name of this program */
74 char hostname[MAXNAMELEN];      /* Our hostname */
75 static char pidfilename[MAXPATHLEN];    /* name of pid file */
76 static char iffilename[MAXPATHLEN];     /* name of if file */
77 static char default_devnam[MAXPATHLEN]; /* name of default device */
78 static pid_t pid;               /* Our pid */
79 static uid_t uid;               /* Our real user-id */
80 time_t          etime,stime;    /* End and Start time */
81 int             minutes;        /* connection duration */
82 static int conn_running;        /* we have a [dis]connector running */
83
84 int ttyfd = -1;                 /* Serial port file descriptor */
85 mode_t tty_mode = -1;           /* Original access permissions to tty */
86 int baud_rate;                  /* Actual bits/second for serial device */
87 int hungup;                     /* terminal has been hung up */
88 int privileged;                 /* we're running as real uid root */
89 int need_holdoff;               /* need holdoff period before restarting */
90 int detached;                   /* have detached from terminal */
91
92 int phase;                      /* where the link is at */
93 int kill_link;
94 int open_ccp_flag;
95
96 char **script_env;              /* Env. variable values for scripts */
97 int s_env_nalloc;               /* # words avail at script_env */
98
99 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
100 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
101
102 static int n_children;          /* # child processes still running */
103
104 static int locked;              /* lock() has succeeded */
105
106 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
107
108 /* Prototypes for procedures local to this file. */
109
110 static void create_pidfile __P((void));
111 static void cleanup __P((void));
112 static void close_tty __P((void));
113 static void get_input __P((void));
114 static void calltimeout __P((void));
115 static struct timeval *timeleft __P((struct timeval *));
116 static void kill_my_pg __P((int));
117 static void hup __P((int));
118 static void term __P((int));
119 static void chld __P((int));
120 static void toggle_debug __P((int));
121 static void open_ccp __P((int));
122 static void bad_signal __P((int));
123 static void holdoff_end __P((void *));
124 static int device_script __P((char *, int, int));
125 static void reap_kids __P((void));
126 static void pr_log __P((void *, char *, ...));
127
128 extern  char    *ttyname __P((int));
129 extern  char    *getlogin __P((void));
130 int main __P((int, char *[]));
131
132 #ifdef ultrix
133 #undef  O_NONBLOCK
134 #define O_NONBLOCK      O_NDELAY
135 #endif
136
137 #ifdef ULTRIX
138 #define setlogmask(x)
139 #endif
140
141 /*
142  * PPP Data Link Layer "protocol" table.
143  * One entry per supported protocol.
144  * The last entry must be NULL.
145  */
146 struct protent *protocols[] = {
147     &lcp_protent,
148     &pap_protent,
149     &chap_protent,
150 #ifdef CBCP_SUPPORT
151     &cbcp_protent,
152 #endif
153     &ipcp_protent,
154     &ccp_protent,
155 #ifdef IPX_CHANGE
156     &ipxcp_protent,
157 #endif
158 #ifdef AT_CHANGE
159     &atcp_protent,
160 #endif
161     NULL
162 };
163
164 int
165 main(argc, argv)
166     int argc;
167     char *argv[];
168 {
169     int i, n, fdflags;
170     struct sigaction sa;
171     FILE *iffile;
172     char *p;
173     struct passwd *pw;
174     struct timeval timo;
175     sigset_t mask;
176     struct protent *protp;
177     struct stat statbuf;
178     int connect_attempts = 0;
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         die(1);
200     }
201     hostname[MAXNAMELEN-1] = 0;
202
203     uid = getuid();
204     privileged = uid == 0;
205     sprintf(numbuf, "%d", uid);
206     script_setenv("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         die(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     sys_check_options();
244     auth_check_options();
245     for (i = 0; (protp = protocols[i]) != NULL; ++i)
246         if (protp->check_options != NULL)
247             (*protp->check_options)();
248     if (demand && connector == 0) {
249         option_error("connect script required for demand-dialling\n");
250         exit(1);
251     }
252
253     script_setenv("DEVICE", devnam);
254     sprintf(numbuf, "%d", baud_rate);
255     script_setenv("SPEED", numbuf);
256
257     /*
258      * If the user has specified the default device name explicitly,
259      * pretend they hadn't.
260      */
261     if (!default_device && strcmp(devnam, default_devnam) == 0)
262         default_device = 1;
263     if (default_device)
264         nodetach = 1;
265
266     /*
267      * Initialize system-dependent stuff and magic number package.
268      */
269     sys_init();
270     magic_init();
271     if (debug)
272         setlogmask(LOG_UPTO(LOG_DEBUG));
273
274     /*
275      * Detach ourselves from the terminal, if required,
276      * and identify who is running us.
277      */
278     if (nodetach == 0)
279         detach();
280     pid = getpid();
281     p = getlogin();
282     stime = time((time_t *) NULL);
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
304 #define SIGNAL(s, handler)      { \
305         sa.sa_handler = handler; \
306         if (sigaction(s, &sa, NULL) < 0) { \
307             syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
308             die(1); \
309         } \
310     }
311
312     sa.sa_mask = mask;
313     sa.sa_flags = 0;
314     SIGNAL(SIGHUP, hup);                /* Hangup */
315     SIGNAL(SIGINT, term);               /* Interrupt */
316     SIGNAL(SIGTERM, term);              /* Terminate */
317     SIGNAL(SIGCHLD, chld);
318
319     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
320     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
321
322     /*
323      * Install a handler for other signals which would otherwise
324      * cause pppd to exit without cleaning up.
325      */
326     SIGNAL(SIGABRT, bad_signal);
327     SIGNAL(SIGALRM, bad_signal);
328     SIGNAL(SIGFPE, bad_signal);
329     SIGNAL(SIGILL, bad_signal);
330     SIGNAL(SIGPIPE, bad_signal);
331     SIGNAL(SIGQUIT, bad_signal);
332     SIGNAL(SIGSEGV, bad_signal);
333 #ifdef SIGBUS
334     SIGNAL(SIGBUS, bad_signal);
335 #endif
336 #ifdef SIGEMT
337     SIGNAL(SIGEMT, bad_signal);
338 #endif
339 #ifdef SIGPOLL
340     SIGNAL(SIGPOLL, bad_signal);
341 #endif
342 #ifdef SIGPROF
343     SIGNAL(SIGPROF, bad_signal);
344 #endif
345 #ifdef SIGSYS
346     SIGNAL(SIGSYS, bad_signal);
347 #endif
348 #ifdef SIGTRAP
349     SIGNAL(SIGTRAP, bad_signal);
350 #endif
351 #ifdef SIGVTALRM
352     SIGNAL(SIGVTALRM, bad_signal);
353 #endif
354 #ifdef SIGXCPU
355     SIGNAL(SIGXCPU, bad_signal);
356 #endif
357 #ifdef SIGXFSZ
358     SIGNAL(SIGXFSZ, bad_signal);
359 #endif
360
361     /*
362      * Apparently we can get a SIGPIPE when we call syslog, if
363      * syslogd has died and been restarted.  Ignoring it seems
364      * be sufficient.
365      */
366     signal(SIGPIPE, SIG_IGN);
367
368     /*
369      * If we're doing dial-on-demand, set up the interface now.
370      */
371     if (demand) {
372         /*
373          * Open the loopback channel and set it up to be the ppp interface.
374          */
375         open_ppp_loopback();
376
377         syslog(LOG_INFO, "Using interface ppp%d", ifunit);
378         (void) sprintf(ifname, "ppp%d", ifunit);
379         script_setenv("IFNAME", ifname);
380
381         create_pidfile();       /* write pid to file */
382
383         /*
384          * Configure the interface and mark it up, etc.
385          */
386         demand_conf();
387     }
388
389     for (;;) {
390
391         need_holdoff = 1;
392
393         if (demand) {
394             /*
395              * Don't do anything until we see some activity.
396              */
397             phase = PHASE_DORMANT;
398             kill_link = 0;
399             demand_unblock();
400             for (;;) {
401                 wait_loop_output(timeleft(&timo));
402                 calltimeout();
403                 if (kill_link) {
404                     if (!persist)
405                         die(0);
406                     kill_link = 0;
407                 }
408                 if (get_loop_output())
409                     break;
410                 reap_kids();
411             }
412
413             /*
414              * Now we want to bring up the link.
415              */
416             demand_block();
417             syslog(LOG_INFO, "Starting link");
418         }
419
420         /*
421          * Lock the device if we've been asked to.
422          */
423         if (lockflag && !default_device) {
424             if (lock(devnam) < 0)
425                 goto fail;
426             locked = 1;
427         }
428
429         /*
430          * Open the serial device and set it up to be the ppp interface.
431          * First we open it in non-blocking mode so we can set the
432          * various termios flags appropriately.  If we aren't dialling
433          * out and we want to use the modem lines, we reopen it later
434          * in order to wait for the carrier detect signal from the modem.
435          */
436         while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
437             if (errno != EINTR)
438                 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
439             if (!persist || errno != EINTR)
440                 goto fail;
441         }
442         if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
443             || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
444             syslog(LOG_WARNING,
445                    "Couldn't reset non-blocking mode on device: %m");
446
447         hungup = 0;
448         kill_link = 0;
449
450         /*
451          * Do the equivalent of `mesg n' to stop broadcast messages.
452          */
453         if (fstat(ttyfd, &statbuf) < 0
454             || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
455             syslog(LOG_WARNING,
456                    "Couldn't restrict write permissions to %s: %m", devnam);
457         } else
458             tty_mode = statbuf.st_mode;
459
460         /* run connection script */
461         if (connector && connector[0]) {
462             MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
463
464             /*
465              * Set line speed, flow control, etc.
466              * On most systems we set CLOCAL for now so that we can talk
467              * to the modem before carrier comes up.  But this has the
468              * side effect that we might miss it if CD drops before we
469              * get to clear CLOCAL below.  On systems where we can talk
470              * successfully to the modem with CLOCAL clear and CD down,
471              * we can clear CLOCAL at this point.
472              */
473             set_up_tty(ttyfd, 1);
474
475             /* drop dtr to hang up in case modem is off hook */
476             if (!default_device && modem) {
477                 setdtr(ttyfd, FALSE);
478                 sleep(1);
479                 setdtr(ttyfd, TRUE);
480             }
481
482             if (device_script(connector, ttyfd, ttyfd) < 0) {
483                 syslog(LOG_ERR, "Connect script failed");
484                 setdtr(ttyfd, FALSE);
485                 connect_attempts++;
486                 goto fail;
487             }
488
489
490             syslog(LOG_INFO, "Serial connection established.");
491             sleep(1);           /* give it time to set up its terminal */
492         }
493
494         connect_attempts = 0;   /* we made it through ok */
495
496         /* set line speed, flow control, etc.; clear CLOCAL if modem option */
497         set_up_tty(ttyfd, 0);
498
499         /* reopen tty if necessary to wait for carrier */
500         if (connector == NULL && modem) {
501             while ((i = open(devnam, O_RDWR)) < 0) {
502                 if (errno != EINTR)
503                     syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
504                 if (!persist || errno != EINTR ||
505                         hungup || kill_link)
506                     goto fail;
507             }
508             close(i);
509         }
510
511         /* run welcome script, if any */
512         if (welcomer && welcomer[0]) {
513             if (device_script(welcomer, ttyfd, ttyfd) < 0)
514                 syslog(LOG_WARNING, "Welcome script failed");
515         }
516
517         /* set up the serial device as a ppp interface */
518         establish_ppp(ttyfd);
519
520         if (!demand) {
521             
522             syslog(LOG_INFO, "Using interface ppp%d", ifunit);
523             (void) sprintf(ifname, "ppp%d", ifunit);
524             
525             create_pidfile();   /* write pid to file */
526
527             /* write interface unit number to file */
528             for (n = strlen(devnam); n > 0 ; n--)
529                     if (devnam[n] == '/') { 
530                             n++;
531                             break;
532                     }
533             (void) sprintf(iffilename, "%s%s.if", _PATH_VARRUN, &devnam[n]);
534             if ((iffile = fopen(iffilename, "w")) != NULL) {
535                 fprintf(iffile, "ppp%d\n", ifunit);
536                 (void) fclose(iffile);
537             } else {
538                 syslog(LOG_ERR, "Failed to create if file %s: %m", iffilename);
539                 iffilename[0] = 0;
540             }
541
542             script_setenv("IFNAME", ifname);
543         }
544
545         /*
546          * Start opening the connection and wait for
547          * incoming events (reply, timeout, etc.).
548          */
549         syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
550         stime = time((time_t *) NULL);
551         lcp_lowerup(0);
552         lcp_open(0);            /* Start protocol */
553         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
554             wait_input(timeleft(&timo));
555             calltimeout();
556             get_input();
557             if (kill_link) {
558                 lcp_close(0, "User request");
559                 kill_link = 0;
560             }
561             if (open_ccp_flag) {
562                 if (phase == PHASE_NETWORK) {
563                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
564                     (*ccp_protent.open)(0);
565                 }
566                 open_ccp_flag = 0;
567             }
568             reap_kids();        /* Don't leave dead kids lying around */
569         }
570
571         /*
572          * If we may want to bring the link up again, transfer
573          * the ppp unit back to the loopback.  Set the
574          * real serial device back to its normal mode of operation.
575          */
576         clean_check();
577         if (demand)
578             restore_loop();
579         disestablish_ppp(ttyfd);
580
581         /*
582          * Run disconnector script, if requested.
583          * XXX we may not be able to do this if the line has hung up!
584          */
585         if (disconnector && !hungup) {
586             set_up_tty(ttyfd, 1);
587             if (device_script(disconnector, ttyfd, ttyfd) < 0) {
588                 syslog(LOG_WARNING, "disconnect script failed");
589             } else {
590                 syslog(LOG_INFO, "Serial link disconnected.");
591             }
592         }
593
594     fail:
595         if (ttyfd >= 0)
596             close_tty();
597         if (locked) {
598             unlock();
599             locked = 0;
600         }
601
602         if (!demand) {
603             if (pidfilename[0] != 0
604                 && unlink(pidfilename) < 0 && errno != ENOENT) 
605                 syslog(LOG_WARNING, "unable to delete pid file: %m");
606             pidfilename[0] = 0;
607
608             if (iffile)
609                     if (unlink(iffilename) < 0 && errno != ENOENT) 
610                             syslog(LOG_WARNING, "unable to delete if file: %m");
611             iffilename[0] = 0;
612         }
613
614         /* limit to retries? */
615         if (max_con_attempts)
616             if (connect_attempts >= max_con_attempts)
617                 break;
618
619         if (!persist)
620             die(1);
621
622         if (demand)
623             demand_discard();
624         if (holdoff > 0 && need_holdoff) {
625             phase = PHASE_HOLDOFF;
626             TIMEOUT(holdoff_end, NULL, holdoff);
627             do {
628                 wait_time(timeleft(&timo));
629                 calltimeout();
630                 if (kill_link) {
631                     if (!persist)
632                         die(0);
633                     kill_link = 0;
634                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
635                 }
636                 reap_kids();
637             } while (phase == PHASE_HOLDOFF);
638         }
639     }
640
641     die(0);
642     return 0;
643 }
644
645 /*
646  * detach - detach us from the controlling terminal.
647  */
648 void
649 detach()
650 {
651     if (detached)
652         return;
653     if (daemon(0, 0) < 0) {
654         perror("Couldn't detach from controlling terminal");
655         die(1);
656     }
657     detached = 1;
658     pid = getpid();
659     /* update pid file if it has been written already */
660     if (pidfilename[0])
661         create_pidfile();
662 }
663
664 /*
665  * Create a file containing our process ID.
666  */
667 static void
668 create_pidfile()
669 {
670     FILE *pidfile;
671
672     (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
673     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
674         fprintf(pidfile, "%d\n", pid);
675         (void) fclose(pidfile);
676     } else {
677         syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
678         pidfilename[0] = 0;
679     }
680 }
681
682 /*
683  * holdoff_end - called via a timeout when the holdoff period ends.
684  */
685 static void
686 holdoff_end(arg)
687     void *arg;
688 {
689     phase = PHASE_DORMANT;
690 }
691
692 /*
693  * get_input - called when incoming data is available.
694  */
695 static void
696 get_input()
697 {
698     int len, i;
699     u_char *p;
700     u_short protocol;
701     struct protent *protp;
702
703     p = inpacket_buf;   /* point to beginning of packet buffer */
704
705     len = read_packet(inpacket_buf);
706     if (len < 0)
707         return;
708
709     if (len == 0) {
710         etime = time((time_t *) NULL);
711         minutes = (etime-stime)/60;
712         syslog(LOG_NOTICE, "Modem hangup, connected for %d minutes", (minutes >1) ? minutes : 1);
713         hungup = 1;
714         lcp_lowerdown(0);       /* serial link is no longer available */
715         link_terminated(0);
716         return;
717     }
718
719     if (debug /*&& (debugflags & DBG_INPACKET)*/)
720         log_packet(p, len, "rcvd ", LOG_DEBUG);
721
722     if (len < PPP_HDRLEN) {
723         MAINDEBUG((LOG_INFO, "io(): Received short packet."));
724         return;
725     }
726
727     p += 2;                             /* Skip address and control */
728     GETSHORT(protocol, p);
729     len -= PPP_HDRLEN;
730
731     /*
732      * Toss all non-LCP packets unless LCP is OPEN.
733      */
734     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
735         MAINDEBUG((LOG_INFO,
736                    "get_input: Received non-LCP packet when LCP not open."));
737         return;
738     }
739
740     /*
741      * Until we get past the authentication phase, toss all packets
742      * except LCP, LQR and authentication packets.
743      */
744     if (phase <= PHASE_AUTHENTICATE
745         && !(protocol == PPP_LCP || protocol == PPP_LQR
746              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
747         MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
748                    protocol, phase));
749         return;
750     }
751
752     /*
753      * Upcall the proper protocol input routine.
754      */
755     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
756         if (protp->protocol == protocol && protp->enabled_flag) {
757             (*protp->input)(0, p, len);
758             return;
759         }
760         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
761             && protp->datainput != NULL) {
762             (*protp->datainput)(0, p, len);
763             return;
764         }
765     }
766
767     if (debug)
768         syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
769     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
770 }
771
772
773 /*
774  * quit - Clean up state and exit (with an error indication).
775  */
776 void 
777 quit()
778 {
779     die(1);
780 }
781
782 /*
783  * die - like quit, except we can specify an exit status.
784  */
785 void
786 die(status)
787     int status;
788 {
789     cleanup();
790     syslog(LOG_INFO, "Exit.");
791     exit(status);
792 }
793
794 /*
795  * cleanup - restore anything which needs to be restored before we exit
796  */
797 /* ARGSUSED */
798 static void
799 cleanup()
800 {
801     sys_cleanup();
802
803     if (ttyfd >= 0)
804         close_tty();
805
806     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
807         syslog(LOG_WARNING, "unable to delete pid file: %m");
808     pidfilename[0] = 0;
809
810     if (locked)
811         unlock();
812 }
813
814 /*
815  * close_tty - restore the terminal device and close it.
816  */
817 static void
818 close_tty()
819 {
820     disestablish_ppp(ttyfd);
821
822     /* drop dtr to hang up */
823     if (modem) {
824         setdtr(ttyfd, FALSE);
825         /*
826          * This sleep is in case the serial port has CLOCAL set by default,
827          * and consequently will reassert DTR when we close the device.
828          */
829         sleep(1);
830     }
831
832     restore_tty(ttyfd);
833
834     if (tty_mode != (mode_t) -1)
835         fchmod(ttyfd, tty_mode);
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_sec))
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 }
1005
1006
1007 /*
1008  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1009  *
1010  * Indicates that we should initiate a graceful disconnect and exit.
1011  */
1012 /*ARGSUSED*/
1013 static void
1014 term(sig)
1015     int sig;
1016 {
1017     syslog(LOG_INFO, "Terminating on signal %d.", sig);
1018     persist = 0;                /* don't try to restart */
1019     kill_link = 1;
1020     if (conn_running)
1021         /* Send the signal to the [dis]connector process(es) also */
1022         kill_my_pg(sig);
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     reap_kids();
1035 }
1036
1037
1038 /*
1039  * toggle_debug - Catch SIGUSR1 signal.
1040  *
1041  * Toggle debug flag.
1042  */
1043 /*ARGSUSED*/
1044 static void
1045 toggle_debug(sig)
1046     int sig;
1047 {
1048     debug = !debug;
1049     if (debug) {
1050         setlogmask(LOG_UPTO(LOG_DEBUG));
1051     } else {
1052         setlogmask(LOG_UPTO(LOG_WARNING));
1053     }
1054 }
1055
1056
1057 /*
1058  * open_ccp - Catch SIGUSR2 signal.
1059  *
1060  * Try to (re)negotiate compression.
1061  */
1062 /*ARGSUSED*/
1063 static void
1064 open_ccp(sig)
1065     int sig;
1066 {
1067     open_ccp_flag = 1;
1068 }
1069
1070
1071 /*
1072  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1073  */
1074 static void
1075 bad_signal(sig)
1076     int sig;
1077 {
1078     static int crashed = 0;
1079
1080     if (crashed)
1081         _exit(127);
1082     crashed = 1;
1083     syslog(LOG_ERR, "Fatal signal %d", sig);
1084     if (conn_running)
1085         kill_my_pg(SIGTERM);
1086     die(1);
1087 }
1088
1089
1090 /*
1091  * device_script - run a program to connect or disconnect the
1092  * serial device.
1093  */
1094 static int
1095 device_script(program, in, out)
1096     char *program;
1097     int in, out;
1098 {
1099     int pid;
1100     int status;
1101     int errfd;
1102
1103     conn_running = 1;
1104     pid = fork();
1105
1106     if (pid < 0) {
1107         conn_running = 0;
1108         syslog(LOG_ERR, "Failed to create child process: %m");
1109         die(1);
1110     }
1111
1112     if (pid == 0) {
1113         sys_close();
1114         closelog();
1115         if (in == out) {
1116             if (in != 0) {
1117                 dup2(in, 0);
1118                 close(in);
1119             }
1120             dup2(0, 1);
1121         } else {
1122             if (out == 0)
1123                 out = dup(out);
1124             if (in != 0) {
1125                 dup2(in, 0);
1126                 close(in);
1127             }
1128             if (out != 1) {
1129                 dup2(out, 1);
1130                 close(out);
1131             }
1132         }
1133         if (nodetach == 0) {
1134             close(2);
1135             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1136             if (errfd >= 0 && errfd != 2) {
1137                 dup2(errfd, 2);
1138                 close(errfd);
1139             }
1140         }
1141         setuid(getuid());
1142         setgid(getgid());
1143         execl("/bin/sh", "sh", "-c", program, (char *)0);
1144         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1145         _exit(99);
1146         /* NOTREACHED */
1147     }
1148
1149     while (waitpid(pid, &status, 0) < 0) {
1150         if (errno == EINTR)
1151             continue;
1152         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1153         die(1);
1154     }
1155     conn_running = 0;
1156
1157     return (status == 0 ? 0 : -1);
1158 }
1159
1160
1161 /*
1162  * run-program - execute a program with given arguments,
1163  * but don't wait for it.
1164  * If the program can't be executed, logs an error unless
1165  * must_exist is 0 and the program file doesn't exist.
1166  */
1167 int
1168 run_program(prog, args, must_exist)
1169     char *prog;
1170     char **args;
1171     int must_exist;
1172 {
1173     int pid;
1174
1175     pid = fork();
1176     if (pid == -1) {
1177         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1178         return -1;
1179     }
1180     if (pid == 0) {
1181         int new_fd;
1182
1183         /* Leave the current location */
1184         (void) setsid();    /* No controlling tty. */
1185         (void) umask (S_IRWXG|S_IRWXO);
1186         (void) chdir ("/"); /* no current directory. */
1187         setuid(geteuid());
1188         setgid(getegid());
1189
1190         /* Ensure that nothing of our device environment is inherited. */
1191         sys_close();
1192         closelog();
1193         close (0);
1194         close (1);
1195         close (2);
1196         close (ttyfd);  /* tty interface to the ppp device */
1197
1198         /* Don't pass handles to the PPP device, even by accident. */
1199         new_fd = open (_PATH_DEVNULL, O_RDWR);
1200         if (new_fd >= 0) {
1201             if (new_fd != 0) {
1202                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1203                 close (new_fd);
1204             }
1205             dup2 (0, 1); /* stdout -> /dev/null */
1206             dup2 (0, 2); /* stderr -> /dev/null */
1207         }
1208
1209 #ifdef BSD
1210         /* Force the priority back to zero if pppd is running higher. */
1211         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1212             syslog (LOG_WARNING, "can't reset priority to 0: %m"); 
1213 #endif
1214
1215         /* SysV recommends a second fork at this point. */
1216
1217         /* run the program; give it a null environment */
1218         execve(prog, args, script_env);
1219         if (must_exist || errno != ENOENT)
1220             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1221         _exit(-1);
1222     }
1223     MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1224     ++n_children;
1225     return 0;
1226 }
1227
1228
1229 /*
1230  * reap_kids - get status from any dead child processes,
1231  * and log a message for abnormal terminations.
1232  */
1233 static void
1234 reap_kids()
1235 {
1236     int pid, status;
1237
1238     if (n_children == 0)
1239         return;
1240     if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1241         if (errno != ECHILD)
1242             syslog(LOG_ERR, "Error waiting for child process: %m");
1243         return;
1244     }
1245     if (pid > 0) {
1246         --n_children;
1247         if (WIFSIGNALED(status)) {
1248             syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1249                    pid, WTERMSIG(status));
1250         }
1251     }
1252 }
1253
1254
1255 /*
1256  * log_packet - format a packet and log it.
1257  */
1258
1259 char line[256];                 /* line to be logged accumulated here */
1260 char *linep;
1261
1262 void
1263 log_packet(p, len, prefix, level)
1264     u_char *p;
1265     int len;
1266     char *prefix;
1267     int level;
1268 {
1269     strcpy(line, prefix);
1270     linep = line + strlen(line);
1271     format_packet(p, len, pr_log, NULL);
1272     if (linep != line)
1273         syslog(level, "%s", line);
1274 }
1275
1276 /*
1277  * format_packet - make a readable representation of a packet,
1278  * calling `printer(arg, format, ...)' to output it.
1279  */
1280 void
1281 format_packet(p, len, printer, arg)
1282     u_char *p;
1283     int len;
1284     void (*printer) __P((void *, char *, ...));
1285     void *arg;
1286 {
1287     int i, n;
1288     u_short proto;
1289     u_char x;
1290     struct protent *protp;
1291
1292     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1293         p += 2;
1294         GETSHORT(proto, p);
1295         len -= PPP_HDRLEN;
1296         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1297             if (proto == protp->protocol)
1298                 break;
1299         if (protp != NULL) {
1300             printer(arg, "[%s", protp->name);
1301             n = (*protp->printpkt)(p, len, printer, arg);
1302             printer(arg, "]");
1303             p += n;
1304             len -= n;
1305         } else {
1306             printer(arg, "[proto=0x%x]", proto);
1307         }
1308     }
1309
1310     for (; len > 0; --len) {
1311         GETCHAR(x, p);
1312         printer(arg, " %.2x", x);
1313     }
1314 }
1315
1316 static void
1317 pr_log __V((void *arg, char *fmt, ...))
1318 {
1319     int n;
1320     va_list pvar;
1321     char buf[256];
1322
1323 #if __STDC__
1324     va_start(pvar, fmt);
1325 #else
1326     void *arg;
1327     char *fmt;
1328     va_start(pvar);
1329     arg = va_arg(pvar, void *);
1330     fmt = va_arg(pvar, char *);
1331 #endif
1332
1333     n = vfmtmsg(buf, sizeof(buf), fmt, pvar);
1334     va_end(pvar);
1335
1336     if (linep + n + 1 > line + sizeof(line)) {
1337         syslog(LOG_DEBUG, "%s", line);
1338         linep = line;
1339     }
1340     strcpy(linep, buf);
1341     linep += n;
1342 }
1343
1344 /*
1345  * print_string - print a readable representation of a string using
1346  * printer.
1347  */
1348 void
1349 print_string(p, len, printer, arg)
1350     char *p;
1351     int len;
1352     void (*printer) __P((void *, char *, ...));
1353     void *arg;
1354 {
1355     int c;
1356
1357     printer(arg, "\"");
1358     for (; len > 0; --len) {
1359         c = *p++;
1360         if (' ' <= c && c <= '~') {
1361             if (c == '\\' || c == '"')
1362                 printer(arg, "\\");
1363             printer(arg, "%c", c);
1364         } else {
1365             switch (c) {
1366             case '\n':
1367                 printer(arg, "\\n");
1368                 break;
1369             case '\r':
1370                 printer(arg, "\\r");
1371                 break;
1372             case '\t':
1373                 printer(arg, "\\t");
1374                 break;
1375             default:
1376                 printer(arg, "\\%.3o", c);
1377             }
1378         }
1379     }
1380     printer(arg, "\"");
1381 }
1382
1383 /*
1384  * novm - log an error message saying we ran out of memory, and die.
1385  */
1386 void
1387 novm(msg)
1388     char *msg;
1389 {
1390     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1391     die(1);
1392 }
1393
1394 /*
1395  * fmtmsg - format a message into a buffer.  Like sprintf except we
1396  * also specify the length of the output buffer, and we handle
1397  * %r (recursive format), %m (error message) and %I (IP address) formats.
1398  * Doesn't do floating-point formats.
1399  * Returns the number of chars put into buf.
1400  */
1401 int
1402 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1403 {
1404     va_list args;
1405     int n;
1406
1407 #if __STDC__
1408     va_start(args, fmt);
1409 #else
1410     char *buf;
1411     int buflen;
1412     char *fmt;
1413     va_start(args);
1414     buf = va_arg(args, char *);
1415     buflen = va_arg(args, int);
1416     fmt = va_arg(args, char *);
1417 #endif
1418     n = vfmtmsg(buf, buflen, fmt, args);
1419     va_end(args);
1420     return n;
1421 }
1422
1423 /*
1424  * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1425  */
1426 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1427
1428 int
1429 vfmtmsg(buf, buflen, fmt, args)
1430     char *buf;
1431     int buflen;
1432     char *fmt;
1433     va_list args;
1434 {
1435     int c, i, n;
1436     int width, prec, fillch;
1437     int base, len, neg, quoted;
1438     unsigned long val = 0;
1439     char *str, *f, *buf0;
1440     unsigned char *p;
1441     char num[32];
1442     time_t t;
1443     static char hexchars[] = "0123456789abcdef";
1444
1445     buf0 = buf;
1446     --buflen;
1447     while (buflen > 0) {
1448         for (f = fmt; *f != '%' && *f != 0; ++f)
1449             ;
1450         if (f > fmt) {
1451             len = f - fmt;
1452             if (len > buflen)
1453                 len = buflen;
1454             memcpy(buf, fmt, len);
1455             buf += len;
1456             buflen -= len;
1457             fmt = f;
1458         }
1459         if (*fmt == 0)
1460             break;
1461         c = *++fmt;
1462         width = prec = 0;
1463         fillch = ' ';
1464         if (c == '0') {
1465             fillch = '0';
1466             c = *++fmt;
1467         }
1468         if (c == '*') {
1469             width = va_arg(args, int);
1470             c = *++fmt;
1471         } else {
1472             while (isdigit(c)) {
1473                 width = width * 10 + c - '0';
1474                 c = *++fmt;
1475             }
1476         }
1477         if (c == '.') {
1478             c = *++fmt;
1479             if (c == '*') {
1480                 prec = va_arg(args, int);
1481                 c = *++fmt;
1482             } else {
1483                 while (isdigit(c)) {
1484                     prec = prec * 10 + c - '0';
1485                     c = *++fmt;
1486                 }
1487             }
1488         }
1489         str = 0;
1490         base = 0;
1491         neg = 0;
1492         ++fmt;
1493         switch (c) {
1494         case 'd':
1495             i = va_arg(args, int);
1496             if (i < 0) {
1497                 neg = 1;
1498                 val = -i;
1499             } else
1500                 val = i;
1501             base = 10;
1502             break;
1503         case 'o':
1504             val = va_arg(args, unsigned int);
1505             base = 8;
1506             break;
1507         case 'x':
1508             val = va_arg(args, unsigned int);
1509             base = 16;
1510             break;
1511         case 'p':
1512             val = (unsigned long) va_arg(args, void *);
1513             base = 16;
1514             neg = 2;
1515             break;
1516         case 's':
1517             str = va_arg(args, char *);
1518             break;
1519         case 'c':
1520             num[0] = va_arg(args, int);
1521             num[1] = 0;
1522             str = num;
1523             break;
1524         case 'm':
1525             str = strerror(errno);
1526             break;
1527         case 'I':
1528             str = ip_ntoa(va_arg(args, u_int32_t));
1529             break;
1530         case 'r':
1531             f = va_arg(args, char *);
1532 #ifndef __powerpc__
1533             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1534 #else
1535             /* On the powerpc, a va_list is an array of 1 structure */
1536             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1537 #endif
1538             buf += n;
1539             buflen -= n;
1540             continue;
1541         case 't':
1542             time(&t);
1543             str = ctime(&t);
1544             str += 4;           /* chop off the day name */
1545             str[15] = 0;        /* chop off year and newline */
1546             break;
1547         case 'v':               /* "visible" string */
1548         case 'q':               /* quoted string */
1549             quoted = c == 'q';
1550             p = va_arg(args, unsigned char *);
1551             if (fillch == '0' && prec > 0) {
1552                 n = prec;
1553             } else {
1554                 n = strlen((char *)p);
1555                 if (prec > 0 && prec < n)
1556                     n = prec;
1557             }
1558             while (n > 0 && buflen > 0) {
1559                 c = *p++;
1560                 --n;
1561                 if (!quoted && c >= 0x80) {
1562                     OUTCHAR('M');
1563                     OUTCHAR('-');
1564                     c -= 0x80;
1565                 }
1566                 if (quoted && (c == '"' || c == '\\'))
1567                     OUTCHAR('\\');
1568                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1569                     if (quoted) {
1570                         OUTCHAR('\\');
1571                         switch (c) {
1572                         case '\t':      OUTCHAR('t');   break;
1573                         case '\n':      OUTCHAR('n');   break;
1574                         case '\b':      OUTCHAR('b');   break;
1575                         case '\f':      OUTCHAR('f');   break;
1576                         default:
1577                             OUTCHAR('x');
1578                             OUTCHAR(hexchars[c >> 4]);
1579                             OUTCHAR(hexchars[c & 0xf]);
1580                         }
1581                     } else {
1582                         if (c == '\t')
1583                             OUTCHAR(c);
1584                         else {
1585                             OUTCHAR('^');
1586                             OUTCHAR(c ^ 0x40);
1587                         }
1588                     }
1589                 } else
1590                     OUTCHAR(c);
1591             }
1592             continue;
1593         default:
1594             *buf++ = '%';
1595             if (c != '%')
1596                 --fmt;          /* so %z outputs %z etc. */
1597             --buflen;
1598             continue;
1599         }
1600         if (base != 0) {
1601             str = num + sizeof(num);
1602             *--str = 0;
1603             while (str > num + neg) {
1604                 *--str = hexchars[val % base];
1605                 val = val / base;
1606                 if (--prec <= 0 && val == 0)
1607                     break;
1608             }
1609             switch (neg) {
1610             case 1:
1611                 *--str = '-';
1612                 break;
1613             case 2:
1614                 *--str = 'x';
1615                 *--str = '0';
1616                 break;
1617             }
1618             len = num + sizeof(num) - 1 - str;
1619         } else {
1620             len = strlen(str);
1621             if (prec > 0 && len > prec)
1622                 len = prec;
1623         }
1624         if (width > 0) {
1625             if (width > buflen)
1626                 width = buflen;
1627             if ((n = width - len) > 0) {
1628                 buflen -= n;
1629                 for (; n > 0; --n)
1630                     *buf++ = fillch;
1631             }
1632         }
1633         if (len > buflen)
1634             len = buflen;
1635         memcpy(buf, str, len);
1636         buf += len;
1637         buflen -= len;
1638     }
1639     *buf = 0;
1640     return buf - buf0;
1641 }
1642
1643 /*
1644  * script_setenv - set an environment variable value to be used
1645  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1646  */
1647 void
1648 script_setenv(var, value)
1649     char *var, *value;
1650 {
1651     int vl = strlen(var);
1652     int i;
1653     char *p, *newstring;
1654
1655     newstring = (char *) malloc(vl + strlen(value) + 2);
1656     if (newstring == 0)
1657         return;
1658     strcpy(newstring, var);
1659     newstring[vl] = '=';
1660     strcpy(newstring+vl+1, value);
1661
1662     /* check if this variable is already set */
1663     if (script_env != 0) {
1664         for (i = 0; (p = script_env[i]) != 0; ++i) {
1665             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1666                 free(p);
1667                 script_env[i] = newstring;
1668                 return;
1669             }
1670         }
1671     } else {
1672         i = 0;
1673         script_env = (char **) malloc(16 * sizeof(char *));
1674         if (script_env == 0)
1675             return;
1676         s_env_nalloc = 16;
1677     }
1678
1679     /* reallocate script_env with more space if needed */
1680     if (i + 1 >= s_env_nalloc) {
1681         int new_n = i + 17;
1682         char **newenv = (char **) realloc((void *)script_env,
1683                                           new_n * sizeof(char *));
1684         if (newenv == 0)
1685             return;
1686         script_env = newenv;
1687         s_env_nalloc = new_n;
1688     }
1689
1690     script_env[i] = newstring;
1691     script_env[i+1] = 0;
1692 }
1693
1694 /*
1695  * script_unsetenv - remove a variable from the environment
1696  * for scripts.
1697  */
1698 void
1699 script_unsetenv(var)
1700     char *var;
1701 {
1702     int vl = strlen(var);
1703     int i;
1704     char *p;
1705
1706     if (script_env == 0)
1707         return;
1708     for (i = 0; (p = script_env[i]) != 0; ++i) {
1709         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1710             free(p);
1711             while ((script_env[i] = script_env[i+1]) != 0)
1712                 ++i;
1713             break;
1714         }
1715     }
1716 }