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