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