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