Initial import from FreeBSD RELENG_4:
[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
20 #ifndef lint
21 static char rcsid[] = "$FreeBSD: src/usr.sbin/pppd/main.c,v 1.19.2.1 2002/07/30 03:50:40 peter 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 <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <sys/time.h>
40 #include <sys/resource.h>
41 #include <sys/stat.h>
42 #include <sys/socket.h>
43
44 #include "pppd.h"
45 #include "magic.h"
46 #include "fsm.h"
47 #include "lcp.h"
48 #include "ipcp.h"
49 #include "upap.h"
50 #include "chap.h"
51 #include "ccp.h"
52 #include "pathnames.h"
53 #include "patchlevel.h"
54
55 #ifdef CBCP_SUPPORT
56 #include "cbcp.h"
57 #endif
58
59 #if defined(SUNOS4)
60 extern char *strerror();
61 #endif
62
63 #ifdef IPX_CHANGE
64 #include "ipxcp.h"
65 #endif /* IPX_CHANGE */
66 #ifdef AT_CHANGE
67 #include "atcp.h"
68 #endif
69
70 /* interface vars */
71 char ifname[32];                /* Interface name */
72 int ifunit;                     /* Interface unit number */
73
74 char *progname;                 /* Name of this program */
75 char hostname[MAXNAMELEN];      /* Our hostname */
76 static char pidfilename[MAXPATHLEN];    /* name of pid file */
77 static char iffilename[MAXPATHLEN];     /* name of if 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 time_t          etime,stime;    /* End and Start time */
82 int             minutes;        /* connection duration */
83 static int conn_running;        /* we have a [dis]connector running */
84
85 int ttyfd = -1;                 /* Serial port file descriptor */
86 mode_t tty_mode = -1;           /* Original access permissions to tty */
87 int baud_rate;                  /* Actual bits/second for serial device */
88 int hungup;                     /* terminal has been hung up */
89 int privileged;                 /* we're running as real uid root */
90 int need_holdoff;               /* need holdoff period before restarting */
91 int detached;                   /* have detached from terminal */
92
93 int phase;                      /* where the link is at */
94 int kill_link;
95 int open_ccp_flag;
96
97 char **script_env;              /* Env. variable values for scripts */
98 int s_env_nalloc;               /* # words avail at script_env */
99
100 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
101 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
102
103 static int n_children;          /* # child processes still running */
104
105 static int locked;              /* lock() has succeeded */
106
107 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
108
109 /* Prototypes for procedures local to this file. */
110
111 static void create_pidfile __P((void));
112 static void cleanup __P((void));
113 static void close_tty __P((void));
114 static void get_input __P((void));
115 static void calltimeout __P((void));
116 static struct timeval *timeleft __P((struct timeval *));
117 static void kill_my_pg __P((int));
118 static void hup __P((int));
119 static void term __P((int));
120 static void chld __P((int));
121 static void toggle_debug __P((int));
122 static void open_ccp __P((int));
123 static void bad_signal __P((int));
124 static void holdoff_end __P((void *));
125 static int device_script __P((char *, int, int));
126 static void reap_kids __P((void));
127 static void pr_log __P((void *, char *, ...));
128
129 extern  char    *ttyname __P((int));
130 extern  char    *getlogin __P((void));
131 int main __P((int, char *[]));
132
133 #ifdef ultrix
134 #undef  O_NONBLOCK
135 #define O_NONBLOCK      O_NDELAY
136 #endif
137
138 #ifdef ULTRIX
139 #define setlogmask(x)
140 #endif
141
142 /*
143  * PPP Data Link Layer "protocol" table.
144  * One entry per supported protocol.
145  * The last entry must be NULL.
146  */
147 struct protent *protocols[] = {
148     &lcp_protent,
149     &pap_protent,
150     &chap_protent,
151 #ifdef CBCP_SUPPORT
152     &cbcp_protent,
153 #endif
154     &ipcp_protent,
155     &ccp_protent,
156 #ifdef IPX_CHANGE
157     &ipxcp_protent,
158 #endif
159 #ifdef AT_CHANGE
160     &atcp_protent,
161 #endif
162     NULL
163 };
164
165 int
166 main(argc, argv)
167     int argc;
168     char *argv[];
169 {
170     int i, n, fdflags;
171     struct sigaction sa;
172     FILE *iffile;
173     char *p;
174     struct passwd *pw;
175     struct timeval timo;
176     sigset_t mask;
177     struct protent *protp;
178     struct stat statbuf;
179     int connect_attempts = 0;
180     char numbuf[16];
181
182     phase = PHASE_INITIALIZE;
183     p = ttyname(0);
184     if (p)
185         strcpy(devnam, p);
186     strcpy(default_devnam, devnam);
187
188     script_env = NULL;
189
190     /* Initialize syslog facilities */
191 #ifdef ULTRIX
192     openlog("pppd", LOG_PID);
193 #else
194     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
195     setlogmask(LOG_UPTO(LOG_INFO));
196 #endif
197
198     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
199         option_error("Couldn't get hostname: %m");
200         die(1);
201     }
202     hostname[MAXNAMELEN-1] = 0;
203
204     uid = getuid();
205     privileged = uid == 0;
206     sprintf(numbuf, "%d", uid);
207     script_setenv("UID", numbuf);
208
209     /*
210      * Initialize to the standard option set, then parse, in order,
211      * the system options file, the user's options file,
212      * the tty's options file, and the command line arguments.
213      */
214     for (i = 0; (protp = protocols[i]) != NULL; ++i)
215         (*protp->init)(0);
216
217     progname = *argv;
218
219     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
220         || !options_from_user())
221         exit(1);
222     scan_args(argc-1, argv+1);  /* look for tty name on command line */
223     if (!options_for_tty()
224         || !parse_args(argc-1, argv+1))
225         exit(1);
226
227     /*
228      * Check that we are running as root.
229      */
230     if (geteuid() != 0) {
231         option_error("must be root to run %s, since it is not setuid-root",
232                      argv[0]);
233         die(1);
234     }
235
236     if (!ppp_available()) {
237         option_error(no_ppp_msg);
238         exit(1);
239     }
240
241     /*
242      * Check that the options given are valid and consistent.
243      */
244     sys_check_options();
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 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 == 0)
280         detach();
281     pid = getpid();
282     p = getlogin();
283     stime = time((time_t *) NULL);
284     if (p == NULL) {
285         pw = getpwuid(uid);
286         if (pw != NULL && pw->pw_name != NULL)
287             p = pw->pw_name;
288         else
289             p = "(unknown)";
290     }
291     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
292            VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
293   
294     /*
295      * Compute mask of all interesting signals and install signal handlers
296      * for each.  Only one signal handler may be active at a time.  Therefore,
297      * all other signals should be masked when any handler is executing.
298      */
299     sigemptyset(&mask);
300     sigaddset(&mask, SIGHUP);
301     sigaddset(&mask, SIGINT);
302     sigaddset(&mask, SIGTERM);
303     sigaddset(&mask, SIGCHLD);
304
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             die(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     /*
370      * If we're doing dial-on-demand, set up the interface now.
371      */
372     if (demand) {
373         /*
374          * Open the loopback channel and set it up to be the ppp interface.
375          */
376         open_ppp_loopback();
377
378         syslog(LOG_INFO, "Using interface ppp%d", ifunit);
379         (void) sprintf(ifname, "ppp%d", ifunit);
380         script_setenv("IFNAME", ifname);
381
382         create_pidfile();       /* write pid to file */
383
384         /*
385          * Configure the interface and mark it up, etc.
386          */
387         demand_conf();
388     }
389
390     for (;;) {
391
392         need_holdoff = 1;
393
394         if (demand) {
395             /*
396              * Don't do anything until we see some activity.
397              */
398             phase = PHASE_DORMANT;
399             kill_link = 0;
400             demand_unblock();
401             for (;;) {
402                 wait_loop_output(timeleft(&timo));
403                 calltimeout();
404                 if (kill_link) {
405                     if (!persist)
406                         die(0);
407                     kill_link = 0;
408                 }
409                 if (get_loop_output())
410                     break;
411                 reap_kids();
412             }
413
414             /*
415              * Now we want to bring up the link.
416              */
417             demand_block();
418             syslog(LOG_INFO, "Starting link");
419         }
420
421         /*
422          * Lock the device if we've been asked to.
423          */
424         if (lockflag && !default_device) {
425             if (lock(devnam) < 0)
426                 goto fail;
427             locked = 1;
428         }
429
430         /*
431          * Open the serial device and set it up to be the ppp interface.
432          * First we open it in non-blocking mode so we can set the
433          * various termios flags appropriately.  If we aren't dialling
434          * out and we want to use the modem lines, we reopen it later
435          * in order to wait for the carrier detect signal from the modem.
436          */
437         while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
438             if (errno != EINTR)
439                 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
440             if (!persist || errno != EINTR)
441                 goto fail;
442         }
443         if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
444             || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
445             syslog(LOG_WARNING,
446                    "Couldn't reset non-blocking mode on device: %m");
447
448         hungup = 0;
449         kill_link = 0;
450
451         /*
452          * Do the equivalent of `mesg n' to stop broadcast messages.
453          */
454         if (fstat(ttyfd, &statbuf) < 0
455             || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
456             syslog(LOG_WARNING,
457                    "Couldn't restrict write permissions to %s: %m", devnam);
458         } else
459             tty_mode = statbuf.st_mode;
460
461         /* run connection script */
462         if (connector && connector[0]) {
463             MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
464
465             /*
466              * Set line speed, flow control, etc.
467              * On most systems we set CLOCAL for now so that we can talk
468              * to the modem before carrier comes up.  But this has the
469              * side effect that we might miss it if CD drops before we
470              * get to clear CLOCAL below.  On systems where we can talk
471              * successfully to the modem with CLOCAL clear and CD down,
472              * we can clear CLOCAL at this point.
473              */
474             set_up_tty(ttyfd, 1);
475
476             /* drop dtr to hang up in case modem is off hook */
477             if (!default_device && modem) {
478                 setdtr(ttyfd, FALSE);
479                 sleep(1);
480                 setdtr(ttyfd, TRUE);
481             }
482
483             if (device_script(connector, ttyfd, ttyfd) < 0) {
484                 syslog(LOG_ERR, "Connect script failed");
485                 setdtr(ttyfd, FALSE);
486                 connect_attempts++;
487                 goto fail;
488             }
489
490
491             syslog(LOG_INFO, "Serial connection established.");
492             sleep(1);           /* give it time to set up its terminal */
493         }
494
495         connect_attempts = 0;   /* we made it through ok */
496
497         /* set line speed, flow control, etc.; clear CLOCAL if modem option */
498         set_up_tty(ttyfd, 0);
499
500         /* reopen tty if necessary to wait for carrier */
501         if (connector == NULL && modem) {
502             while ((i = open(devnam, O_RDWR)) < 0) {
503                 if (errno != EINTR)
504                     syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
505                 if (!persist || errno != EINTR ||
506                         hungup || kill_link)
507                     goto fail;
508             }
509             close(i);
510         }
511
512         /* run welcome script, if any */
513         if (welcomer && welcomer[0]) {
514             if (device_script(welcomer, ttyfd, ttyfd) < 0)
515                 syslog(LOG_WARNING, "Welcome script failed");
516         }
517
518         /* set up the serial device as a ppp interface */
519         establish_ppp(ttyfd);
520
521         if (!demand) {
522             
523             syslog(LOG_INFO, "Using interface ppp%d", ifunit);
524             (void) sprintf(ifname, "ppp%d", ifunit);
525             
526             create_pidfile();   /* write pid to file */
527
528             /* write interface unit number to file */
529             for (n = strlen(devnam); n > 0 ; n--)
530                     if (devnam[n] == '/') { 
531                             n++;
532                             break;
533                     }
534             (void) sprintf(iffilename, "%s%s.if", _PATH_VARRUN, &devnam[n]);
535             if ((iffile = fopen(iffilename, "w")) != NULL) {
536                 fprintf(iffile, "ppp%d\n", ifunit);
537                 (void) fclose(iffile);
538             } else {
539                 syslog(LOG_ERR, "Failed to create if file %s: %m", iffilename);
540                 iffilename[0] = 0;
541             }
542
543             script_setenv("IFNAME", ifname);
544         }
545
546         /*
547          * Start opening the connection and wait for
548          * incoming events (reply, timeout, etc.).
549          */
550         syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
551         stime = time((time_t *) NULL);
552         lcp_lowerup(0);
553         lcp_open(0);            /* Start protocol */
554         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
555             wait_input(timeleft(&timo));
556             calltimeout();
557             get_input();
558             if (kill_link) {
559                 lcp_close(0, "User request");
560                 kill_link = 0;
561             }
562             if (open_ccp_flag) {
563                 if (phase == PHASE_NETWORK) {
564                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
565                     (*ccp_protent.open)(0);
566                 }
567                 open_ccp_flag = 0;
568             }
569             reap_kids();        /* Don't leave dead kids lying around */
570         }
571
572         /*
573          * If we may want to bring the link up again, transfer
574          * the ppp unit back to the loopback.  Set the
575          * real serial device back to its normal mode of operation.
576          */
577         clean_check();
578         if (demand)
579             restore_loop();
580         disestablish_ppp(ttyfd);
581
582         /*
583          * Run disconnector script, if requested.
584          * XXX we may not be able to do this if the line has hung up!
585          */
586         if (disconnector && !hungup) {
587             set_up_tty(ttyfd, 1);
588             if (device_script(disconnector, ttyfd, ttyfd) < 0) {
589                 syslog(LOG_WARNING, "disconnect script failed");
590             } else {
591                 syslog(LOG_INFO, "Serial link disconnected.");
592             }
593         }
594
595     fail:
596         if (ttyfd >= 0)
597             close_tty();
598         if (locked) {
599             unlock();
600             locked = 0;
601         }
602
603         if (!demand) {
604             if (pidfilename[0] != 0
605                 && unlink(pidfilename) < 0 && errno != ENOENT) 
606                 syslog(LOG_WARNING, "unable to delete pid file: %m");
607             pidfilename[0] = 0;
608
609             if (iffile)
610                     if (unlink(iffilename) < 0 && errno != ENOENT) 
611                             syslog(LOG_WARNING, "unable to delete if file: %m");
612             iffilename[0] = 0;
613         }
614
615         /* limit to retries? */
616         if (max_con_attempts)
617             if (connect_attempts >= max_con_attempts)
618                 break;
619
620         if (!persist)
621             die(1);
622
623         if (demand)
624             demand_discard();
625         if (holdoff > 0 && need_holdoff) {
626             phase = PHASE_HOLDOFF;
627             TIMEOUT(holdoff_end, NULL, holdoff);
628             do {
629                 wait_time(timeleft(&timo));
630                 calltimeout();
631                 if (kill_link) {
632                     if (!persist)
633                         die(0);
634                     kill_link = 0;
635                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
636                 }
637                 reap_kids();
638             } while (phase == PHASE_HOLDOFF);
639         }
640     }
641
642     die(0);
643     return 0;
644 }
645
646 /*
647  * detach - detach us from the controlling terminal.
648  */
649 void
650 detach()
651 {
652     if (detached)
653         return;
654     if (daemon(0, 0) < 0) {
655         perror("Couldn't detach from controlling terminal");
656         die(1);
657     }
658     detached = 1;
659     pid = getpid();
660     /* update pid file if it has been written already */
661     if (pidfilename[0])
662         create_pidfile();
663 }
664
665 /*
666  * Create a file containing our process ID.
667  */
668 static void
669 create_pidfile()
670 {
671     FILE *pidfile;
672
673     (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
674     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
675         fprintf(pidfile, "%d\n", pid);
676         (void) fclose(pidfile);
677     } else {
678         syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
679         pidfilename[0] = 0;
680     }
681 }
682
683 /*
684  * holdoff_end - called via a timeout when the holdoff period ends.
685  */
686 static void
687 holdoff_end(arg)
688     void *arg;
689 {
690     phase = PHASE_DORMANT;
691 }
692
693 /*
694  * get_input - called when incoming data is available.
695  */
696 static void
697 get_input()
698 {
699     int len, i;
700     u_char *p;
701     u_short protocol;
702     struct protent *protp;
703
704     p = inpacket_buf;   /* point to beginning of packet buffer */
705
706     len = read_packet(inpacket_buf);
707     if (len < 0)
708         return;
709
710     if (len == 0) {
711         etime = time((time_t *) NULL);
712         minutes = (etime-stime)/60;
713         syslog(LOG_NOTICE, "Modem hangup, connected for %d minutes", (minutes >1) ? minutes : 1);
714         hungup = 1;
715         lcp_lowerdown(0);       /* serial link is no longer available */
716         link_terminated(0);
717         return;
718     }
719
720     if (debug /*&& (debugflags & DBG_INPACKET)*/)
721         log_packet(p, len, "rcvd ", LOG_DEBUG);
722
723     if (len < PPP_HDRLEN) {
724         MAINDEBUG((LOG_INFO, "io(): Received short packet."));
725         return;
726     }
727
728     p += 2;                             /* Skip address and control */
729     GETSHORT(protocol, p);
730     len -= PPP_HDRLEN;
731
732     /*
733      * Toss all non-LCP packets unless LCP is OPEN.
734      */
735     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
736         MAINDEBUG((LOG_INFO,
737                    "get_input: Received non-LCP packet when LCP not open."));
738         return;
739     }
740
741     /*
742      * Until we get past the authentication phase, toss all packets
743      * except LCP, LQR and authentication packets.
744      */
745     if (phase <= PHASE_AUTHENTICATE
746         && !(protocol == PPP_LCP || protocol == PPP_LQR
747              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
748         MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
749                    protocol, phase));
750         return;
751     }
752
753     /*
754      * Upcall the proper protocol input routine.
755      */
756     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
757         if (protp->protocol == protocol && protp->enabled_flag) {
758             (*protp->input)(0, p, len);
759             return;
760         }
761         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
762             && protp->datainput != NULL) {
763             (*protp->datainput)(0, p, len);
764             return;
765         }
766     }
767
768     if (debug)
769         syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
770     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
771 }
772
773
774 /*
775  * quit - Clean up state and exit (with an error indication).
776  */
777 void 
778 quit()
779 {
780     die(1);
781 }
782
783 /*
784  * die - like quit, except we can specify an exit status.
785  */
786 void
787 die(status)
788     int status;
789 {
790     cleanup();
791     syslog(LOG_INFO, "Exit.");
792     exit(status);
793 }
794
795 /*
796  * cleanup - restore anything which needs to be restored before we exit
797  */
798 /* ARGSUSED */
799 static void
800 cleanup()
801 {
802     sys_cleanup();
803
804     if (ttyfd >= 0)
805         close_tty();
806
807     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
808         syslog(LOG_WARNING, "unable to delete pid file: %m");
809     pidfilename[0] = 0;
810
811     if (locked)
812         unlock();
813 }
814
815 /*
816  * close_tty - restore the terminal device and close it.
817  */
818 static void
819 close_tty()
820 {
821     disestablish_ppp(ttyfd);
822
823     /* drop dtr to hang up */
824     if (modem) {
825         setdtr(ttyfd, FALSE);
826         /*
827          * This sleep is in case the serial port has CLOCAL set by default,
828          * and consequently will reassert DTR when we close the device.
829          */
830         sleep(1);
831     }
832
833     restore_tty(ttyfd);
834
835     if (tty_mode != (mode_t) -1)
836         fchmod(ttyfd, tty_mode);
837
838     close(ttyfd);
839     ttyfd = -1;
840 }
841
842
843 struct  callout {
844     struct timeval      c_time;         /* time at which to call routine */
845     void                *c_arg;         /* argument to routine */
846     void                (*c_func) __P((void *)); /* routine */
847     struct              callout *c_next;
848 };
849
850 static struct callout *callout = NULL;  /* Callout list */
851 static struct timeval timenow;          /* Current time */
852
853 /*
854  * timeout - Schedule a timeout.
855  *
856  * Note that this timeout takes the number of seconds, NOT hz (as in
857  * the kernel).
858  */
859 void
860 timeout(func, arg, time)
861     void (*func) __P((void *));
862     void *arg;
863     int time;
864 {
865     struct callout *newp, *p, **pp;
866   
867     MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
868                (long) func, (long) arg, time));
869   
870     /*
871      * Allocate timeout.
872      */
873     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
874         syslog(LOG_ERR, "Out of memory in timeout()!");
875         die(1);
876     }
877     newp->c_arg = arg;
878     newp->c_func = func;
879     gettimeofday(&timenow, NULL);
880     newp->c_time.tv_sec = timenow.tv_sec + time;
881     newp->c_time.tv_usec = timenow.tv_usec;
882   
883     /*
884      * Find correct place and link it in.
885      */
886     for (pp = &callout; (p = *pp); pp = &p->c_next)
887         if (newp->c_time.tv_sec < p->c_time.tv_sec
888             || (newp->c_time.tv_sec == p->c_time.tv_sec
889                 && newp->c_time.tv_usec < p->c_time.tv_sec))
890             break;
891     newp->c_next = p;
892     *pp = newp;
893 }
894
895
896 /*
897  * untimeout - Unschedule a timeout.
898  */
899 void
900 untimeout(func, arg)
901     void (*func) __P((void *));
902     void *arg;
903 {
904     struct callout **copp, *freep;
905   
906     MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
907   
908     /*
909      * Find first matching timeout and remove it from the list.
910      */
911     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
912         if (freep->c_func == func && freep->c_arg == arg) {
913             *copp = freep->c_next;
914             (void) free((char *) freep);
915             break;
916         }
917 }
918
919
920 /*
921  * calltimeout - Call any timeout routines which are now due.
922  */
923 static void
924 calltimeout()
925 {
926     struct callout *p;
927
928     while (callout != NULL) {
929         p = callout;
930
931         if (gettimeofday(&timenow, NULL) < 0) {
932             syslog(LOG_ERR, "Failed to get time of day: %m");
933             die(1);
934         }
935         if (!(p->c_time.tv_sec < timenow.tv_sec
936               || (p->c_time.tv_sec == timenow.tv_sec
937                   && p->c_time.tv_usec <= timenow.tv_usec)))
938             break;              /* no, it's not time yet */
939
940         callout = p->c_next;
941         (*p->c_func)(p->c_arg);
942
943         free((char *) p);
944     }
945 }
946
947
948 /*
949  * timeleft - return the length of time until the next timeout is due.
950  */
951 static struct timeval *
952 timeleft(tvp)
953     struct timeval *tvp;
954 {
955     if (callout == NULL)
956         return NULL;
957
958     gettimeofday(&timenow, NULL);
959     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
960     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
961     if (tvp->tv_usec < 0) {
962         tvp->tv_usec += 1000000;
963         tvp->tv_sec -= 1;
964     }
965     if (tvp->tv_sec < 0)
966         tvp->tv_sec = tvp->tv_usec = 0;
967
968     return tvp;
969 }
970
971
972 /*
973  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
974  */
975 static void
976 kill_my_pg(sig)
977     int sig;
978 {
979     struct sigaction act, oldact;
980
981     act.sa_handler = SIG_IGN;
982     act.sa_flags = 0;
983     kill(0, sig);
984     sigaction(sig, &act, &oldact);
985     sigaction(sig, &oldact, NULL);
986 }
987
988
989 /*
990  * hup - Catch SIGHUP signal.
991  *
992  * Indicates that the physical layer has been disconnected.
993  * We don't rely on this indication; if the user has sent this
994  * signal, we just take the link down.
995  */
996 static void
997 hup(sig)
998     int sig;
999 {
1000     syslog(LOG_INFO, "Hangup (SIGHUP)");
1001     kill_link = 1;
1002     if (conn_running)
1003         /* Send the signal to the [dis]connector process(es) also */
1004         kill_my_pg(sig);
1005 }
1006
1007
1008 /*
1009  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1010  *
1011  * Indicates that we should initiate a graceful disconnect and exit.
1012  */
1013 /*ARGSUSED*/
1014 static void
1015 term(sig)
1016     int sig;
1017 {
1018     syslog(LOG_INFO, "Terminating on signal %d.", sig);
1019     persist = 0;                /* don't try to restart */
1020     kill_link = 1;
1021     if (conn_running)
1022         /* Send the signal to the [dis]connector process(es) also */
1023         kill_my_pg(sig);
1024 }
1025
1026
1027 /*
1028  * chld - Catch SIGCHLD signal.
1029  * Calls reap_kids to get status for any dead kids.
1030  */
1031 static void
1032 chld(sig)
1033     int sig;
1034 {
1035     reap_kids();
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 }
1070
1071
1072 /*
1073  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1074  */
1075 static void
1076 bad_signal(sig)
1077     int sig;
1078 {
1079     static int crashed = 0;
1080
1081     if (crashed)
1082         _exit(127);
1083     crashed = 1;
1084     syslog(LOG_ERR, "Fatal signal %d", sig);
1085     if (conn_running)
1086         kill_my_pg(SIGTERM);
1087     die(1);
1088 }
1089
1090
1091 /*
1092  * device_script - run a program to connect or disconnect the
1093  * serial device.
1094  */
1095 static int
1096 device_script(program, in, out)
1097     char *program;
1098     int in, out;
1099 {
1100     int pid;
1101     int status;
1102     int errfd;
1103
1104     conn_running = 1;
1105     pid = fork();
1106
1107     if (pid < 0) {
1108         conn_running = 0;
1109         syslog(LOG_ERR, "Failed to create child process: %m");
1110         die(1);
1111     }
1112
1113     if (pid == 0) {
1114         sys_close();
1115         closelog();
1116         if (in == out) {
1117             if (in != 0) {
1118                 dup2(in, 0);
1119                 close(in);
1120             }
1121             dup2(0, 1);
1122         } else {
1123             if (out == 0)
1124                 out = dup(out);
1125             if (in != 0) {
1126                 dup2(in, 0);
1127                 close(in);
1128             }
1129             if (out != 1) {
1130                 dup2(out, 1);
1131                 close(out);
1132             }
1133         }
1134         if (nodetach == 0) {
1135             close(2);
1136             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1137             if (errfd >= 0 && errfd != 2) {
1138                 dup2(errfd, 2);
1139                 close(errfd);
1140             }
1141         }
1142         setuid(getuid());
1143         setgid(getgid());
1144         execl("/bin/sh", "sh", "-c", program, (char *)0);
1145         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1146         _exit(99);
1147         /* NOTREACHED */
1148     }
1149
1150     while (waitpid(pid, &status, 0) < 0) {
1151         if (errno == EINTR)
1152             continue;
1153         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1154         die(1);
1155     }
1156     conn_running = 0;
1157
1158     return (status == 0 ? 0 : -1);
1159 }
1160
1161
1162 /*
1163  * run-program - execute a program with given arguments,
1164  * but don't wait for it.
1165  * If the program can't be executed, logs an error unless
1166  * must_exist is 0 and the program file doesn't exist.
1167  */
1168 int
1169 run_program(prog, args, must_exist)
1170     char *prog;
1171     char **args;
1172     int must_exist;
1173 {
1174     int pid;
1175
1176     pid = fork();
1177     if (pid == -1) {
1178         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1179         return -1;
1180     }
1181     if (pid == 0) {
1182         int new_fd;
1183
1184         /* Leave the current location */
1185         (void) setsid();    /* No controlling tty. */
1186         (void) umask (S_IRWXG|S_IRWXO);
1187         (void) chdir ("/"); /* no current directory. */
1188         setuid(geteuid());
1189         setgid(getegid());
1190
1191         /* Ensure that nothing of our device environment is inherited. */
1192         sys_close();
1193         closelog();
1194         close (0);
1195         close (1);
1196         close (2);
1197         close (ttyfd);  /* tty interface to the ppp device */
1198
1199         /* Don't pass handles to the PPP device, even by accident. */
1200         new_fd = open (_PATH_DEVNULL, O_RDWR);
1201         if (new_fd >= 0) {
1202             if (new_fd != 0) {
1203                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1204                 close (new_fd);
1205             }
1206             dup2 (0, 1); /* stdout -> /dev/null */
1207             dup2 (0, 2); /* stderr -> /dev/null */
1208         }
1209
1210 #ifdef BSD
1211         /* Force the priority back to zero if pppd is running higher. */
1212         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1213             syslog (LOG_WARNING, "can't reset priority to 0: %m"); 
1214 #endif
1215
1216         /* SysV recommends a second fork at this point. */
1217
1218         /* run the program; give it a null environment */
1219         execve(prog, args, script_env);
1220         if (must_exist || errno != ENOENT)
1221             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1222         _exit(-1);
1223     }
1224     MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1225     ++n_children;
1226     return 0;
1227 }
1228
1229
1230 /*
1231  * reap_kids - get status from any dead child processes,
1232  * and log a message for abnormal terminations.
1233  */
1234 static void
1235 reap_kids()
1236 {
1237     int pid, status;
1238
1239     if (n_children == 0)
1240         return;
1241     if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1242         if (errno != ECHILD)
1243             syslog(LOG_ERR, "Error waiting for child process: %m");
1244         return;
1245     }
1246     if (pid > 0) {
1247         --n_children;
1248         if (WIFSIGNALED(status)) {
1249             syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1250                    pid, WTERMSIG(status));
1251         }
1252     }
1253 }
1254
1255
1256 /*
1257  * log_packet - format a packet and log it.
1258  */
1259
1260 char line[256];                 /* line to be logged accumulated here */
1261 char *linep;
1262
1263 void
1264 log_packet(p, len, prefix, level)
1265     u_char *p;
1266     int len;
1267     char *prefix;
1268     int level;
1269 {
1270     strcpy(line, prefix);
1271     linep = line + strlen(line);
1272     format_packet(p, len, pr_log, NULL);
1273     if (linep != line)
1274         syslog(level, "%s", line);
1275 }
1276
1277 /*
1278  * format_packet - make a readable representation of a packet,
1279  * calling `printer(arg, format, ...)' to output it.
1280  */
1281 void
1282 format_packet(p, len, printer, arg)
1283     u_char *p;
1284     int len;
1285     void (*printer) __P((void *, char *, ...));
1286     void *arg;
1287 {
1288     int i, n;
1289     u_short proto;
1290     u_char x;
1291     struct protent *protp;
1292
1293     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1294         p += 2;
1295         GETSHORT(proto, p);
1296         len -= PPP_HDRLEN;
1297         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1298             if (proto == protp->protocol)
1299                 break;
1300         if (protp != NULL) {
1301             printer(arg, "[%s", protp->name);
1302             n = (*protp->printpkt)(p, len, printer, arg);
1303             printer(arg, "]");
1304             p += n;
1305             len -= n;
1306         } else {
1307             printer(arg, "[proto=0x%x]", proto);
1308         }
1309     }
1310
1311     for (; len > 0; --len) {
1312         GETCHAR(x, p);
1313         printer(arg, " %.2x", x);
1314     }
1315 }
1316
1317 static void
1318 pr_log __V((void *arg, char *fmt, ...))
1319 {
1320     int n;
1321     va_list pvar;
1322     char buf[256];
1323
1324 #if __STDC__
1325     va_start(pvar, fmt);
1326 #else
1327     void *arg;
1328     char *fmt;
1329     va_start(pvar);
1330     arg = va_arg(pvar, void *);
1331     fmt = va_arg(pvar, char *);
1332 #endif
1333
1334     n = vfmtmsg(buf, sizeof(buf), fmt, pvar);
1335     va_end(pvar);
1336
1337     if (linep + n + 1 > line + sizeof(line)) {
1338         syslog(LOG_DEBUG, "%s", line);
1339         linep = line;
1340     }
1341     strcpy(linep, buf);
1342     linep += n;
1343 }
1344
1345 /*
1346  * print_string - print a readable representation of a string using
1347  * printer.
1348  */
1349 void
1350 print_string(p, len, printer, arg)
1351     char *p;
1352     int len;
1353     void (*printer) __P((void *, char *, ...));
1354     void *arg;
1355 {
1356     int c;
1357
1358     printer(arg, "\"");
1359     for (; len > 0; --len) {
1360         c = *p++;
1361         if (' ' <= c && c <= '~') {
1362             if (c == '\\' || c == '"')
1363                 printer(arg, "\\");
1364             printer(arg, "%c", c);
1365         } else {
1366             switch (c) {
1367             case '\n':
1368                 printer(arg, "\\n");
1369                 break;
1370             case '\r':
1371                 printer(arg, "\\r");
1372                 break;
1373             case '\t':
1374                 printer(arg, "\\t");
1375                 break;
1376             default:
1377                 printer(arg, "\\%.3o", c);
1378             }
1379         }
1380     }
1381     printer(arg, "\"");
1382 }
1383
1384 /*
1385  * novm - log an error message saying we ran out of memory, and die.
1386  */
1387 void
1388 novm(msg)
1389     char *msg;
1390 {
1391     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1392     die(1);
1393 }
1394
1395 /*
1396  * fmtmsg - format a message into a buffer.  Like sprintf except we
1397  * also specify the length of the output buffer, and we handle
1398  * %r (recursive format), %m (error message) and %I (IP address) formats.
1399  * Doesn't do floating-point formats.
1400  * Returns the number of chars put into buf.
1401  */
1402 int
1403 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1404 {
1405     va_list args;
1406     int n;
1407
1408 #if __STDC__
1409     va_start(args, fmt);
1410 #else
1411     char *buf;
1412     int buflen;
1413     char *fmt;
1414     va_start(args);
1415     buf = va_arg(args, char *);
1416     buflen = va_arg(args, int);
1417     fmt = va_arg(args, char *);
1418 #endif
1419     n = vfmtmsg(buf, buflen, fmt, args);
1420     va_end(args);
1421     return n;
1422 }
1423
1424 /*
1425  * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1426  */
1427 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1428
1429 int
1430 vfmtmsg(buf, buflen, fmt, args)
1431     char *buf;
1432     int buflen;
1433     char *fmt;
1434     va_list args;
1435 {
1436     int c, i, n;
1437     int width, prec, fillch;
1438     int base, len, neg, quoted;
1439     unsigned long val = 0;
1440     char *str, *f, *buf0;
1441     unsigned char *p;
1442     char num[32];
1443     time_t t;
1444     static char hexchars[] = "0123456789abcdef";
1445
1446     buf0 = buf;
1447     --buflen;
1448     while (buflen > 0) {
1449         for (f = fmt; *f != '%' && *f != 0; ++f)
1450             ;
1451         if (f > fmt) {
1452             len = f - fmt;
1453             if (len > buflen)
1454                 len = buflen;
1455             memcpy(buf, fmt, len);
1456             buf += len;
1457             buflen -= len;
1458             fmt = f;
1459         }
1460         if (*fmt == 0)
1461             break;
1462         c = *++fmt;
1463         width = prec = 0;
1464         fillch = ' ';
1465         if (c == '0') {
1466             fillch = '0';
1467             c = *++fmt;
1468         }
1469         if (c == '*') {
1470             width = va_arg(args, int);
1471             c = *++fmt;
1472         } else {
1473             while (isdigit(c)) {
1474                 width = width * 10 + c - '0';
1475                 c = *++fmt;
1476             }
1477         }
1478         if (c == '.') {
1479             c = *++fmt;
1480             if (c == '*') {
1481                 prec = va_arg(args, int);
1482                 c = *++fmt;
1483             } else {
1484                 while (isdigit(c)) {
1485                     prec = prec * 10 + c - '0';
1486                     c = *++fmt;
1487                 }
1488             }
1489         }
1490         str = 0;
1491         base = 0;
1492         neg = 0;
1493         ++fmt;
1494         switch (c) {
1495         case 'd':
1496             i = va_arg(args, int);
1497             if (i < 0) {
1498                 neg = 1;
1499                 val = -i;
1500             } else
1501                 val = i;
1502             base = 10;
1503             break;
1504         case 'o':
1505             val = va_arg(args, unsigned int);
1506             base = 8;
1507             break;
1508         case 'x':
1509             val = va_arg(args, unsigned int);
1510             base = 16;
1511             break;
1512         case 'p':
1513             val = (unsigned long) va_arg(args, void *);
1514             base = 16;
1515             neg = 2;
1516             break;
1517         case 's':
1518             str = va_arg(args, char *);
1519             break;
1520         case 'c':
1521             num[0] = va_arg(args, int);
1522             num[1] = 0;
1523             str = num;
1524             break;
1525         case 'm':
1526             str = strerror(errno);
1527             break;
1528         case 'I':
1529             str = ip_ntoa(va_arg(args, u_int32_t));
1530             break;
1531         case 'r':
1532             f = va_arg(args, char *);
1533 #ifndef __powerpc__
1534             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1535 #else
1536             /* On the powerpc, a va_list is an array of 1 structure */
1537             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1538 #endif
1539             buf += n;
1540             buflen -= n;
1541             continue;
1542         case 't':
1543             time(&t);
1544             str = ctime(&t);
1545             str += 4;           /* chop off the day name */
1546             str[15] = 0;        /* chop off year and newline */
1547             break;
1548         case 'v':               /* "visible" string */
1549         case 'q':               /* quoted string */
1550             quoted = c == 'q';
1551             p = va_arg(args, unsigned char *);
1552             if (fillch == '0' && prec > 0) {
1553                 n = prec;
1554             } else {
1555                 n = strlen((char *)p);
1556                 if (prec > 0 && prec < n)
1557                     n = prec;
1558             }
1559             while (n > 0 && buflen > 0) {
1560                 c = *p++;
1561                 --n;
1562                 if (!quoted && c >= 0x80) {
1563                     OUTCHAR('M');
1564                     OUTCHAR('-');
1565                     c -= 0x80;
1566                 }
1567                 if (quoted && (c == '"' || c == '\\'))
1568                     OUTCHAR('\\');
1569                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1570                     if (quoted) {
1571                         OUTCHAR('\\');
1572                         switch (c) {
1573                         case '\t':      OUTCHAR('t');   break;
1574                         case '\n':      OUTCHAR('n');   break;
1575                         case '\b':      OUTCHAR('b');   break;
1576                         case '\f':      OUTCHAR('f');   break;
1577                         default:
1578                             OUTCHAR('x');
1579                             OUTCHAR(hexchars[c >> 4]);
1580                             OUTCHAR(hexchars[c & 0xf]);
1581                         }
1582                     } else {
1583                         if (c == '\t')
1584                             OUTCHAR(c);
1585                         else {
1586                             OUTCHAR('^');
1587                             OUTCHAR(c ^ 0x40);
1588                         }
1589                     }
1590                 } else
1591                     OUTCHAR(c);
1592             }
1593             continue;
1594         default:
1595             *buf++ = '%';
1596             if (c != '%')
1597                 --fmt;          /* so %z outputs %z etc. */
1598             --buflen;
1599             continue;
1600         }
1601         if (base != 0) {
1602             str = num + sizeof(num);
1603             *--str = 0;
1604             while (str > num + neg) {
1605                 *--str = hexchars[val % base];
1606                 val = val / base;
1607                 if (--prec <= 0 && val == 0)
1608                     break;
1609             }
1610             switch (neg) {
1611             case 1:
1612                 *--str = '-';
1613                 break;
1614             case 2:
1615                 *--str = 'x';
1616                 *--str = '0';
1617                 break;
1618             }
1619             len = num + sizeof(num) - 1 - str;
1620         } else {
1621             len = strlen(str);
1622             if (prec > 0 && len > prec)
1623                 len = prec;
1624         }
1625         if (width > 0) {
1626             if (width > buflen)
1627                 width = buflen;
1628             if ((n = width - len) > 0) {
1629                 buflen -= n;
1630                 for (; n > 0; --n)
1631                     *buf++ = fillch;
1632             }
1633         }
1634         if (len > buflen)
1635             len = buflen;
1636         memcpy(buf, str, len);
1637         buf += len;
1638         buflen -= len;
1639     }
1640     *buf = 0;
1641     return buf - buf0;
1642 }
1643
1644 /*
1645  * script_setenv - set an environment variable value to be used
1646  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1647  */
1648 void
1649 script_setenv(var, value)
1650     char *var, *value;
1651 {
1652     int vl = strlen(var);
1653     int i;
1654     char *p, *newstring;
1655
1656     newstring = (char *) malloc(vl + strlen(value) + 2);
1657     if (newstring == 0)
1658         return;
1659     strcpy(newstring, var);
1660     newstring[vl] = '=';
1661     strcpy(newstring+vl+1, value);
1662
1663     /* check if this variable is already set */
1664     if (script_env != 0) {
1665         for (i = 0; (p = script_env[i]) != 0; ++i) {
1666             if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1667                 free(p);
1668                 script_env[i] = newstring;
1669                 return;
1670             }
1671         }
1672     } else {
1673         i = 0;
1674         script_env = (char **) malloc(16 * sizeof(char *));
1675         if (script_env == 0)
1676             return;
1677         s_env_nalloc = 16;
1678     }
1679
1680     /* reallocate script_env with more space if needed */
1681     if (i + 1 >= s_env_nalloc) {
1682         int new_n = i + 17;
1683         char **newenv = (char **) realloc((void *)script_env,
1684                                           new_n * sizeof(char *));
1685         if (newenv == 0)
1686             return;
1687         script_env = newenv;
1688         s_env_nalloc = new_n;
1689     }
1690
1691     script_env[i] = newstring;
1692     script_env[i+1] = 0;
1693 }
1694
1695 /*
1696  * script_unsetenv - remove a variable from the environment
1697  * for scripts.
1698  */
1699 void
1700 script_unsetenv(var)
1701     char *var;
1702 {
1703     int vl = strlen(var);
1704     int i;
1705     char *p;
1706
1707     if (script_env == 0)
1708         return;
1709     for (i = 0; (p = script_env[i]) != 0; ++i) {
1710         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1711             free(p);
1712             while ((script_env[i] = script_env[i+1]) != 0)
1713                 ++i;
1714             break;
1715         }
1716     }
1717 }