]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
5b57e99a00c6fbda3b66e7df2c5805d5b984d921
[ppp.git] / pppd / main.c
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright (c) 1989 Carnegie Mellon University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by Carnegie Mellon University.  The name of the
13  * University may not be used to endorse or promote products derived
14  * from this software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  */
19
20 #define RCSID   "$Id: main.c,v 1.92 2000/04/04 07:06:51 paulus Exp $"
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 <setjmp.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 #include <netinet/in.h>
43 #include <arpa/inet.h>
44
45 #include "pppd.h"
46 #include "magic.h"
47 #include "fsm.h"
48 #include "lcp.h"
49 #include "ipcp.h"
50 #ifdef INET6
51 #include "ipv6cp.h"
52 #endif
53 #include "upap.h"
54 #include "chap.h"
55 #include "ccp.h"
56 #include "pathnames.h"
57 #include "patchlevel.h"
58 #include "tdb.h"
59
60 #ifdef CBCP_SUPPORT
61 #include "cbcp.h"
62 #endif
63
64 #ifdef IPX_CHANGE
65 #include "ipxcp.h"
66 #endif /* IPX_CHANGE */
67 #ifdef AT_CHANGE
68 #include "atcp.h"
69 #endif
70
71 static const char rcsid[] = RCSID;
72
73 /* interface vars */
74 char ifname[32];                /* Interface name */
75 int ifunit;                     /* Interface unit number */
76
77 char *progname;                 /* Name of this program */
78 char hostname[MAXNAMELEN];      /* Our hostname */
79 static char pidfilename[MAXPATHLEN];    /* name of pid file */
80 static char linkpidfile[MAXPATHLEN];    /* name of linkname pid file */
81 static char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
82 static uid_t uid;               /* Our real user-id */
83 static int conn_running;        /* we have a [dis]connector running */
84
85 int ttyfd;                      /* Serial port file descriptor */
86 mode_t tty_mode = -1;           /* Original access permissions to tty */
87 int baud_rate;                  /* Actual bits/second for serial device */
88 int hungup;                     /* terminal has been hung up */
89 int privileged;                 /* we're running as real uid root */
90 int need_holdoff;               /* need holdoff period before restarting */
91 int detached;                   /* have detached from terminal */
92 struct stat devstat;            /* result of stat() on devnam */
93 int prepass = 0;                /* doing prepass to find device name */
94 int devnam_fixed;               /* set while in options.ttyxx file */
95 volatile int status;            /* exit status for pppd */
96 int unsuccess;                  /* # unsuccessful connection attempts */
97 int do_callback;                /* != 0 if we should do callback next */
98 int doing_callback;             /* != 0 if we are doing callback */
99 char *callback_script;          /* script for doing callback */
100 TDB_CONTEXT *pppdb;             /* database for storing status etc. */
101 char db_key[32];
102
103 int (*holdoff_hook) __P((void)) = NULL;
104 int (*new_phase_hook) __P((int)) = NULL;
105
106 static int fd_ppp = -1;         /* fd for talking PPP */
107 static int fd_loop;             /* fd for getting demand-dial packets */
108 static int pty_master;          /* fd for master side of pty */
109 static int pty_slave;           /* fd for slave side of pty */
110 static int real_ttyfd;          /* fd for actual serial port (not pty) */
111
112 int phase;                      /* where the link is at */
113 int kill_link;
114 int open_ccp_flag;
115
116 static int waiting;
117 static sigjmp_buf sigjmp;
118
119 char **script_env;              /* Env. variable values for scripts */
120 int s_env_nalloc;               /* # words avail at script_env */
121
122 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
123 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
124
125 static int n_children;          /* # child processes still running */
126 static int got_sigchld;         /* set if we have received a SIGCHLD */
127
128 static int locked;              /* lock() has succeeded */
129 static int privopen;            /* don't lock, open device as root */
130
131 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
132
133 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
134 int ngroups;                    /* How many groups valid in groups */
135
136 static struct timeval start_time;       /* Time when link was started. */
137
138 struct pppd_stats link_stats;
139 int link_connect_time;
140 int link_stats_valid;
141
142 static int charshunt_pid;       /* Process ID for charshunt */
143
144 /*
145  * We maintain a list of child process pids and
146  * functions to call when they exit.
147  */
148 struct subprocess {
149     pid_t       pid;
150     char        *prog;
151     void        (*done) __P((void *));
152     void        *arg;
153     struct subprocess *next;
154 };
155
156 static struct subprocess *children;
157
158 /* Prototypes for procedures local to this file. */
159
160 static void setup_signals __P((void));
161 static void create_pidfile __P((void));
162 static void create_linkpidfile __P((void));
163 static void cleanup __P((void));
164 static void close_tty __P((void));
165 static void get_input __P((void));
166 static void calltimeout __P((void));
167 static struct timeval *timeleft __P((struct timeval *));
168 static void kill_my_pg __P((int));
169 static void hup __P((int));
170 static void term __P((int));
171 static void chld __P((int));
172 static void toggle_debug __P((int));
173 static void open_ccp __P((int));
174 static void bad_signal __P((int));
175 static void holdoff_end __P((void *));
176 static int device_script __P((char *, int, int, int));
177 static int reap_kids __P((int waitfor));
178 static void record_child __P((int, char *, void (*) (void *), void *));
179 static void update_db_entry __P((void));
180 static void add_db_key __P((const char *));
181 static void delete_db_key __P((const char *));
182 static int open_socket __P((char *));
183 static int start_charshunt __P((int, int));
184 static void charshunt_done __P((void *));
185 static void charshunt __P((int, int, char *));
186 static int record_write __P((FILE *, int code, u_char *buf, int nb,
187                              struct timeval *));
188
189 extern  char    *ttyname __P((int));
190 extern  char    *getlogin __P((void));
191 int main __P((int, char *[]));
192
193 #ifdef ultrix
194 #undef  O_NONBLOCK
195 #define O_NONBLOCK      O_NDELAY
196 #endif
197
198 #ifdef ULTRIX
199 #define setlogmask(x)
200 #endif
201
202 /*
203  * PPP Data Link Layer "protocol" table.
204  * One entry per supported protocol.
205  * The last entry must be NULL.
206  */
207 struct protent *protocols[] = {
208     &lcp_protent,
209     &pap_protent,
210     &chap_protent,
211 #ifdef CBCP_SUPPORT
212     &cbcp_protent,
213 #endif
214     &ipcp_protent,
215 #ifdef INET6
216     &ipv6cp_protent,
217 #endif
218     &ccp_protent,
219 #ifdef IPX_CHANGE
220     &ipxcp_protent,
221 #endif
222 #ifdef AT_CHANGE
223     &atcp_protent,
224 #endif
225     NULL
226 };
227
228 int
229 main(argc, argv)
230     int argc;
231     char *argv[];
232 {
233     int i, fdflags, t;
234     char *p, *connector;
235     struct passwd *pw;
236     struct timeval timo;
237     sigset_t mask;
238     struct protent *protp;
239     struct stat statbuf;
240     char numbuf[16];
241
242     new_phase(PHASE_INITIALIZE);
243
244     /*
245      * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
246      * This way we can close 0, 1, 2 in detach() without clobbering
247      * a fd that we are using.
248      */
249     if ((i = open("/dev/null", O_RDWR)) >= 0) {
250         while (0 <= i && i <= 2)
251             i = dup(i);
252         if (i >= 0)
253             close(i);
254     }
255
256     script_env = NULL;
257
258     /* Initialize syslog facilities */
259     reopen_log();
260
261     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
262         option_error("Couldn't get hostname: %m");
263         exit(1);
264     }
265     hostname[MAXNAMELEN-1] = 0;
266
267     /* make sure we don't create world or group writable files. */
268     umask(umask(0777) | 022);
269
270     uid = getuid();
271     privileged = uid == 0;
272     slprintf(numbuf, sizeof(numbuf), "%d", uid);
273     script_setenv("ORIG_UID", numbuf, 0);
274
275     ngroups = getgroups(NGROUPS_MAX, groups);
276
277     /*
278      * Initialize magic number generator now so that protocols may
279      * use magic numbers in initialization.
280      */
281     magic_init();
282
283     /*
284      * Initialize to the standard option set, then parse, in order,
285      * the system options file, the user's options file,
286      * the tty's options file, and the command line arguments.
287      */
288     for (i = 0; (protp = protocols[i]) != NULL; ++i)
289         (*protp->init)(0);
290
291     progname = *argv;
292
293     prepass = 0;
294     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
295         || !options_from_user())
296         exit(EXIT_OPTION_ERROR);
297
298     /* scan command line and options files to find device name */
299     prepass = 1;
300     parse_args(argc-1, argv+1);
301     prepass = 0;
302
303     /*
304      * Work out the device name, if it hasn't already been specified.
305      */
306     using_pty = notty || ptycommand != NULL || pty_socket != NULL;
307     if (!using_pty && default_device) {
308         char *p;
309         if (!isatty(0) || (p = ttyname(0)) == NULL) {
310             option_error("no device specified and stdin is not a tty");
311             exit(EXIT_OPTION_ERROR);
312         }
313         strlcpy(devnam, p, sizeof(devnam));
314         if (stat(devnam, &devstat) < 0)
315             fatal("Couldn't stat default device %s: %m", devnam);
316     }
317
318     /*
319      * Parse the tty options file and the command line.
320      * The per-tty options file should not change
321      * ptycommand, pty_socket, notty or devnam.
322      */
323     devnam_fixed = 1;
324     if (!using_pty) {
325         if (!options_for_tty())
326             exit(EXIT_OPTION_ERROR);
327     }
328
329     devnam_fixed = 0;
330     if (!parse_args(argc-1, argv+1))
331         exit(EXIT_OPTION_ERROR);
332
333     /*
334      * Check that we are running as root.
335      */
336     if (geteuid() != 0) {
337         option_error("must be root to run %s, since it is not setuid-root",
338                      argv[0]);
339         exit(EXIT_NOT_ROOT);
340     }
341
342     if (!ppp_available()) {
343         option_error(no_ppp_msg);
344         exit(EXIT_NO_KERNEL_SUPPORT);
345     }
346
347     /*
348      * Check that the options given are valid and consistent.
349      */
350     if (!sys_check_options())
351         exit(EXIT_OPTION_ERROR);
352     auth_check_options();
353 #ifdef HAVE_MULTILINK
354     mp_check_options();
355 #endif
356     for (i = 0; (protp = protocols[i]) != NULL; ++i)
357         if (protp->check_options != NULL)
358             (*protp->check_options)();
359     if (demand && connect_script == 0) {
360         option_error("connect script is required for demand-dialling\n");
361         exit(EXIT_OPTION_ERROR);
362     }
363     /* default holdoff to 0 if no connect script has been given */
364     if (connect_script == 0 && !holdoff_specified)
365         holdoff = 0;
366
367     if (using_pty) {
368         if (!default_device) {
369             option_error("%s option precludes specifying device name",
370                          notty? "notty": "pty");
371             exit(EXIT_OPTION_ERROR);
372         }
373         if (ptycommand != NULL && notty) {
374             option_error("pty option is incompatible with notty option");
375             exit(EXIT_OPTION_ERROR);
376         }
377         if (pty_socket != NULL && (ptycommand != NULL || notty)) {
378             option_error("socket option is incompatible with pty and notty");
379             exit(EXIT_OPTION_ERROR);
380         }
381         default_device = notty;
382         lockflag = 0;
383         modem = 0;
384         if (notty && log_to_fd <= 1)
385             log_to_fd = -1;
386     } else {
387         /*
388          * If the user has specified a device which is the same as
389          * the one on stdin, pretend they didn't specify any.
390          * If the device is already open read/write on stdin,
391          * we assume we don't need to lock it, and we can open it as root.
392          */
393         if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
394             && statbuf.st_rdev == devstat.st_rdev) {
395             default_device = 1;
396             fdflags = fcntl(0, F_GETFL);
397             if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
398                 privopen = 1;
399         }
400     }
401     if (default_device)
402         nodetach = 1;
403
404     /*
405      * Don't send log messages to the serial port, it tends to
406      * confuse the peer. :-)
407      */
408     if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
409         && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
410         log_to_fd = -1;
411
412     /*
413      * Initialize system-dependent stuff.
414      */
415     sys_init();
416     if (debug)
417         setlogmask(LOG_UPTO(LOG_DEBUG));
418
419     pppdb = tdb_open(_PATH_PPPDB, 0, TDB_CLEAR_IF_FIRST, O_RDWR|O_CREAT, 0644);
420     if (pppdb != NULL) {
421         slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
422         update_db_entry();
423     } else {
424         warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
425         if (multilink) {
426             warn("Warning: disabling multilink");
427             multilink = 0;
428         }
429     }
430
431     /*
432      * Detach ourselves from the terminal, if required,
433      * and identify who is running us.
434      */
435     if (!nodetach && !updetach)
436         detach();
437     p = getlogin();
438     if (p == NULL) {
439         pw = getpwuid(uid);
440         if (pw != NULL && pw->pw_name != NULL)
441             p = pw->pw_name;
442         else
443             p = "(unknown)";
444     }
445     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
446            VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
447     script_setenv("PPPLOGNAME", p, 0);
448
449     if (devnam[0])
450         script_setenv("DEVICE", devnam, 1);
451
452     setup_signals();
453
454     waiting = 0;
455
456     create_linkpidfile();
457
458     /*
459      * If we're doing dial-on-demand, set up the interface now.
460      */
461     if (demand) {
462         /*
463          * Open the loopback channel and set it up to be the ppp interface.
464          */
465         fd_loop = open_ppp_loopback();
466         set_ifunit(1);
467
468         /*
469          * Configure the interface and mark it up, etc.
470          */
471         demand_conf();
472     }
473
474     do_callback = 0;
475     for (;;) {
476
477         need_holdoff = 1;
478         ttyfd = -1;
479         real_ttyfd = -1;
480         status = EXIT_OK;
481         ++unsuccess;
482         doing_callback = do_callback;
483         do_callback = 0;
484
485         if (demand && !doing_callback) {
486             /*
487              * Don't do anything until we see some activity.
488              */
489             kill_link = 0;
490             new_phase(PHASE_DORMANT);
491             demand_unblock();
492             add_fd(fd_loop);
493             for (;;) {
494                 if (sigsetjmp(sigjmp, 1) == 0) {
495                     sigprocmask(SIG_BLOCK, &mask, NULL);
496                     if (kill_link || got_sigchld) {
497                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
498                     } else {
499                         waiting = 1;
500                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
501                         wait_input(timeleft(&timo));
502                     }
503                 }
504                 waiting = 0;
505                 calltimeout();
506                 if (kill_link) {
507                     if (!persist)
508                         break;
509                     kill_link = 0;
510                 }
511                 if (get_loop_output())
512                     break;
513                 if (got_sigchld)
514                     reap_kids(0);
515             }
516             remove_fd(fd_loop);
517             if (kill_link && !persist)
518                 break;
519
520             /*
521              * Now we want to bring up the link.
522              */
523             demand_block();
524             info("Starting link");
525         }
526
527         new_phase(PHASE_SERIALCONN);
528
529         /*
530          * Get a pty master/slave pair if the pty, notty, socket,
531          * or record options were specified.
532          */
533         strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
534         pty_master = -1;
535         pty_slave = -1;
536         if (using_pty || record_file != NULL) {
537             if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
538                 error("Couldn't allocate pseudo-tty");
539                 status = EXIT_FATAL_ERROR;
540                 goto fail;
541             }
542             set_up_tty(pty_slave, 1);
543         }
544
545         /*
546          * Lock the device if we've been asked to.
547          */
548         status = EXIT_LOCK_FAILED;
549         if (lockflag && !privopen) {
550             if (lock(devnam) < 0)
551                 goto fail;
552             locked = 1;
553         }
554
555         /*
556          * Open the serial device and set it up to be the ppp interface.
557          * First we open it in non-blocking mode so we can set the
558          * various termios flags appropriately.  If we aren't dialling
559          * out and we want to use the modem lines, we reopen it later
560          * in order to wait for the carrier detect signal from the modem.
561          */
562         hungup = 0;
563         kill_link = 0;
564         connector = doing_callback? callback_script: connect_script;
565         if (devnam[0] != 0) {
566             for (;;) {
567                 /* If the user specified the device name, become the
568                    user before opening it. */
569                 int err;
570                 if (!devnam_info.priv && !privopen)
571                     seteuid(uid);
572                 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
573                 err = errno;
574                 if (!devnam_info.priv && !privopen)
575                     seteuid(0);
576                 if (ttyfd >= 0)
577                     break;
578                 errno = err;
579                 if (err != EINTR) {
580                     error("Failed to open %s: %m", devnam);
581                     status = EXIT_OPEN_FAILED;
582                 }
583                 if (!persist || err != EINTR)
584                     goto fail;
585             }
586             if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
587                 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
588                 warn("Couldn't reset non-blocking mode on device: %m");
589
590             /*
591              * Do the equivalent of `mesg n' to stop broadcast messages.
592              */
593             if (fstat(ttyfd, &statbuf) < 0
594                 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
595                 warn("Couldn't restrict write permissions to %s: %m", devnam);
596             } else
597                 tty_mode = statbuf.st_mode;
598
599             /*
600              * Set line speed, flow control, etc.
601              * If we have a non-null connection or initializer script,
602              * on most systems we set CLOCAL for now so that we can talk
603              * to the modem before carrier comes up.  But this has the
604              * side effect that we might miss it if CD drops before we
605              * get to clear CLOCAL below.  On systems where we can talk
606              * successfully to the modem with CLOCAL clear and CD down,
607              * we could clear CLOCAL at this point.
608              */
609             set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
610                                || initializer != NULL));
611             real_ttyfd = ttyfd;
612         }
613
614         /*
615          * If the pty, socket, notty and/or record option was specified,
616          * start up the character shunt now.
617          */
618         status = EXIT_PTYCMD_FAILED;
619         if (ptycommand != NULL) {
620             if (record_file != NULL) {
621                 int ipipe[2], opipe[2], ok;
622
623                 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
624                     fatal("Couldn't create pipes for record option: %m");
625                 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
626                     && start_charshunt(ipipe[0], opipe[1]);
627                 close(ipipe[0]);
628                 close(ipipe[1]);
629                 close(opipe[0]);
630                 close(opipe[1]);
631                 if (!ok)
632                     goto fail;
633             } else {
634                 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
635                     goto fail;
636                 ttyfd = pty_slave;
637                 close(pty_master);
638                 pty_master = -1;
639             }
640         } else if (pty_socket != NULL) {
641             int fd = open_socket(pty_socket);
642             if (fd < 0)
643                 goto fail;
644             if (!start_charshunt(fd, fd))
645                 goto fail;
646         } else if (notty) {
647             if (!start_charshunt(0, 1))
648                 goto fail;
649         } else if (record_file != NULL) {
650             if (!start_charshunt(ttyfd, ttyfd))
651                 goto fail;
652         }
653
654         /* run connection script */
655         if ((connector && connector[0]) || initializer) {
656             if (real_ttyfd != -1) {
657                 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
658                 if (!default_device && modem) {
659                     setdtr(real_ttyfd, 0);      /* in case modem is off hook */
660                     sleep(1);
661                     setdtr(real_ttyfd, 1);
662                 }
663             }
664
665             if (initializer && initializer[0]) {
666                 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
667                     error("Initializer script failed");
668                     status = EXIT_INIT_FAILED;
669                     goto fail;
670                 }
671                 if (kill_link)
672                     goto disconnect;
673
674                 info("Serial port initialized.");
675             }
676
677             if (connector && connector[0]) {
678                 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
679                     error("Connect script failed");
680                     status = EXIT_CONNECT_FAILED;
681                     goto fail;
682                 }
683                 if (kill_link)
684                     goto disconnect;
685
686                 info("Serial connection established.");
687             }
688
689             /* set line speed, flow control, etc.;
690                clear CLOCAL if modem option */
691             if (real_ttyfd != -1)
692                 set_up_tty(real_ttyfd, 0);
693
694             if (doing_callback == CALLBACK_DIALIN)
695                 connector = NULL;
696         }
697
698         /* reopen tty if necessary to wait for carrier */
699         if (connector == NULL && modem && devnam[0] != 0) {
700             for (;;) {
701                 if ((i = open(devnam, O_RDWR)) >= 0)
702                     break;
703                 if (errno != EINTR) {
704                     error("Failed to reopen %s: %m", devnam);
705                     status = EXIT_OPEN_FAILED;
706                 }
707                 if (!persist || errno != EINTR || hungup || kill_link)
708                     goto fail;
709             }
710             close(i);
711         }
712
713         slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
714         script_setenv("SPEED", numbuf, 0);
715
716         /* run welcome script, if any */
717         if (welcomer && welcomer[0]) {
718             if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
719                 warn("Welcome script failed");
720         }
721
722         /* set up the serial device as a ppp interface */
723         fd_ppp = establish_ppp(ttyfd);
724         if (fd_ppp < 0) {
725             status = EXIT_FATAL_ERROR;
726             goto disconnect;
727         }
728
729         if (!demand && ifunit >= 0)
730             set_ifunit(1);
731
732         /*
733          * Start opening the connection and wait for
734          * incoming events (reply, timeout, etc.).
735          */
736         notice("Connect: %s <--> %s", ifname, ppp_devnam);
737         gettimeofday(&start_time, NULL);
738         link_stats_valid = 0;
739         script_unsetenv("CONNECT_TIME");
740         script_unsetenv("BYTES_SENT");
741         script_unsetenv("BYTES_RCVD");
742         lcp_lowerup(0);
743
744         /*
745          * If we are initiating this connection, wait for a short
746          * time for something from the peer.  This can avoid bouncing
747          * our packets off his tty before he has it set up.
748          */
749         add_fd(fd_ppp);
750         if (connect_delay != 0 && (connector != NULL || ptycommand != NULL)) {
751             struct timeval t;
752             t.tv_sec = connect_delay / 1000;
753             t.tv_usec = connect_delay % 1000;
754             wait_input(&t);
755         }
756
757         lcp_open(0);            /* Start protocol */
758         open_ccp_flag = 0;
759         status = EXIT_NEGOTIATION_FAILED;
760         new_phase(PHASE_ESTABLISH);
761         while (phase != PHASE_DEAD) {
762             if (sigsetjmp(sigjmp, 1) == 0) {
763                 sigprocmask(SIG_BLOCK, &mask, NULL);
764                 if (kill_link || open_ccp_flag || got_sigchld) {
765                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
766                 } else {
767                     waiting = 1;
768                     sigprocmask(SIG_UNBLOCK, &mask, NULL);
769                     wait_input(timeleft(&timo));
770                 }
771             }
772             waiting = 0;
773             calltimeout();
774             get_input();
775             if (kill_link) {
776                 lcp_close(0, "User request");
777                 kill_link = 0;
778             }
779             if (open_ccp_flag) {
780                 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
781                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
782                     (*ccp_protent.open)(0);
783                 }
784                 open_ccp_flag = 0;
785             }
786             if (got_sigchld)
787                 reap_kids(0);   /* Don't leave dead kids lying around */
788         }
789
790         /*
791          * Print connect time and statistics.
792          */
793         if (link_stats_valid) {
794             int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
795             info("Connect time %d.%d minutes.", t/10, t%10);
796             info("Sent %d bytes, received %d bytes.",
797                  link_stats.bytes_out, link_stats.bytes_in);
798         }
799
800         /*
801          * Delete pid file before disestablishing ppp.  Otherwise it
802          * can happen that another pppd gets the same unit and then
803          * we delete its pid file.
804          */
805         if (!demand) {
806             if (pidfilename[0] != 0
807                 && unlink(pidfilename) < 0 && errno != ENOENT) 
808                 warn("unable to delete pid file %s: %m", pidfilename);
809             pidfilename[0] = 0;
810         }
811
812         /*
813          * If we may want to bring the link up again, transfer
814          * the ppp unit back to the loopback.  Set the
815          * real serial device back to its normal mode of operation.
816          */
817         remove_fd(fd_ppp);
818         clean_check();
819         if (demand)
820             restore_loop();
821         disestablish_ppp(ttyfd);
822         fd_ppp = -1;
823         if (!hungup)
824             lcp_lowerdown(0);
825
826         /*
827          * Run disconnector script, if requested.
828          * XXX we may not be able to do this if the line has hung up!
829          */
830     disconnect:
831         if (disconnect_script && !hungup) {
832             new_phase(PHASE_DISCONNECT);
833             if (real_ttyfd >= 0)
834                 set_up_tty(real_ttyfd, 1);
835             if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
836                 warn("disconnect script failed");
837             } else {
838                 info("Serial link disconnected.");
839             }
840         }
841
842     fail:
843         if (pty_master >= 0)
844             close(pty_master);
845         if (pty_slave >= 0)
846             close(pty_slave);
847         if (real_ttyfd >= 0)
848             close_tty();
849         if (locked) {
850             unlock();
851             locked = 0;
852         }
853
854         if (!demand) {
855             if (pidfilename[0] != 0
856                 && unlink(pidfilename) < 0 && errno != ENOENT) 
857                 warn("unable to delete pid file %s: %m", pidfilename);
858             pidfilename[0] = 0;
859         }
860
861         if (!persist || (maxfail > 0 && unsuccess >= maxfail))
862             break;
863
864         kill_link = 0;
865         if (demand)
866             demand_discard();
867         t = need_holdoff? holdoff: 0;
868         if (holdoff_hook)
869             t = (*holdoff_hook)();
870         if (t > 0) {
871             new_phase(PHASE_HOLDOFF);
872             TIMEOUT(holdoff_end, NULL, t);
873             do {
874                 if (sigsetjmp(sigjmp, 1) == 0) {
875                     sigprocmask(SIG_BLOCK, &mask, NULL);
876                     if (kill_link || got_sigchld) {
877                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
878                     } else {
879                         waiting = 1;
880                         sigprocmask(SIG_UNBLOCK, &mask, NULL);
881                         wait_input(timeleft(&timo));
882                     }
883                 }
884                 waiting = 0;
885                 calltimeout();
886                 if (kill_link) {
887                     kill_link = 0;
888                     new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
889                 }
890                 if (got_sigchld)
891                     reap_kids(0);
892             } while (phase == PHASE_HOLDOFF);
893             if (!persist)
894                 break;
895         }
896     }
897
898     /* Wait for scripts to finish */
899     /* XXX should have a timeout here */
900     while (n_children > 0) {
901         if (debug) {
902             struct subprocess *chp;
903             dbglog("Waiting for %d child processes...", n_children);
904             for (chp = children; chp != NULL; chp = chp->next)
905                 dbglog("  script %s, pid %d", chp->prog, chp->pid);
906         }
907         if (reap_kids(1) < 0)
908             break;
909     }
910
911     die(status);
912     return 0;
913 }
914
915 /*
916  * setup_signals - initialize signal handling.
917  */
918 static void
919 setup_signals()
920 {
921     struct sigaction sa;
922     sigset_t mask;
923
924     /*
925      * Compute mask of all interesting signals and install signal handlers
926      * for each.  Only one signal handler may be active at a time.  Therefore,
927      * all other signals should be masked when any handler is executing.
928      */
929     sigemptyset(&mask);
930     sigaddset(&mask, SIGHUP);
931     sigaddset(&mask, SIGINT);
932     sigaddset(&mask, SIGTERM);
933     sigaddset(&mask, SIGCHLD);
934     sigaddset(&mask, SIGUSR2);
935
936 #define SIGNAL(s, handler)      do { \
937         sa.sa_handler = handler; \
938         if (sigaction(s, &sa, NULL) < 0) \
939             fatal("Couldn't establish signal handler (%d): %m", s); \
940     } while (0)
941
942     sa.sa_mask = mask;
943     sa.sa_flags = 0;
944     SIGNAL(SIGHUP, hup);                /* Hangup */
945     SIGNAL(SIGINT, term);               /* Interrupt */
946     SIGNAL(SIGTERM, term);              /* Terminate */
947     SIGNAL(SIGCHLD, chld);
948
949     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
950     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
951
952     /*
953      * Install a handler for other signals which would otherwise
954      * cause pppd to exit without cleaning up.
955      */
956     SIGNAL(SIGABRT, bad_signal);
957     SIGNAL(SIGALRM, bad_signal);
958     SIGNAL(SIGFPE, bad_signal);
959     SIGNAL(SIGILL, bad_signal);
960     SIGNAL(SIGPIPE, bad_signal);
961     SIGNAL(SIGQUIT, bad_signal);
962     SIGNAL(SIGSEGV, bad_signal);
963 #ifdef SIGBUS
964     SIGNAL(SIGBUS, bad_signal);
965 #endif
966 #ifdef SIGEMT
967     SIGNAL(SIGEMT, bad_signal);
968 #endif
969 #ifdef SIGPOLL
970     SIGNAL(SIGPOLL, bad_signal);
971 #endif
972 #ifdef SIGPROF
973     SIGNAL(SIGPROF, bad_signal);
974 #endif
975 #ifdef SIGSYS
976     SIGNAL(SIGSYS, bad_signal);
977 #endif
978 #ifdef SIGTRAP
979     SIGNAL(SIGTRAP, bad_signal);
980 #endif
981 #ifdef SIGVTALRM
982     SIGNAL(SIGVTALRM, bad_signal);
983 #endif
984 #ifdef SIGXCPU
985     SIGNAL(SIGXCPU, bad_signal);
986 #endif
987 #ifdef SIGXFSZ
988     SIGNAL(SIGXFSZ, bad_signal);
989 #endif
990
991     /*
992      * Apparently we can get a SIGPIPE when we call syslog, if
993      * syslogd has died and been restarted.  Ignoring it seems
994      * be sufficient.
995      */
996     signal(SIGPIPE, SIG_IGN);
997 }
998
999 /*
1000  * set_ifunit - do things we need to do once we know which ppp
1001  * unit we are using.
1002  */
1003 void
1004 set_ifunit(iskey)
1005     int iskey;
1006 {
1007     info("Using interface ppp%d", ifunit);
1008     slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
1009     script_setenv("IFNAME", ifname, iskey);
1010     create_pidfile();   /* write pid to file */
1011     create_linkpidfile();
1012 }
1013
1014 /*
1015  * detach - detach us from the controlling terminal.
1016  */
1017 void
1018 detach()
1019 {
1020     int pid;
1021
1022     if (detached)
1023         return;
1024     if ((pid = fork()) < 0) {
1025         error("Couldn't detach (fork failed: %m)");
1026         die(1);                 /* or just return? */
1027     }
1028     if (pid != 0) {
1029         /* parent */
1030         if (locked)
1031             relock(pid);
1032         exit(0);                /* parent dies */
1033     }
1034     setsid();
1035     chdir("/");
1036     close(0);
1037     close(1);
1038     close(2);
1039     detached = 1;
1040     log_to_fd = -1;
1041     /* update pid files if they have been written already */
1042     if (pidfilename[0])
1043         create_pidfile();
1044     if (linkpidfile[0])
1045         create_linkpidfile();
1046 }
1047
1048 /*
1049  * reopen_log - (re)open our connection to syslog.
1050  */
1051 void
1052 reopen_log()
1053 {
1054 #ifdef ULTRIX
1055     openlog("pppd", LOG_PID);
1056 #else
1057     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1058     setlogmask(LOG_UPTO(LOG_INFO));
1059 #endif
1060 }
1061
1062 /*
1063  * Create a file containing our process ID.
1064  */
1065 static void
1066 create_pidfile()
1067 {
1068     FILE *pidfile;
1069     char numbuf[16];
1070
1071     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1072              _PATH_VARRUN, ifname);
1073     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1074         fprintf(pidfile, "%d\n", getpid());
1075         (void) fclose(pidfile);
1076     } else {
1077         error("Failed to create pid file %s: %m", pidfilename);
1078         pidfilename[0] = 0;
1079     }
1080     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1081     script_setenv("PPPD_PID", numbuf, 1);
1082 }
1083
1084 static void
1085 create_linkpidfile()
1086 {
1087     FILE *pidfile;
1088
1089     if (linkname[0] == 0)
1090         return;
1091     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1092              _PATH_VARRUN, linkname);
1093     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1094         fprintf(pidfile, "%d\n", getpid());
1095         if (ifname[0])
1096             fprintf(pidfile, "%s\n", ifname);
1097         (void) fclose(pidfile);
1098     } else {
1099         error("Failed to create pid file %s: %m", linkpidfile);
1100         linkpidfile[0] = 0;
1101     }
1102     script_setenv("LINKNAME", linkname, 1);
1103 }
1104
1105 /*
1106  * holdoff_end - called via a timeout when the holdoff period ends.
1107  */
1108 static void
1109 holdoff_end(arg)
1110     void *arg;
1111 {
1112     new_phase(PHASE_DORMANT);
1113 }
1114
1115 /* List of protocol names, to make our messages a little more informative. */
1116 struct protocol_list {
1117     u_short     proto;
1118     const char  *name;
1119 } protocol_list[] = {
1120     { 0x21,     "IP" },
1121     { 0x23,     "OSI Network Layer" },
1122     { 0x25,     "Xerox NS IDP" },
1123     { 0x27,     "DECnet Phase IV" },
1124     { 0x29,     "Appletalk" },
1125     { 0x2b,     "Novell IPX" },
1126     { 0x2d,     "VJ compressed TCP/IP" },
1127     { 0x2f,     "VJ uncompressed TCP/IP" },
1128     { 0x31,     "Bridging PDU" },
1129     { 0x33,     "Stream Protocol ST-II" },
1130     { 0x35,     "Banyan Vines" },
1131     { 0x39,     "AppleTalk EDDP" },
1132     { 0x3b,     "AppleTalk SmartBuffered" },
1133     { 0x3d,     "Multi-Link" },
1134     { 0x3f,     "NETBIOS Framing" },
1135     { 0x41,     "Cisco Systems" },
1136     { 0x43,     "Ascom Timeplex" },
1137     { 0x45,     "Fujitsu Link Backup and Load Balancing (LBLB)" },
1138     { 0x47,     "DCA Remote Lan" },
1139     { 0x49,     "Serial Data Transport Protocol (PPP-SDTP)" },
1140     { 0x4b,     "SNA over 802.2" },
1141     { 0x4d,     "SNA" },
1142     { 0x4f,     "IP6 Header Compression" },
1143     { 0x6f,     "Stampede Bridging" },
1144     { 0xfb,     "single-link compression" },
1145     { 0xfd,     "1st choice compression" },
1146     { 0x0201,   "802.1d Hello Packets" },
1147     { 0x0203,   "IBM Source Routing BPDU" },
1148     { 0x0205,   "DEC LANBridge100 Spanning Tree" },
1149     { 0x0231,   "Luxcom" },
1150     { 0x0233,   "Sigma Network Systems" },
1151     { 0x8021,   "Internet Protocol Control Protocol" },
1152     { 0x8023,   "OSI Network Layer Control Protocol" },
1153     { 0x8025,   "Xerox NS IDP Control Protocol" },
1154     { 0x8027,   "DECnet Phase IV Control Protocol" },
1155     { 0x8029,   "Appletalk Control Protocol" },
1156     { 0x802b,   "Novell IPX Control Protocol" },
1157     { 0x8031,   "Bridging NCP" },
1158     { 0x8033,   "Stream Protocol Control Protocol" },
1159     { 0x8035,   "Banyan Vines Control Protocol" },
1160     { 0x803d,   "Multi-Link Control Protocol" },
1161     { 0x803f,   "NETBIOS Framing Control Protocol" },
1162     { 0x8041,   "Cisco Systems Control Protocol" },
1163     { 0x8043,   "Ascom Timeplex" },
1164     { 0x8045,   "Fujitsu LBLB Control Protocol" },
1165     { 0x8047,   "DCA Remote Lan Network Control Protocol (RLNCP)" },
1166     { 0x8049,   "Serial Data Control Protocol (PPP-SDCP)" },
1167     { 0x804b,   "SNA over 802.2 Control Protocol" },
1168     { 0x804d,   "SNA Control Protocol" },
1169     { 0x804f,   "IP6 Header Compression Control Protocol" },
1170     { 0x006f,   "Stampede Bridging Control Protocol" },
1171     { 0x80fb,   "Single Link Compression Control Protocol" },
1172     { 0x80fd,   "Compression Control Protocol" },
1173     { 0xc021,   "Link Control Protocol" },
1174     { 0xc023,   "Password Authentication Protocol" },
1175     { 0xc025,   "Link Quality Report" },
1176     { 0xc027,   "Shiva Password Authentication Protocol" },
1177     { 0xc029,   "CallBack Control Protocol (CBCP)" },
1178     { 0xc081,   "Container Control Protocol" },
1179     { 0xc223,   "Challenge Handshake Authentication Protocol" },
1180     { 0xc281,   "Proprietary Authentication Protocol" },
1181     { 0,        NULL },
1182 };
1183
1184 /*
1185  * protocol_name - find a name for a PPP protocol.
1186  */
1187 const char *
1188 protocol_name(proto)
1189     int proto;
1190 {
1191     struct protocol_list *lp;
1192
1193     for (lp = protocol_list; lp->proto != 0; ++lp)
1194         if (proto == lp->proto)
1195             return lp->name;
1196     return NULL;
1197 }
1198
1199 /*
1200  * get_input - called when incoming data is available.
1201  */
1202 static void
1203 get_input()
1204 {
1205     int len, i;
1206     u_char *p;
1207     u_short protocol;
1208     struct protent *protp;
1209
1210     p = inpacket_buf;   /* point to beginning of packet buffer */
1211
1212     len = read_packet(inpacket_buf);
1213     if (len < 0)
1214         return;
1215
1216     if (len == 0) {
1217         notice("Modem hangup");
1218         hungup = 1;
1219         status = EXIT_HANGUP;
1220         lcp_lowerdown(0);       /* serial link is no longer available */
1221         link_terminated(0);
1222         return;
1223     }
1224
1225     if (debug /*&& (debugflags & DBG_INPACKET)*/)
1226         dbglog("rcvd %P", p, len);
1227
1228     if (len < PPP_HDRLEN) {
1229         MAINDEBUG(("io(): Received short packet."));
1230         return;
1231     }
1232
1233     p += 2;                             /* Skip address and control */
1234     GETSHORT(protocol, p);
1235     len -= PPP_HDRLEN;
1236
1237     /*
1238      * Toss all non-LCP packets unless LCP is OPEN.
1239      */
1240     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1241         MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1242         return;
1243     }
1244
1245     /*
1246      * Until we get past the authentication phase, toss all packets
1247      * except LCP, LQR and authentication packets.
1248      */
1249     if (phase <= PHASE_AUTHENTICATE
1250         && !(protocol == PPP_LCP || protocol == PPP_LQR
1251              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1252         MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1253                    protocol, phase));
1254         return;
1255     }
1256
1257     /*
1258      * Upcall the proper protocol input routine.
1259      */
1260     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1261         if (protp->protocol == protocol && protp->enabled_flag) {
1262             (*protp->input)(0, p, len);
1263             return;
1264         }
1265         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1266             && protp->datainput != NULL) {
1267             (*protp->datainput)(0, p, len);
1268             return;
1269         }
1270     }
1271
1272     if (debug) {
1273         const char *pname = protocol_name(protocol);
1274         if (pname != NULL)
1275             warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1276         else
1277             warn("Unsupported protocol 0x%x received", protocol);
1278     }
1279     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1280 }
1281
1282 /*
1283  * new_phase - signal the start of a new phase of pppd's operation.
1284  */
1285 void
1286 new_phase(p)
1287     int p;
1288 {
1289     phase = p;
1290     if (new_phase_hook)
1291         (*new_phase_hook)(p);
1292 }
1293
1294 /*
1295  * die - clean up state and exit with the specified status.
1296  */
1297 void
1298 die(status)
1299     int status;
1300 {
1301     cleanup();
1302     syslog(LOG_INFO, "Exit.");
1303     exit(status);
1304 }
1305
1306 /*
1307  * cleanup - restore anything which needs to be restored before we exit
1308  */
1309 /* ARGSUSED */
1310 static void
1311 cleanup()
1312 {
1313     sys_cleanup();
1314
1315     if (fd_ppp >= 0)
1316         disestablish_ppp(ttyfd);
1317     if (real_ttyfd >= 0)
1318         close_tty();
1319
1320     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
1321         warn("unable to delete pid file %s: %m", pidfilename);
1322     pidfilename[0] = 0;
1323     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT) 
1324         warn("unable to delete pid file %s: %m", linkpidfile);
1325     linkpidfile[0] = 0;
1326
1327     if (locked)
1328         unlock();
1329
1330     if (pppdb != NULL) {
1331         TDB_DATA key;
1332
1333         key.dptr = db_key;
1334         key.dsize = strlen(db_key);
1335         tdb_delete(pppdb, key);
1336     }
1337 }
1338
1339 /*
1340  * close_tty - restore the terminal device and close it.
1341  */
1342 static void
1343 close_tty()
1344 {
1345     /* drop dtr to hang up */
1346     if (!default_device && modem) {
1347         setdtr(real_ttyfd, 0);
1348         /*
1349          * This sleep is in case the serial port has CLOCAL set by default,
1350          * and consequently will reassert DTR when we close the device.
1351          */
1352         sleep(1);
1353     }
1354
1355     restore_tty(real_ttyfd);
1356
1357     if (tty_mode != (mode_t) -1) {
1358         if (fchmod(real_ttyfd, tty_mode) != 0) {
1359             /* XXX if devnam is a symlink, this will change the link */
1360             chmod(devnam, tty_mode);
1361         }
1362     }
1363
1364     close(real_ttyfd);
1365     real_ttyfd = -1;
1366 }
1367
1368 /*
1369  * update_link_stats - get stats at link termination.
1370  */
1371 void
1372 update_link_stats(u)
1373     int u;
1374 {
1375     struct timeval now;
1376     char numbuf[32];
1377
1378     if (!get_ppp_stats(u, &link_stats)
1379         || gettimeofday(&now, NULL) < 0)
1380         return;
1381     link_connect_time = now.tv_sec - start_time.tv_sec;
1382     link_stats_valid = 1;
1383
1384     slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1385     script_setenv("CONNECT_TIME", numbuf, 0);
1386     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1387     script_setenv("BYTES_SENT", numbuf, 0);
1388     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1389     script_setenv("BYTES_RCVD", numbuf, 0);
1390 }
1391
1392
1393 struct  callout {
1394     struct timeval      c_time;         /* time at which to call routine */
1395     void                *c_arg;         /* argument to routine */
1396     void                (*c_func) __P((void *)); /* routine */
1397     struct              callout *c_next;
1398 };
1399
1400 static struct callout *callout = NULL;  /* Callout list */
1401 static struct timeval timenow;          /* Current time */
1402
1403 /*
1404  * timeout - Schedule a timeout.
1405  *
1406  * Note that this timeout takes the number of seconds, NOT hz (as in
1407  * the kernel).
1408  */
1409 void
1410 timeout(func, arg, time)
1411     void (*func) __P((void *));
1412     void *arg;
1413     int time;
1414 {
1415     struct callout *newp, *p, **pp;
1416   
1417     MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1418   
1419     /*
1420      * Allocate timeout.
1421      */
1422     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1423         fatal("Out of memory in timeout()!");
1424     newp->c_arg = arg;
1425     newp->c_func = func;
1426     gettimeofday(&timenow, NULL);
1427     newp->c_time.tv_sec = timenow.tv_sec + time;
1428     newp->c_time.tv_usec = timenow.tv_usec;
1429   
1430     /*
1431      * Find correct place and link it in.
1432      */
1433     for (pp = &callout; (p = *pp); pp = &p->c_next)
1434         if (newp->c_time.tv_sec < p->c_time.tv_sec
1435             || (newp->c_time.tv_sec == p->c_time.tv_sec
1436                 && newp->c_time.tv_usec < p->c_time.tv_usec))
1437             break;
1438     newp->c_next = p;
1439     *pp = newp;
1440 }
1441
1442
1443 /*
1444  * untimeout - Unschedule a timeout.
1445  */
1446 void
1447 untimeout(func, arg)
1448     void (*func) __P((void *));
1449     void *arg;
1450 {
1451     struct callout **copp, *freep;
1452   
1453     MAINDEBUG(("Untimeout %p:%p.", func, arg));
1454   
1455     /*
1456      * Find first matching timeout and remove it from the list.
1457      */
1458     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1459         if (freep->c_func == func && freep->c_arg == arg) {
1460             *copp = freep->c_next;
1461             free((char *) freep);
1462             break;
1463         }
1464 }
1465
1466
1467 /*
1468  * calltimeout - Call any timeout routines which are now due.
1469  */
1470 static void
1471 calltimeout()
1472 {
1473     struct callout *p;
1474
1475     while (callout != NULL) {
1476         p = callout;
1477
1478         if (gettimeofday(&timenow, NULL) < 0)
1479             fatal("Failed to get time of day: %m");
1480         if (!(p->c_time.tv_sec < timenow.tv_sec
1481               || (p->c_time.tv_sec == timenow.tv_sec
1482                   && p->c_time.tv_usec <= timenow.tv_usec)))
1483             break;              /* no, it's not time yet */
1484
1485         callout = p->c_next;
1486         (*p->c_func)(p->c_arg);
1487
1488         free((char *) p);
1489     }
1490 }
1491
1492
1493 /*
1494  * timeleft - return the length of time until the next timeout is due.
1495  */
1496 static struct timeval *
1497 timeleft(tvp)
1498     struct timeval *tvp;
1499 {
1500     if (callout == NULL)
1501         return NULL;
1502
1503     gettimeofday(&timenow, NULL);
1504     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1505     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1506     if (tvp->tv_usec < 0) {
1507         tvp->tv_usec += 1000000;
1508         tvp->tv_sec -= 1;
1509     }
1510     if (tvp->tv_sec < 0)
1511         tvp->tv_sec = tvp->tv_usec = 0;
1512
1513     return tvp;
1514 }
1515
1516
1517 /*
1518  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1519  */
1520 static void
1521 kill_my_pg(sig)
1522     int sig;
1523 {
1524     struct sigaction act, oldact;
1525
1526     act.sa_handler = SIG_IGN;
1527     act.sa_flags = 0;
1528     kill(0, sig);
1529     sigaction(sig, &act, &oldact);
1530     sigaction(sig, &oldact, NULL);
1531 }
1532
1533
1534 /*
1535  * hup - Catch SIGHUP signal.
1536  *
1537  * Indicates that the physical layer has been disconnected.
1538  * We don't rely on this indication; if the user has sent this
1539  * signal, we just take the link down.
1540  */
1541 static void
1542 hup(sig)
1543     int sig;
1544 {
1545     info("Hangup (SIGHUP)");
1546     kill_link = 1;
1547     if (status != EXIT_HANGUP)
1548         status = EXIT_USER_REQUEST;
1549     if (conn_running)
1550         /* Send the signal to the [dis]connector process(es) also */
1551         kill_my_pg(sig);
1552     if (charshunt_pid)
1553         kill(charshunt_pid, sig);
1554     if (waiting)
1555         siglongjmp(sigjmp, 1);
1556 }
1557
1558
1559 /*
1560  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1561  *
1562  * Indicates that we should initiate a graceful disconnect and exit.
1563  */
1564 /*ARGSUSED*/
1565 static void
1566 term(sig)
1567     int sig;
1568 {
1569     info("Terminating on signal %d.", sig);
1570     persist = 0;                /* don't try to restart */
1571     kill_link = 1;
1572     status = EXIT_USER_REQUEST;
1573     if (conn_running)
1574         /* Send the signal to the [dis]connector process(es) also */
1575         kill_my_pg(sig);
1576     if (charshunt_pid)
1577         kill(charshunt_pid, sig);
1578     if (waiting)
1579         siglongjmp(sigjmp, 1);
1580 }
1581
1582
1583 /*
1584  * chld - Catch SIGCHLD signal.
1585  * Sets a flag so we will call reap_kids in the mainline.
1586  */
1587 static void
1588 chld(sig)
1589     int sig;
1590 {
1591     got_sigchld = 1;
1592     if (waiting)
1593         siglongjmp(sigjmp, 1);
1594 }
1595
1596
1597 /*
1598  * toggle_debug - Catch SIGUSR1 signal.
1599  *
1600  * Toggle debug flag.
1601  */
1602 /*ARGSUSED*/
1603 static void
1604 toggle_debug(sig)
1605     int sig;
1606 {
1607     debug = !debug;
1608     if (debug) {
1609         setlogmask(LOG_UPTO(LOG_DEBUG));
1610     } else {
1611         setlogmask(LOG_UPTO(LOG_WARNING));
1612     }
1613 }
1614
1615
1616 /*
1617  * open_ccp - Catch SIGUSR2 signal.
1618  *
1619  * Try to (re)negotiate compression.
1620  */
1621 /*ARGSUSED*/
1622 static void
1623 open_ccp(sig)
1624     int sig;
1625 {
1626     open_ccp_flag = 1;
1627     if (waiting)
1628         siglongjmp(sigjmp, 1);
1629 }
1630
1631
1632 /*
1633  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1634  */
1635 static void
1636 bad_signal(sig)
1637     int sig;
1638 {
1639     static int crashed = 0;
1640
1641     if (crashed)
1642         _exit(127);
1643     crashed = 1;
1644     error("Fatal signal %d", sig);
1645     if (conn_running)
1646         kill_my_pg(SIGTERM);
1647     if (charshunt_pid)
1648         kill(charshunt_pid, SIGTERM);
1649     die(127);
1650 }
1651
1652
1653 /*
1654  * device_script - run a program to talk to the serial device
1655  * (e.g. to run the connector or disconnector script).
1656  */
1657 static int
1658 device_script(program, in, out, dont_wait)
1659     char *program;
1660     int in, out;
1661     int dont_wait;
1662 {
1663     int pid;
1664     int status = -1;
1665     int errfd;
1666
1667     ++conn_running;
1668     pid = fork();
1669
1670     if (pid < 0) {
1671         --conn_running;
1672         error("Failed to create child process: %m");
1673         return -1;
1674     }
1675
1676     if (pid == 0) {
1677         sys_close();
1678         closelog();
1679         if (in == 2) {
1680             /* aargh!!! */
1681             int newin = dup(in);
1682             if (in == out)
1683                 out = newin;
1684             in = newin;
1685         } else if (out == 2) {
1686             out = dup(out);
1687         }
1688         if (log_to_fd >= 0) {
1689             if (log_to_fd != 2)
1690                 dup2(log_to_fd, 2);
1691         } else {
1692             close(2);
1693             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1694             if (errfd >= 0 && errfd != 2) {
1695                 dup2(errfd, 2);
1696                 close(errfd);
1697             }
1698         }
1699         if (in != 0) {
1700             if (out == 0)
1701                 out = dup(out);
1702             dup2(in, 0);
1703         }
1704         if (out != 1) {
1705             dup2(out, 1);
1706         }
1707         if (real_ttyfd > 2)
1708             close(real_ttyfd);
1709         if (pty_master > 2)
1710             close(pty_master);
1711         if (pty_slave > 2)
1712             close(pty_slave);
1713         setuid(uid);
1714         if (getuid() != uid) {
1715             error("setuid failed");
1716             exit(1);
1717         }
1718         setgid(getgid());
1719         execl("/bin/sh", "sh", "-c", program, (char *)0);
1720         error("could not exec /bin/sh: %m");
1721         exit(99);
1722         /* NOTREACHED */
1723     }
1724
1725     if (dont_wait) {
1726         record_child(pid, program, NULL, NULL);
1727         status = 0;
1728     } else {
1729         while (waitpid(pid, &status, 0) < 0) {
1730             if (errno == EINTR)
1731                 continue;
1732             fatal("error waiting for (dis)connection process: %m");
1733         }
1734         --conn_running;
1735     }
1736
1737     return (status == 0 ? 0 : -1);
1738 }
1739
1740
1741 /*
1742  * run-program - execute a program with given arguments,
1743  * but don't wait for it.
1744  * If the program can't be executed, logs an error unless
1745  * must_exist is 0 and the program file doesn't exist.
1746  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1747  * or isn't an executable plain file, or the process ID of the child.
1748  * If done != NULL, (*done)(arg) will be called later (within
1749  * reap_kids) iff the return value is > 0.
1750  */
1751 pid_t
1752 run_program(prog, args, must_exist, done, arg)
1753     char *prog;
1754     char **args;
1755     int must_exist;
1756     void (*done) __P((void *));
1757     void *arg;
1758 {
1759     int pid;
1760     struct stat sbuf;
1761
1762     /*
1763      * First check if the file exists and is executable.
1764      * We don't use access() because that would use the
1765      * real user-id, which might not be root, and the script
1766      * might be accessible only to root.
1767      */
1768     errno = EINVAL;
1769     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1770         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1771         if (must_exist || errno != ENOENT)
1772             warn("Can't execute %s: %m", prog);
1773         return 0;
1774     }
1775
1776     pid = fork();
1777     if (pid == -1) {
1778         error("Failed to create child process for %s: %m", prog);
1779         return -1;
1780     }
1781     if (pid == 0) {
1782         int new_fd;
1783
1784         /* Leave the current location */
1785         (void) setsid();        /* No controlling tty. */
1786         (void) umask (S_IRWXG|S_IRWXO);
1787         (void) chdir ("/");     /* no current directory. */
1788         setuid(0);              /* set real UID = root */
1789         setgid(getegid());
1790
1791         /* Ensure that nothing of our device environment is inherited. */
1792         sys_close();
1793         closelog();
1794         close (0);
1795         close (1);
1796         close (2);
1797         close (ttyfd);  /* tty interface to the ppp device */
1798         if (real_ttyfd >= 0)
1799             close(real_ttyfd);
1800
1801         /* Don't pass handles to the PPP device, even by accident. */
1802         new_fd = open (_PATH_DEVNULL, O_RDWR);
1803         if (new_fd >= 0) {
1804             if (new_fd != 0) {
1805                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1806                 close (new_fd);
1807             }
1808             dup2 (0, 1); /* stdout -> /dev/null */
1809             dup2 (0, 2); /* stderr -> /dev/null */
1810         }
1811
1812 #ifdef BSD
1813         /* Force the priority back to zero if pppd is running higher. */
1814         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1815             warn("can't reset priority to 0: %m"); 
1816 #endif
1817
1818         /* SysV recommends a second fork at this point. */
1819
1820         /* run the program */
1821         execve(prog, args, script_env);
1822         if (must_exist || errno != ENOENT) {
1823             /* have to reopen the log, there's nowhere else
1824                for the message to go. */
1825             reopen_log();
1826             syslog(LOG_ERR, "Can't execute %s: %m", prog);
1827             closelog();
1828         }
1829         _exit(-1);
1830     }
1831
1832     if (debug)
1833         dbglog("Script %s started (pid %d)", prog, pid);
1834     record_child(pid, prog, done, arg);
1835
1836     return pid;
1837 }
1838
1839
1840 /*
1841  * record_child - add a child process to the list for reap_kids
1842  * to use.
1843  */
1844 static void
1845 record_child(pid, prog, done, arg)
1846     int pid;
1847     char *prog;
1848     void (*done) __P((void *));
1849     void *arg;
1850 {
1851     struct subprocess *chp;
1852
1853     ++n_children;
1854
1855     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1856     if (chp == NULL) {
1857         warn("losing track of %s process", prog);
1858     } else {
1859         chp->pid = pid;
1860         chp->prog = prog;
1861         chp->done = done;
1862         chp->arg = arg;
1863         chp->next = children;
1864         children = chp;
1865     }
1866 }
1867
1868
1869 /*
1870  * reap_kids - get status from any dead child processes,
1871  * and log a message for abnormal terminations.
1872  */
1873 static int
1874 reap_kids(waitfor)
1875     int waitfor;
1876 {
1877     int pid, status;
1878     struct subprocess *chp, **prevp;
1879
1880     got_sigchld = 0;
1881     if (n_children == 0)
1882         return 0;
1883     while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1884            && pid != 0) {
1885         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1886             if (chp->pid == pid) {
1887                 --n_children;
1888                 *prevp = chp->next;
1889                 break;
1890             }
1891         }
1892         if (WIFSIGNALED(status)) {
1893             warn("Child process %s (pid %d) terminated with signal %d",
1894                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1895         } else if (debug)
1896             dbglog("Script %s finished (pid %d), status = 0x%x",
1897                    (chp? chp->prog: "??"), pid, status);
1898         if (chp && chp->done)
1899             (*chp->done)(chp->arg);
1900         if (chp)
1901             free(chp);
1902     }
1903     if (pid == -1) {
1904         if (errno == ECHILD)
1905             return -1;
1906         if (errno != EINTR)
1907             error("Error waiting for child process: %m");
1908     }
1909     return 0;
1910 }
1911
1912
1913 /*
1914  * novm - log an error message saying we ran out of memory, and die.
1915  */
1916 void
1917 novm(msg)
1918     char *msg;
1919 {
1920     fatal("Virtual memory exhausted allocating %s\n", msg);
1921 }
1922
1923 /*
1924  * script_setenv - set an environment variable value to be used
1925  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1926  */
1927 void
1928 script_setenv(var, value, iskey)
1929     char *var, *value;
1930     int iskey;
1931 {
1932     size_t varl = strlen(var);
1933     size_t vl = varl + strlen(value) + 2;
1934     int i;
1935     char *p, *newstring;
1936
1937     newstring = (char *) malloc(vl);
1938     if (newstring == 0)
1939         return;
1940     slprintf(newstring, vl, "%s=%s", var, value);
1941
1942     /* check if this variable is already set */
1943     if (script_env != 0) {
1944         for (i = 0; (p = script_env[i]) != 0; ++i) {
1945             if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1946                 if (iskey && pppdb != NULL) {
1947                     delete_db_key(p);
1948                     add_db_key(newstring);
1949                 }
1950                 free(p);
1951                 script_env[i] = newstring;
1952                 return;
1953             }
1954         }
1955     } else {
1956         /* no space allocated for script env. ptrs. yet */
1957         i = 0;
1958         script_env = (char **) malloc(16 * sizeof(char *));
1959         if (script_env == 0)
1960             return;
1961         s_env_nalloc = 16;
1962     }
1963
1964     /* reallocate script_env with more space if needed */
1965     if (i + 1 >= s_env_nalloc) {
1966         int new_n = i + 17;
1967         char **newenv = (char **) realloc((void *)script_env,
1968                                           new_n * sizeof(char *));
1969         if (newenv == 0)
1970             return;
1971         script_env = newenv;
1972         s_env_nalloc = new_n;
1973     }
1974
1975     script_env[i] = newstring;
1976     script_env[i+1] = 0;
1977
1978     if (pppdb != NULL) {
1979         if (iskey)
1980             add_db_key(newstring);
1981         update_db_entry();
1982     }
1983 }
1984
1985 /*
1986  * script_unsetenv - remove a variable from the environment
1987  * for scripts.
1988  */
1989 void
1990 script_unsetenv(var)
1991     char *var;
1992 {
1993     int vl = strlen(var);
1994     int i;
1995     char *p;
1996
1997     if (script_env == 0)
1998         return;
1999     for (i = 0; (p = script_env[i]) != 0; ++i) {
2000         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2001             free(p);
2002             while ((script_env[i] = script_env[i+1]) != 0)
2003                 ++i;
2004             break;
2005         }
2006     }
2007     if (pppdb != NULL)
2008         update_db_entry();
2009 }
2010
2011 /*
2012  * update_db_entry - update our entry in the database.
2013  */
2014 static void
2015 update_db_entry()
2016 {
2017     TDB_DATA key, dbuf;
2018     int vlen, i;
2019     char *p, *q, *vbuf;
2020
2021     if (script_env == NULL)
2022         return;
2023     vlen = 0;
2024     for (i = 0; (p = script_env[i]) != 0; ++i)
2025         vlen += strlen(p) + 1;
2026     vbuf = malloc(vlen);
2027     if (vbuf == 0)
2028         novm("database entry");
2029     q = vbuf;
2030     for (i = 0; (p = script_env[i]) != 0; ++i)
2031         q += slprintf(q, vbuf + vlen - q, "%s;", p);
2032
2033     key.dptr = db_key;
2034     key.dsize = strlen(db_key);
2035     dbuf.dptr = vbuf;
2036     dbuf.dsize = vlen;
2037     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2038         error("tdb_store failed: %s", tdb_error(pppdb));
2039
2040 }
2041
2042 /*
2043  * add_db_key - add a key that we can use to look up our database entry.
2044  */
2045 static void
2046 add_db_key(str)
2047     const char *str;
2048 {
2049     TDB_DATA key, dbuf;
2050
2051     key.dptr = (char *) str;
2052     key.dsize = strlen(str);
2053     dbuf.dptr = db_key;
2054     dbuf.dsize = strlen(db_key);
2055     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2056         error("tdb_store key failed: %s", tdb_error(pppdb));
2057 }
2058
2059 /*
2060  * delete_db_key - delete a key for looking up our database entry.
2061  */
2062 static void
2063 delete_db_key(str)
2064     const char *str;
2065 {
2066     TDB_DATA key;
2067
2068     key.dptr = (char *) str;
2069     key.dsize = strlen(str);
2070     tdb_delete(pppdb, key);
2071 }
2072
2073 /*
2074  * open_socket - establish a stream socket connection to the nominated
2075  * host and port.
2076  */
2077 static int
2078 open_socket(dest)
2079     char *dest;
2080 {
2081     char *sep, *endp = NULL;
2082     int sock, port = -1;
2083     u_int32_t host;
2084     struct hostent *hent;
2085     struct sockaddr_in sad;
2086
2087     /* parse host:port and resolve host to an IP address */
2088     sep = strchr(dest, ':');
2089     if (sep != NULL)
2090         port = strtol(sep+1, &endp, 10);
2091     if (port < 0 || endp == sep+1 || sep == dest) {
2092         error("Can't parse host:port for socket destination");
2093         return -1;
2094     }
2095     *sep = 0;
2096     host = inet_addr(dest);
2097     if (host == (u_int32_t) -1) {
2098         hent = gethostbyname(dest);
2099         if (hent == NULL) {
2100             error("%s: unknown host in socket option", dest);
2101             *sep = ':';
2102             return -1;
2103         }
2104         host = *(u_int32_t *)(hent->h_addr_list[0]);
2105     }
2106     *sep = ':';
2107
2108     /* get a socket and connect it to the other end */
2109     sock = socket(PF_INET, SOCK_STREAM, 0);
2110     if (sock < 0) {
2111         error("Can't create socket: %m");
2112         return -1;
2113     }
2114     memset(&sad, 0, sizeof(sad));
2115     sad.sin_family = AF_INET;
2116     sad.sin_port = htons(port);
2117     sad.sin_addr.s_addr = host;
2118     if (connect(sock, &sad, sizeof(sad)) < 0) {
2119         error("Can't connect to %s: %m", dest);
2120         close(sock);
2121         return -1;
2122     }
2123
2124     return sock;
2125 }
2126
2127 /*
2128  * start_charshunt - create a child process to run the character shunt.
2129  */
2130 static int
2131 start_charshunt(ifd, ofd)
2132     int ifd, ofd;
2133 {
2134     int cpid;
2135
2136     cpid = fork();
2137     if (cpid == -1) {
2138         error("Can't fork process for character shunt: %m");
2139         return 0;
2140     }
2141     if (cpid == 0) {
2142         /* child */
2143         close(pty_slave);
2144         setuid(uid);
2145         if (getuid() != uid)
2146             fatal("setuid failed");
2147         setgid(getgid());
2148         if (!nodetach)
2149             log_to_fd = -1;
2150         charshunt(ifd, ofd, record_file);
2151         exit(0);
2152     }
2153     charshunt_pid = cpid;
2154     close(pty_master);
2155     pty_master = -1;
2156     ttyfd = pty_slave;
2157     record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2158     return 1;
2159 }
2160
2161 static void
2162 charshunt_done(arg)
2163     void *arg;
2164 {
2165     charshunt_pid = 0;
2166 }
2167
2168 /*
2169  * charshunt - the character shunt, which passes characters between
2170  * the pty master side and the serial port (or stdin/stdout).
2171  * This runs as the user (not as root).
2172  * (We assume ofd >= ifd which is true the way this gets called. :-).
2173  */
2174 static void
2175 charshunt(ifd, ofd, record_file)
2176     int ifd, ofd;
2177     char *record_file;
2178 {
2179     int n, nfds;
2180     fd_set ready, writey;
2181     u_char *ibufp, *obufp;
2182     int nibuf, nobuf;
2183     int flags;
2184     int pty_readable, stdin_readable;
2185     struct timeval lasttime;
2186     FILE *recordf = NULL;
2187     int ilevel, olevel, max_level;
2188     struct timeval levelt, tout, *top;
2189
2190     /*
2191      * Reset signal handlers.
2192      */
2193     signal(SIGHUP, SIG_IGN);            /* Hangup */
2194     signal(SIGINT, SIG_DFL);            /* Interrupt */
2195     signal(SIGTERM, SIG_DFL);           /* Terminate */
2196     signal(SIGCHLD, SIG_DFL);
2197     signal(SIGUSR1, SIG_DFL);
2198     signal(SIGUSR2, SIG_DFL);
2199     signal(SIGABRT, SIG_DFL);
2200     signal(SIGALRM, SIG_DFL);
2201     signal(SIGFPE, SIG_DFL);
2202     signal(SIGILL, SIG_DFL);
2203     signal(SIGPIPE, SIG_DFL);
2204     signal(SIGQUIT, SIG_DFL);
2205     signal(SIGSEGV, SIG_DFL);
2206 #ifdef SIGBUS
2207     signal(SIGBUS, SIG_DFL);
2208 #endif
2209 #ifdef SIGEMT
2210     signal(SIGEMT, SIG_DFL);
2211 #endif
2212 #ifdef SIGPOLL
2213     signal(SIGPOLL, SIG_DFL);
2214 #endif
2215 #ifdef SIGPROF
2216     signal(SIGPROF, SIG_DFL);
2217 #endif
2218 #ifdef SIGSYS
2219     signal(SIGSYS, SIG_DFL);
2220 #endif
2221 #ifdef SIGTRAP
2222     signal(SIGTRAP, SIG_DFL);
2223 #endif
2224 #ifdef SIGVTALRM
2225     signal(SIGVTALRM, SIG_DFL);
2226 #endif
2227 #ifdef SIGXCPU
2228     signal(SIGXCPU, SIG_DFL);
2229 #endif
2230 #ifdef SIGXFSZ
2231     signal(SIGXFSZ, SIG_DFL);
2232 #endif
2233
2234     /*
2235      * Open the record file if required.
2236      */
2237     if (record_file != NULL) {
2238         recordf = fopen(record_file, "a");
2239         if (recordf == NULL)
2240             error("Couldn't create record file %s: %m", record_file);
2241     }
2242
2243     /* set all the fds to non-blocking mode */
2244     flags = fcntl(pty_master, F_GETFL);
2245     if (flags == -1
2246         || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2247         warn("couldn't set pty master to nonblock: %m");
2248     flags = fcntl(ifd, F_GETFL);
2249     if (flags == -1
2250         || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2251         warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2252     if (ofd != ifd) {
2253         flags = fcntl(ofd, F_GETFL);
2254         if (flags == -1
2255             || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2256             warn("couldn't set stdout to nonblock: %m");
2257     }
2258
2259     nibuf = nobuf = 0;
2260     ibufp = obufp = NULL;
2261     pty_readable = stdin_readable = 1;
2262
2263     ilevel = olevel = 0;
2264     gettimeofday(&levelt, NULL);
2265     if (max_data_rate) {
2266         max_level = max_data_rate / 10;
2267         if (max_level < 100)
2268             max_level = 100;
2269     } else
2270         max_level = sizeof(inpacket_buf) + 1;
2271
2272     nfds = (ofd > pty_master? ofd: pty_master) + 1;
2273     if (recordf != NULL) {
2274         gettimeofday(&lasttime, NULL);
2275         putc(7, recordf);       /* put start marker */
2276         putc(lasttime.tv_sec >> 24, recordf);
2277         putc(lasttime.tv_sec >> 16, recordf);
2278         putc(lasttime.tv_sec >> 8, recordf);
2279         putc(lasttime.tv_sec, recordf);
2280         lasttime.tv_usec = 0;
2281     }
2282
2283     while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2284         top = 0;
2285         tout.tv_sec = 0;
2286         tout.tv_usec = 10000;
2287         FD_ZERO(&ready);
2288         FD_ZERO(&writey);
2289         if (nibuf != 0) {
2290             if (ilevel >= max_level)
2291                 top = &tout;
2292             else
2293                 FD_SET(pty_master, &writey);
2294         } else if (stdin_readable)
2295             FD_SET(ifd, &ready);
2296         if (nobuf != 0) {
2297             if (olevel >= max_level)
2298                 top = &tout;
2299             else
2300                 FD_SET(ofd, &writey);
2301         } else if (pty_readable)
2302             FD_SET(pty_master, &ready);
2303         if (select(nfds, &ready, &writey, NULL, top) < 0) {
2304             if (errno != EINTR)
2305                 fatal("select");
2306             continue;
2307         }
2308         if (max_data_rate) {
2309             double dt;
2310             int nbt;
2311             struct timeval now;
2312
2313             gettimeofday(&now, NULL);
2314             dt = (now.tv_sec - levelt.tv_sec
2315                   + (now.tv_usec - levelt.tv_usec) / 1e6);
2316             nbt = (int)(dt * max_data_rate);
2317             ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2318             olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2319             levelt = now;
2320         } else
2321             ilevel = olevel = 0;
2322         if (FD_ISSET(ifd, &ready)) {
2323             ibufp = inpacket_buf;
2324             nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2325             if (nibuf < 0 && errno == EIO)
2326                 nibuf = 0;
2327             if (nibuf < 0) {
2328                 if (!(errno == EINTR || errno == EAGAIN)) {
2329                     error("Error reading standard input: %m");
2330                     break;
2331                 }
2332                 nibuf = 0;
2333             } else if (nibuf == 0) {
2334                 /* end of file from stdin */
2335                 stdin_readable = 0;
2336                 /* do a 0-length write, hopefully this will generate
2337                    an EOF (hangup) on the slave side. */
2338                 write(pty_master, inpacket_buf, 0);
2339                 if (recordf)
2340                     if (!record_write(recordf, 4, NULL, 0, &lasttime))
2341                         recordf = NULL;
2342             } else {
2343                 FD_SET(pty_master, &writey);
2344                 if (recordf)
2345                     if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2346                         recordf = NULL;
2347             }
2348         }
2349         if (FD_ISSET(pty_master, &ready)) {
2350             obufp = outpacket_buf;
2351             nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2352             if (nobuf < 0 && errno == EIO)
2353                 nobuf = 0;
2354             if (nobuf < 0) {
2355                 if (!(errno == EINTR || errno == EAGAIN)) {
2356                     error("Error reading pseudo-tty master: %m");
2357                     break;
2358                 }
2359                 nobuf = 0;
2360             } else if (nobuf == 0) {
2361                 /* end of file from the pty - slave side has closed */
2362                 pty_readable = 0;
2363                 stdin_readable = 0;     /* pty is not writable now */
2364                 nibuf = 0;
2365                 close(ofd);
2366                 if (recordf)
2367                     if (!record_write(recordf, 3, NULL, 0, &lasttime))
2368                         recordf = NULL;
2369             } else {
2370                 FD_SET(ofd, &writey);
2371                 if (recordf)
2372                     if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2373                         recordf = NULL;
2374             }
2375         }
2376         if (FD_ISSET(ofd, &writey)) {
2377             n = nobuf;
2378             if (olevel + n > max_level)
2379                 n = max_level - olevel;
2380             n = write(ofd, obufp, n);
2381             if (n < 0) {
2382                 if (errno != EIO) {
2383                     error("Error writing standard output: %m");
2384                     break;
2385                 }
2386                 pty_readable = 0;
2387                 nobuf = 0;
2388             } else {
2389                 obufp += n;
2390                 nobuf -= n;
2391                 olevel += n;
2392             }
2393         }
2394         if (FD_ISSET(pty_master, &writey)) {
2395             n = nibuf;
2396             if (ilevel + n > max_level)
2397                 n = max_level - ilevel;
2398             n = write(pty_master, ibufp, n);
2399             if (n < 0) {
2400                 if (errno != EIO) {
2401                     error("Error writing pseudo-tty master: %m");
2402                     break;
2403                 }
2404                 stdin_readable = 0;
2405                 nibuf = 0;
2406             } else {
2407                 ibufp += n;
2408                 nibuf -= n;
2409                 ilevel += n;
2410             }
2411         }
2412     }
2413     exit(0);
2414 }
2415
2416 static int
2417 record_write(f, code, buf, nb, tp)
2418     FILE *f;
2419     int code;
2420     u_char *buf;
2421     int nb;
2422     struct timeval *tp;
2423 {
2424     struct timeval now;
2425     int diff;
2426
2427     gettimeofday(&now, NULL);
2428     now.tv_usec /= 100000;      /* actually 1/10 s, not usec now */
2429     diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2430     if (diff > 0) {
2431         if (diff > 255) {
2432             putc(5, f);
2433             putc(diff >> 24, f);
2434             putc(diff >> 16, f);
2435             putc(diff >> 8, f);
2436             putc(diff, f);
2437         } else {
2438             putc(6, f);
2439             putc(diff, f);
2440         }
2441         *tp = now;
2442     }
2443     putc(code, f);
2444     if (buf != NULL) {
2445         putc(nb >> 8, f);
2446         putc(nb, f);
2447         fwrite(buf, nb, 1, f);
2448     }
2449     fflush(f);
2450     if (ferror(f)) {
2451         error("Error writing record file: %m");
2452         return 0;
2453     }
2454     return 1;
2455 }