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