]> git.ozlabs.org Git - ppp.git/blob - pppd/sys-linux.c
pppd: Add support for arbitrary baud rates via BOTHER on Linux (#278)
[ppp.git] / pppd / sys-linux.c
1 /*
2  * sys-linux.c - System-dependent procedures for setting up
3  * PPP interfaces on Linux systems
4  *
5  * Copyright (c) 1994-2004 Paul Mackerras. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. The name(s) of the authors of this software must not be used to
15  *    endorse or promote products derived from this software without
16  *    prior written permission.
17  *
18  * 3. Redistributions of any form whatsoever must retain the following
19  *    acknowledgment:
20  *    "This product includes software developed by Paul Mackerras
21  *     <paulus@samba.org>".
22  *
23  * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
24  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
25  * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
26  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
27  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
28  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
29  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
30  *
31  * Derived from main.c and pppd.h, which are:
32  *
33  * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
34  *
35  * Redistribution and use in source and binary forms, with or without
36  * modification, are permitted provided that the following conditions
37  * are met:
38  *
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  *
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in
44  *    the documentation and/or other materials provided with the
45  *    distribution.
46  *
47  * 3. The name "Carnegie Mellon University" must not be used to
48  *    endorse or promote products derived from this software without
49  *    prior written permission. For permission or any legal
50  *    details, please contact
51  *      Office of Technology Transfer
52  *      Carnegie Mellon University
53  *      5000 Forbes Avenue
54  *      Pittsburgh, PA  15213-3890
55  *      (412) 268-4387, fax: (412) 268-7395
56  *      tech-transfer@andrew.cmu.edu
57  *
58  * 4. Redistributions of any form whatsoever must retain the following
59  *    acknowledgment:
60  *    "This product includes software developed by Computing Services
61  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
62  *
63  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
64  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
65  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
66  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
67  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
68  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
69  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
70  */
71
72 #include <sys/ioctl.h>
73 #include <sys/types.h>
74 #include <sys/socket.h>
75 #include <sys/time.h>
76 #include <sys/file.h>
77 #include <sys/stat.h>
78 #include <sys/utsname.h>
79 #include <sys/sysmacros.h>
80
81 #include <errno.h>
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include <syslog.h>
85 #include <string.h>
86 #include <time.h>
87 #include <memory.h>
88 #include <utmp.h>
89 #include <mntent.h>
90 #include <signal.h>
91 #include <fcntl.h>
92 #include <ctype.h>
93 #include <termios.h>
94 #include <unistd.h>
95
96 /* This is in netdevice.h. However, this compile will fail miserably if
97    you attempt to include netdevice.h because it has so many references
98    to __memcpy functions which it should not attempt to do. So, since I
99    really don't use it, but it must be defined, define it now. */
100
101 #ifndef MAX_ADDR_LEN
102 #define MAX_ADDR_LEN 7
103 #endif
104
105 #if !defined(__GLIBC__) || __GLIBC__ >= 2
106 #include <asm/types.h>          /* glibc 2 conflicts with linux/types.h */
107 #include <asm/ioctls.h>
108 #include <net/if.h>
109 #include <net/if_arp.h>
110 #include <net/route.h>
111 #include <netinet/if_ether.h>
112 #else
113 #include <linux/types.h>
114 #include <linux/if.h>
115 #include <linux/if_arp.h>
116 #include <linux/route.h>
117 #include <linux/if_ether.h>
118 #endif
119 #include <netinet/in.h>
120 #include <arpa/inet.h>
121
122 #include <linux/ppp_defs.h>
123 #include <linux/if_ppp.h>
124
125 #ifdef INET6
126 #include <linux/netlink.h>
127 #include <linux/rtnetlink.h>
128 #include <linux/if_addr.h>
129 /* glibc versions prior to 2.24 do not define SOL_NETLINK */
130 #ifndef SOL_NETLINK
131 #define SOL_NETLINK 270
132 #endif
133 /* linux kernel versions prior to 4.3 do not define/support NETLINK_CAP_ACK */
134 #ifndef NETLINK_CAP_ACK
135 #define NETLINK_CAP_ACK 10
136 #endif
137 #endif
138
139 #include "pppd.h"
140 #include "fsm.h"
141 #include "ipcp.h"
142
143 #ifdef IPX_CHANGE
144 #include "ipxcp.h"
145 #if __GLIBC__ >= 2 && \
146     !(defined(__powerpc__) && __GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
147 #include <netipx/ipx.h>
148 #else
149 #include <linux/ipx.h>
150 #endif
151 #endif /* IPX_CHANGE */
152
153 #ifdef PPP_FILTER
154 #include <pcap-bpf.h>
155 #include <linux/filter.h>
156 #endif /* PPP_FILTER */
157
158 #ifdef LOCKLIB
159 #include <sys/locks.h>
160 #endif
161
162 #ifndef BOTHER
163 #define BOTHER 0010000
164 #endif
165 struct termios2 {
166         unsigned int c_iflag;
167         unsigned int c_oflag;
168         unsigned int c_cflag;
169         unsigned int c_lflag;
170         unsigned char c_line;
171         unsigned char c_cc[19];
172         unsigned int c_ispeed;
173         unsigned int c_ospeed;
174 };
175
176 #ifdef INET6
177 #ifndef _LINUX_IN6_H
178 /*
179  *    This is in linux/include/net/ipv6.h.
180  */
181
182 struct in6_ifreq {
183     struct in6_addr ifr6_addr;
184     __u32 ifr6_prefixlen;
185     unsigned int ifr6_ifindex;
186 };
187 #endif
188
189 #define IN6_LLADDR_FROM_EUI64(sin6, eui64) do {                 \
190         memset(&(sin6).s6_addr, 0, sizeof(struct in6_addr));    \
191         (sin6).s6_addr16[0] = htons(0xfe80);                    \
192         eui64_copy(eui64, (sin6).s6_addr32[2]);                 \
193         } while (0)
194
195 static const eui64_t nulleui64;
196 #endif /* INET6 */
197
198 /* We can get an EIO error on an ioctl if the modem has hung up */
199 #define ok_error(num) ((num)==EIO)
200
201 static int tty_disc = N_TTY;    /* The TTY discipline */
202 static int ppp_disc = N_PPP;    /* The PPP discpline */
203 static int initfdflags = -1;    /* Initial file descriptor flags for fd */
204 static int ppp_fd = -1;         /* fd which is set to PPP discipline */
205 static int sock_fd = -1;        /* socket for doing interface ioctls */
206 static int slave_fd = -1;       /* pty for old-style demand mode, slave */
207 static int master_fd = -1;      /* pty for old-style demand mode, master */
208 #ifdef INET6
209 static int sock6_fd = -1;
210 #endif /* INET6 */
211
212 /*
213  * For the old-style kernel driver, this is the same as ppp_fd.
214  * For the new-style driver, it is the fd of an instance of /dev/ppp
215  * which is attached to the ppp unit and is used for controlling it.
216  */
217 int ppp_dev_fd = -1;            /* fd for /dev/ppp (new style driver) */
218
219 static int chindex;             /* channel index (new style driver) */
220
221 static fd_set in_fds;           /* set of fds that wait_input waits for */
222 static int max_in_fd;           /* highest fd set in in_fds */
223
224 static int has_proxy_arp       = 0;
225 static int driver_version      = 0;
226 static int driver_modification = 0;
227 static int driver_patch        = 0;
228 static int driver_is_old       = 0;
229 static int restore_term        = 0;     /* 1 => we've munged the terminal */
230 static struct termios inittermios;      /* Initial TTY termios */
231
232 int new_style_driver = 0;
233
234 static char loop_name[20];
235 static unsigned char inbuf[512]; /* buffer for chars read from loopback */
236
237 static int      if_is_up;       /* Interface has been marked up */
238 static int      if6_is_up;      /* Interface has been marked up for IPv6, to help differentiate */
239 static int      have_default_route;     /* Gateway for default route added */
240 static int      have_default_route6;    /* Gateway for default IPv6 route added */
241 static struct   rtentry old_def_rt;     /* Old default route */
242 static int      default_rt_repl_rest;   /* replace and restore old default rt */
243 static u_int32_t proxy_arp_addr;        /* Addr for proxy arp entry added */
244 static char proxy_arp_dev[16];          /* Device for proxy arp entry */
245 static u_int32_t our_old_addr;          /* for detecting address changes */
246 static int      dynaddr_set;            /* 1 if ip_dynaddr set */
247 static int      looped;                 /* 1 if using loop */
248 static int      link_mtu;               /* mtu for the link (not bundle) */
249
250 static struct utsname utsname;  /* for the kernel version */
251 static int kernel_version;
252 #define KVERSION(j,n,p) ((j)*1000000 + (n)*1000 + (p))
253
254 #define MAX_IFS         100
255
256 #define FLAGS_GOOD (IFF_UP          | IFF_BROADCAST)
257 #define FLAGS_MASK (IFF_UP          | IFF_BROADCAST | \
258                     IFF_POINTOPOINT | IFF_LOOPBACK  | IFF_NOARP)
259
260 #define SIN_ADDR(x)     (((struct sockaddr_in *) (&(x)))->sin_addr.s_addr)
261
262 /* Prototypes for procedures local to this file. */
263 static int modify_flags(int fd, int clear_bits, int set_bits);
264 static int translate_speed (int bps);
265 static int baud_rate_of (int speed);
266 static void close_route_table (void);
267 static int open_route_table (void);
268 static int read_route_table (struct rtentry *rt);
269 static int defaultroute_exists (struct rtentry *rt, int metric);
270 static int defaultroute6_exists (struct in6_rtmsg *rt, int metric);
271 static int get_ether_addr (u_int32_t ipaddr, struct sockaddr *hwaddr,
272                            char *name, int namelen);
273 static void decode_version (char *buf, int *version, int *mod, int *patch);
274 static int set_kdebugflag(int level);
275 static int ppp_registered(void);
276 static int make_ppp_unit(void);
277 static int setifstate (int u, int state);
278
279 extern u_char   inpacket_buf[]; /* borrowed from main.c */
280
281 extern int dfl_route_metric;
282
283 /*
284  * SET_SA_FAMILY - set the sa_family field of a struct sockaddr,
285  * if it exists.
286  */
287
288 #define SET_SA_FAMILY(addr, family)                     \
289     memset ((char *) &(addr), '\0', sizeof(addr));      \
290     addr.sa_family = (family);
291
292 /*
293  * Determine if the PPP connection should still be present.
294  */
295
296 extern int hungup;
297
298 /* new_fd is the fd of a tty */
299 static void set_ppp_fd (int new_fd)
300 {
301         ppp_fd = new_fd;
302         if (!new_style_driver)
303                 ppp_dev_fd = new_fd;
304 }
305
306 static int still_ppp(void)
307 {
308         if (new_style_driver)
309                 return !hungup && ppp_fd >= 0;
310         if (!hungup || ppp_fd == slave_fd)
311                 return 1;
312         if (slave_fd >= 0) {
313                 set_ppp_fd(slave_fd);
314                 return 1;
315         }
316         return 0;
317 }
318
319 /*
320  * modify_flags - set and clear flag bits controlling the kernel
321  * PPP driver.
322  */
323 static int modify_flags(int fd, int clear_bits, int set_bits)
324 {
325         int flags;
326
327         if (ioctl(fd, PPPIOCGFLAGS, &flags) == -1)
328                 goto err;
329         flags = (flags & ~clear_bits) | set_bits;
330         if (ioctl(fd, PPPIOCSFLAGS, &flags) == -1)
331                 goto err;
332
333         return 0;
334
335  err:
336         if (errno != EIO)
337                 error("Failed to set PPP kernel option flags: %m");
338         return -1;
339 }
340
341 /********************************************************************
342  *
343  * sys_init - System-dependent initialization.
344  */
345
346 void sys_init(void)
347 {
348     /* Get an internet socket for doing socket ioctls. */
349     sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
350     if (sock_fd < 0)
351         fatal("Couldn't create IP socket: %m(%d)", errno);
352
353 #ifdef INET6
354     sock6_fd = socket(AF_INET6, SOCK_DGRAM, 0);
355     if (sock6_fd < 0)
356         sock6_fd = -errno;      /* save errno for later */
357 #endif
358
359     FD_ZERO(&in_fds);
360     max_in_fd = 0;
361 }
362
363 /********************************************************************
364  *
365  * sys_cleanup - restore any system state we modified before exiting:
366  * mark the interface down, delete default route and/or proxy arp entry.
367  * This shouldn't call die() because it's called from die().
368  */
369
370 void sys_cleanup(void)
371 {
372 /*
373  * Take down the device
374  */
375     if (if_is_up) {
376         if_is_up = 0;
377         sifdown(0);
378     }
379     if (if6_is_up)
380         sif6down(0);
381
382 /*
383  * Delete any routes through the device.
384  */
385     if (have_default_route)
386         cifdefaultroute(0, 0, 0);
387 #ifdef INET6
388     if (have_default_route6)
389         cif6defaultroute(0, nulleui64, nulleui64);
390 #endif
391
392     if (has_proxy_arp)
393         cifproxyarp(0, proxy_arp_addr);
394 }
395
396 /********************************************************************
397  *
398  * sys_close - Clean up in a child process before execing.
399  */
400 void
401 sys_close(void)
402 {
403     if (new_style_driver && ppp_dev_fd >= 0)
404         close(ppp_dev_fd);
405     if (sock_fd >= 0)
406         close(sock_fd);
407 #ifdef INET6
408     if (sock6_fd >= 0)
409         close(sock6_fd);
410 #endif
411     if (slave_fd >= 0)
412         close(slave_fd);
413     if (master_fd >= 0)
414         close(master_fd);
415 }
416
417 /********************************************************************
418  *
419  * set_kdebugflag - Define the debugging level for the kernel
420  */
421
422 static int set_kdebugflag (int requested_level)
423 {
424     if (ppp_dev_fd < 0)
425         return 1;
426     if (ioctl(ppp_dev_fd, PPPIOCSDEBUG, &requested_level) < 0) {
427         if ( ! ok_error (errno) )
428             error("ioctl(PPPIOCSDEBUG): %m (line %d)", __LINE__);
429         return (0);
430     }
431     return (1);
432 }
433
434 /********************************************************************
435  *
436  * tty_establish_ppp - Turn the serial port into a ppp interface.
437  */
438
439 int tty_establish_ppp (int tty_fd)
440 {
441     int ret_fd;
442
443 /*
444  * Ensure that the tty device is in exclusive mode.
445  */
446     if (ioctl(tty_fd, TIOCEXCL, 0) < 0) {
447         if ( ! ok_error ( errno ))
448             warn("Couldn't make tty exclusive: %m");
449     }
450 /*
451  * Demand mode - prime the old ppp device to relinquish the unit.
452  */
453     if (!new_style_driver && looped
454         && ioctl(slave_fd, PPPIOCXFERUNIT, 0) < 0) {
455         error("ioctl(transfer ppp unit): %m, line %d", __LINE__);
456         return -1;
457     }
458 /*
459  * Set the current tty to the PPP discpline
460  */
461
462 #ifndef N_SYNC_PPP
463 #define N_SYNC_PPP 14
464 #endif
465     ppp_disc = (new_style_driver && sync_serial)? N_SYNC_PPP: N_PPP;
466     if (ioctl(tty_fd, TIOCSETD, &ppp_disc) < 0) {
467         if ( ! ok_error (errno) ) {
468             error("Couldn't set tty to PPP discipline: %m");
469             return -1;
470         }
471     }
472
473     ret_fd = generic_establish_ppp(tty_fd);
474
475 #define SC_RCVB (SC_RCV_B7_0 | SC_RCV_B7_1 | SC_RCV_EVNP | SC_RCV_ODDP)
476 #define SC_LOGB (SC_DEBUG | SC_LOG_INPKT | SC_LOG_OUTPKT | SC_LOG_RAWIN \
477                  | SC_LOG_FLUSH)
478
479     if (ret_fd >= 0) {
480         modify_flags(ppp_fd, SC_RCVB | SC_LOGB,
481                      (kdebugflag * SC_DEBUG) & SC_LOGB);
482     } else {
483         if (ioctl(tty_fd, TIOCSETD, &tty_disc) < 0 && !ok_error(errno))
484             warn("Couldn't reset tty to normal line discipline: %m");
485     }
486
487     return ret_fd;
488 }
489
490 /********************************************************************
491  *
492  * generic_establish_ppp - Turn the fd into a ppp interface.
493  */
494 int generic_establish_ppp (int fd)
495 {
496     int x;
497
498     if (new_style_driver) {
499         int flags;
500
501         /* If a ppp_fd is already open, close it first */
502         if (ppp_fd >= 0) {
503             close(ppp_fd);
504             remove_fd(ppp_fd);
505             ppp_fd = -1;
506         }
507
508         /* Open an instance of /dev/ppp and connect the channel to it */
509         if (ioctl(fd, PPPIOCGCHAN, &chindex) == -1) {
510             error("Couldn't get channel number: %m");
511             goto err;
512         }
513         dbglog("using channel %d", chindex);
514         fd = open("/dev/ppp", O_RDWR);
515         if (fd < 0) {
516             error("Couldn't reopen /dev/ppp: %m");
517             goto err;
518         }
519         (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
520         if (ioctl(fd, PPPIOCATTCHAN, &chindex) < 0) {
521             error("Couldn't attach to channel %d: %m", chindex);
522             goto err_close;
523         }
524         flags = fcntl(fd, F_GETFL);
525         if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
526             warn("Couldn't set /dev/ppp (channel) to nonblock: %m");
527         set_ppp_fd(fd);
528
529         if (!looped)
530             ifunit = -1;
531         if (!looped && !multilink) {
532             /*
533              * Create a new PPP unit.
534              */
535             if (make_ppp_unit() < 0)
536                 goto err_close;
537         }
538
539         if (looped)
540             modify_flags(ppp_dev_fd, SC_LOOP_TRAFFIC, 0);
541
542         if (!multilink) {
543             add_fd(ppp_dev_fd);
544             if (ioctl(fd, PPPIOCCONNECT, &ifunit) < 0) {
545                 error("Couldn't attach to PPP unit %d: %m", ifunit);
546                 goto err_close;
547             }
548         }
549
550     } else {
551         /*
552          * Old-style driver: find out which interface we were given.
553          */
554         set_ppp_fd (fd);
555         if (ioctl(fd, PPPIOCGUNIT, &x) < 0) {
556             if (ok_error (errno))
557                 goto err;
558             fatal("ioctl(PPPIOCGUNIT): %m (line %d)", __LINE__);
559         }
560         /* Check that we got the same unit again. */
561         if (looped && x != ifunit)
562             fatal("transfer_ppp failed: wanted unit %d, got %d", ifunit, x);
563         ifunit = x;
564
565         /*
566          * Fetch the initial file flags and reset blocking mode on the file.
567          */
568         initfdflags = fcntl(fd, F_GETFL);
569         if (initfdflags == -1 ||
570             fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
571             if ( ! ok_error (errno))
572                 warn("Couldn't set device to non-blocking mode: %m");
573         }
574     }
575
576     /*
577      * Enable debug in the driver if requested.
578      */
579     if (!looped)
580         set_kdebugflag (kdebugflag);
581
582     looped = 0;
583
584     return ppp_fd;
585
586  err_close:
587     close(fd);
588  err:
589     return -1;
590 }
591
592 /********************************************************************
593  *
594  * tty_disestablish_ppp - Restore the serial port to normal operation.
595  * This shouldn't call die() because it's called from die().
596  */
597
598 void tty_disestablish_ppp(int tty_fd)
599 {
600     if (!hungup) {
601 /*
602  * Flush the tty output buffer so that the TIOCSETD doesn't hang.
603  */
604         if (tcflush(tty_fd, TCIOFLUSH) < 0)
605         {
606             warn("tcflush failed: %m");
607             goto flushfailed;
608         }
609 /*
610  * Restore the previous line discipline
611  */
612         if (ioctl(tty_fd, TIOCSETD, &tty_disc) < 0) {
613             if ( ! ok_error (errno))
614                 error("ioctl(TIOCSETD, N_TTY): %m (line %d)", __LINE__);
615         }
616
617         if (ioctl(tty_fd, TIOCNXCL, 0) < 0) {
618             if ( ! ok_error (errno))
619                 warn("ioctl(TIOCNXCL): %m (line %d)", __LINE__);
620         }
621
622         /* Reset non-blocking mode on fd. */
623         if (initfdflags != -1 && fcntl(tty_fd, F_SETFL, initfdflags) < 0) {
624             if ( ! ok_error (errno))
625                 warn("Couldn't restore device fd flags: %m");
626         }
627     }
628 flushfailed:
629     initfdflags = -1;
630
631     generic_disestablish_ppp(tty_fd);
632 }
633
634 /********************************************************************
635  *
636  * generic_disestablish_ppp - Restore device components to normal
637  * operation, and reconnect the ppp unit to the loopback if in demand
638  * mode.  This shouldn't call die() because it's called from die().
639  */
640 void generic_disestablish_ppp(int dev_fd)
641 {
642     if (new_style_driver) {
643         close(ppp_fd);
644         ppp_fd = -1;
645         if (demand) {
646             modify_flags(ppp_dev_fd, 0, SC_LOOP_TRAFFIC);
647             looped = 1;
648         } else if (!doing_multilink && ppp_dev_fd >= 0) {
649             close(ppp_dev_fd);
650             remove_fd(ppp_dev_fd);
651             ppp_dev_fd = -1;
652         }
653     } else {
654         /* old-style driver */
655         if (demand)
656             set_ppp_fd(slave_fd);
657         else
658             ppp_dev_fd = -1;
659     }
660 }
661
662 /*
663  * make_ppp_unit - make a new ppp unit for ppp_dev_fd.
664  * Assumes new_style_driver.
665  */
666 static int make_ppp_unit(void)
667 {
668         int x, flags;
669
670         if (ppp_dev_fd >= 0) {
671                 dbglog("in make_ppp_unit, already had /dev/ppp open?");
672                 close(ppp_dev_fd);
673         }
674         ppp_dev_fd = open("/dev/ppp", O_RDWR);
675         if (ppp_dev_fd < 0)
676                 fatal("Couldn't open /dev/ppp: %m");
677         flags = fcntl(ppp_dev_fd, F_GETFL);
678         if (flags == -1
679             || fcntl(ppp_dev_fd, F_SETFL, flags | O_NONBLOCK) == -1)
680                 warn("Couldn't set /dev/ppp to nonblock: %m");
681
682         ifunit = req_unit;
683         x = ioctl(ppp_dev_fd, PPPIOCNEWUNIT, &ifunit);
684         if (x < 0 && req_unit >= 0 && errno == EEXIST) {
685                 warn("Couldn't allocate PPP unit %d as it is already in use", req_unit);
686                 ifunit = -1;
687                 x = ioctl(ppp_dev_fd, PPPIOCNEWUNIT, &ifunit);
688         }
689         if (x < 0)
690                 error("Couldn't create new ppp unit: %m");
691
692         if (x == 0 && req_ifname[0] != '\0') {
693                 struct ifreq ifr;
694                 char t[MAXIFNAMELEN];
695                 memset(&ifr, 0, sizeof(struct ifreq));
696                 slprintf(t, sizeof(t), "%s%d", PPP_DRV_NAME, ifunit);
697                 strlcpy(ifr.ifr_name, t, IF_NAMESIZE);
698                 strlcpy(ifr.ifr_newname, req_ifname, IF_NAMESIZE);
699                 x = ioctl(sock_fd, SIOCSIFNAME, &ifr);
700                 if (x < 0)
701                     error("Couldn't rename interface %s to %s: %m", t, req_ifname);
702                 else
703                     info("Renamed interface %s to %s", t, req_ifname);
704         }
705
706         return x;
707 }
708
709 /*
710  * cfg_bundle - configure the existing bundle.
711  * Used in demand mode.
712  */
713 void cfg_bundle(int mrru, int mtru, int rssn, int tssn)
714 {
715         if (!new_style_driver)
716                 return;
717
718         /* set the mrru, mtu and flags */
719         if (ioctl(ppp_dev_fd, PPPIOCSMRRU, &mrru) < 0)
720                 error("Couldn't set MRRU: %m");
721
722         modify_flags(ppp_dev_fd, SC_MP_SHORTSEQ|SC_MP_XSHORTSEQ|SC_MULTILINK,
723                      ((rssn? SC_MP_SHORTSEQ: 0) | (tssn? SC_MP_XSHORTSEQ: 0)
724                       | (mrru? SC_MULTILINK: 0)));
725
726         /* connect up the channel */
727         if (ioctl(ppp_fd, PPPIOCCONNECT, &ifunit) < 0)
728                 fatal("Couldn't attach to PPP unit %d: %m", ifunit);
729         add_fd(ppp_dev_fd);
730 }
731
732 /*
733  * make_new_bundle - create a new PPP unit (i.e. a bundle)
734  * and connect our channel to it.  This should only get called
735  * if `multilink' was set at the time establish_ppp was called.
736  * In demand mode this uses our existing bundle instead of making
737  * a new one.
738  */
739 void make_new_bundle(int mrru, int mtru, int rssn, int tssn)
740 {
741         if (!new_style_driver)
742                 return;
743
744         /* make us a ppp unit */
745         if (make_ppp_unit() < 0)
746                 die(1);
747
748         /* set the mrru and flags */
749         cfg_bundle(mrru, mtru, rssn, tssn);
750 }
751
752 /*
753  * bundle_attach - attach our link to a given PPP unit.
754  * We assume the unit is controlled by another pppd.
755  */
756 int bundle_attach(int ifnum)
757 {
758         int master_fd;
759
760         if (!new_style_driver)
761                 return -1;
762
763         master_fd = open("/dev/ppp", O_RDWR);
764         if (master_fd < 0)
765                 fatal("Couldn't open /dev/ppp: %m");
766         if (ioctl(master_fd, PPPIOCATTACH, &ifnum) < 0) {
767                 if (errno == ENXIO) {
768                         close(master_fd);
769                         return 0;       /* doesn't still exist */
770                 }
771                 fatal("Couldn't attach to interface unit %d: %m\n", ifnum);
772         }
773         if (ioctl(ppp_fd, PPPIOCCONNECT, &ifnum) < 0)
774                 fatal("Couldn't connect to interface unit %d: %m", ifnum);
775         modify_flags(master_fd, 0, SC_MULTILINK);
776         close(master_fd);
777
778         ifunit = ifnum;
779         return 1;
780 }
781
782 /*
783  * destroy_bundle - tell the driver to destroy our bundle.
784  */
785 void destroy_bundle(void)
786 {
787         if (ppp_dev_fd >= 0) {
788                 close(ppp_dev_fd);
789                 remove_fd(ppp_dev_fd);
790                 ppp_dev_fd = -1;
791         }
792 }
793
794 /********************************************************************
795  *
796  * clean_check - Fetch the flags for the device and generate
797  * appropriate error messages.
798  */
799 void clean_check(void)
800 {
801     int x;
802     char *s;
803
804     if (still_ppp()) {
805         if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &x) == 0) {
806             s = NULL;
807             switch (~x & (SC_RCV_B7_0|SC_RCV_B7_1|SC_RCV_EVNP|SC_RCV_ODDP)) {
808             case SC_RCV_B7_0:
809                 s = "all had bit 7 set to 1";
810                 break;
811
812             case SC_RCV_B7_1:
813                 s = "all had bit 7 set to 0";
814                 break;
815
816             case SC_RCV_EVNP:
817                 s = "all had odd parity";
818                 break;
819
820             case SC_RCV_ODDP:
821                 s = "all had even parity";
822                 break;
823             }
824
825             if (s != NULL) {
826                 warn("Receive serial link is not 8-bit clean:");
827                 warn("Problem: %s", s);
828             }
829         }
830     }
831 }
832
833
834 /*
835  * List of valid speeds.
836  */
837
838 struct speed {
839     int speed_int, speed_val;
840 } speeds[] = {
841 #ifdef B50
842     { 50, B50 },
843 #endif
844 #ifdef B75
845     { 75, B75 },
846 #endif
847 #ifdef B110
848     { 110, B110 },
849 #endif
850 #ifdef B134
851     { 134, B134 },
852 #endif
853 #ifdef B150
854     { 150, B150 },
855 #endif
856 #ifdef B200
857     { 200, B200 },
858 #endif
859 #ifdef B300
860     { 300, B300 },
861 #endif
862 #ifdef B600
863     { 600, B600 },
864 #endif
865 #ifdef B1200
866     { 1200, B1200 },
867 #endif
868 #ifdef B1800
869     { 1800, B1800 },
870 #endif
871 #ifdef B2000
872     { 2000, B2000 },
873 #endif
874 #ifdef B2400
875     { 2400, B2400 },
876 #endif
877 #ifdef B3600
878     { 3600, B3600 },
879 #endif
880 #ifdef B4800
881     { 4800, B4800 },
882 #endif
883 #ifdef B7200
884     { 7200, B7200 },
885 #endif
886 #ifdef B9600
887     { 9600, B9600 },
888 #endif
889 #ifdef B19200
890     { 19200, B19200 },
891 #endif
892 #ifdef B38400
893     { 38400, B38400 },
894 #endif
895 #ifdef B57600
896     { 57600, B57600 },
897 #endif
898 #ifdef B76800
899     { 76800, B76800 },
900 #endif
901 #ifdef B115200
902     { 115200, B115200 },
903 #endif
904 #ifdef EXTA
905     { 19200, EXTA },
906 #endif
907 #ifdef EXTB
908     { 38400, EXTB },
909 #endif
910 #ifdef B230400
911     { 230400, B230400 },
912 #endif
913 #ifdef B460800
914     { 460800, B460800 },
915 #endif
916 #ifdef B500000
917     { 500000, B500000 },
918 #endif
919 #ifdef B576000
920     { 576000, B576000 },
921 #endif
922 #ifdef B921600
923     { 921600, B921600 },
924 #endif
925 #ifdef B1000000
926     { 1000000, B1000000 },
927 #endif
928 #ifdef B1152000
929     { 1152000, B1152000 },
930 #endif
931 #ifdef B1500000
932     { 1500000, B1500000 },
933 #endif
934 #ifdef B2000000
935     { 2000000, B2000000 },
936 #endif
937 #ifdef B2500000
938     { 2500000, B2500000 },
939 #endif
940 #ifdef B3000000
941     { 3000000, B3000000 },
942 #endif
943 #ifdef B3500000
944     { 3500000, B3500000 },
945 #endif
946 #ifdef B4000000
947     { 4000000, B4000000 },
948 #endif
949     { 0, 0 }
950 };
951
952 /********************************************************************
953  *
954  * Translate from bits/second to a speed_t.
955  */
956
957 static int translate_speed (int bps)
958 {
959     struct speed *speedp;
960
961     if (bps != 0) {
962         for (speedp = speeds; speedp->speed_int; speedp++) {
963             if (bps == speedp->speed_int)
964                 return speedp->speed_val;
965         }
966     }
967     return 0;
968 }
969
970 /********************************************************************
971  *
972  * Translate from a speed_t to bits/second.
973  */
974
975 static int baud_rate_of (int speed)
976 {
977     struct speed *speedp;
978
979     if (speed != 0) {
980         for (speedp = speeds; speedp->speed_int; speedp++) {
981             if (speed == speedp->speed_val)
982                 return speedp->speed_int;
983         }
984     }
985     return 0;
986 }
987
988 /********************************************************************
989  *
990  * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
991  * at the requested speed, etc.  If `local' is true, set CLOCAL
992  * regardless of whether the modem option was specified.
993  */
994
995 void set_up_tty(int tty_fd, int local)
996 {
997     int speed;
998     struct termios tios;
999
1000     setdtr(tty_fd, 1);
1001     if (tcgetattr(tty_fd, &tios) < 0) {
1002         if (!ok_error(errno))
1003             fatal("tcgetattr: %m (line %d)", __LINE__);
1004         return;
1005     }
1006
1007     if (!restore_term)
1008         inittermios = tios;
1009
1010     tios.c_cflag     &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
1011     tios.c_cflag     |= CS8 | CREAD | HUPCL;
1012
1013     tios.c_iflag      = IGNBRK | IGNPAR;
1014     tios.c_oflag      = 0;
1015     tios.c_lflag      = 0;
1016     tios.c_cc[VMIN]   = 1;
1017     tios.c_cc[VTIME]  = 0;
1018
1019     if (local || !modem)
1020         tios.c_cflag ^= (CLOCAL | HUPCL);
1021
1022     switch (crtscts) {
1023     case 1:
1024         tios.c_cflag |= CRTSCTS;
1025         break;
1026
1027     case -2:
1028         tios.c_iflag     |= IXON | IXOFF;
1029         tios.c_cc[VSTOP]  = 0x13;       /* DC3 = XOFF = ^S */
1030         tios.c_cc[VSTART] = 0x11;       /* DC1 = XON  = ^Q */
1031         break;
1032
1033     case -1:
1034         tios.c_cflag &= ~CRTSCTS;
1035         break;
1036
1037     default:
1038         break;
1039     }
1040
1041     if (stop_bits >= 2)
1042         tios.c_cflag |= CSTOPB;
1043
1044     if (inspeed) {
1045         speed = translate_speed(inspeed);
1046         if (speed) {
1047             cfsetospeed (&tios, speed);
1048             cfsetispeed (&tios, speed);
1049             speed = cfgetospeed(&tios);
1050         }
1051         baud_rate = baud_rate_of(speed);
1052     }
1053     else {
1054         speed = cfgetospeed(&tios);
1055         baud_rate = baud_rate_of(speed);
1056     }
1057
1058     while (tcsetattr(tty_fd, TCSAFLUSH, &tios) < 0 && !ok_error(errno))
1059         if (errno != EINTR)
1060             fatal("tcsetattr: %m (line %d)", __LINE__);
1061
1062 /* Most Linux architectures and drivers support arbitrary baud rate values via BOTHER */
1063 #ifdef TCGETS2
1064     if (!baud_rate) {
1065         struct termios2 tios2;
1066         if (ioctl(tty_fd, TCGETS2, &tios2) == 0) {
1067             if (inspeed) {
1068                 tios2.c_cflag &= ~CBAUD;
1069                 tios2.c_cflag |= BOTHER;
1070                 tios2.c_ispeed = inspeed;
1071                 tios2.c_ospeed = inspeed;
1072 #ifdef TCSETS2
1073                 if (ioctl(tty_fd, TCSETS2, &tios2) == 0)
1074                     baud_rate = inspeed;
1075 #endif
1076             } else {
1077                 if ((tios2.c_cflag & CBAUD) == BOTHER && tios2.c_ospeed)
1078                     baud_rate = tios2.c_ospeed;
1079             }
1080         }
1081     }
1082 #endif
1083
1084 /*
1085  * We can't proceed if the serial port baud rate is unknown,
1086  * since that implies that the serial port is disabled.
1087  */
1088     if (!baud_rate) {
1089         if (inspeed)
1090             fatal("speed %d not supported", inspeed);
1091         else
1092             fatal("Baud rate for %s is 0; need explicit baud rate", devnam);
1093     }
1094
1095     restore_term = 1;
1096 }
1097
1098 /********************************************************************
1099  *
1100  * setdtr - control the DTR line on the serial port.
1101  * This is called from die(), so it shouldn't call die().
1102  */
1103
1104 void setdtr (int tty_fd, int on)
1105 {
1106     int modembits = TIOCM_DTR;
1107
1108     ioctl(tty_fd, (on ? TIOCMBIS : TIOCMBIC), &modembits);
1109 }
1110
1111 /********************************************************************
1112  *
1113  * restore_tty - restore the terminal to the saved settings.
1114  */
1115
1116 void restore_tty (int tty_fd)
1117 {
1118     if (restore_term) {
1119         restore_term = 0;
1120 /*
1121  * Turn off echoing, because otherwise we can get into
1122  * a loop with the tty and the modem echoing to each other.
1123  * We presume we are the sole user of this tty device, so
1124  * when we close it, it will revert to its defaults anyway.
1125  */
1126         if (!default_device)
1127             inittermios.c_lflag &= ~(ECHO | ECHONL);
1128
1129         if (tcsetattr(tty_fd, TCSAFLUSH, &inittermios) < 0) {
1130             if (! ok_error (errno))
1131                 warn("tcsetattr: %m (line %d)", __LINE__);
1132         }
1133     }
1134 }
1135
1136 /********************************************************************
1137  *
1138  * output - Output PPP packet.
1139  */
1140
1141 void output (int unit, unsigned char *p, int len)
1142 {
1143     int fd = ppp_fd;
1144     int proto;
1145
1146     dump_packet("sent", p, len);
1147     if (snoop_send_hook) snoop_send_hook(p, len);
1148
1149     if (len < PPP_HDRLEN)
1150         return;
1151     if (new_style_driver) {
1152         p += 2;
1153         len -= 2;
1154         proto = (p[0] << 8) + p[1];
1155         if (ppp_dev_fd >= 0 && !(proto >= 0xc000 || proto == PPP_CCPFRAG))
1156             fd = ppp_dev_fd;
1157     }
1158     if (write(fd, p, len) < 0) {
1159         if (errno == EWOULDBLOCK || errno == EAGAIN || errno == ENOBUFS
1160             || errno == ENXIO || errno == EIO || errno == EINTR)
1161             warn("write: warning: %m (%d)", errno);
1162         else
1163             error("write: %m (%d)", errno);
1164     }
1165 }
1166
1167 /********************************************************************
1168  *
1169  * wait_input - wait until there is data available,
1170  * for the length of time specified by *timo (indefinite
1171  * if timo is NULL).
1172  */
1173
1174 void wait_input(struct timeval *timo)
1175 {
1176     fd_set ready, exc;
1177     int n;
1178
1179     ready = in_fds;
1180     exc = in_fds;
1181     n = select(max_in_fd + 1, &ready, NULL, &exc, timo);
1182     if (n < 0 && errno != EINTR)
1183         fatal("select: %m");
1184 }
1185
1186 /*
1187  * add_fd - add an fd to the set that wait_input waits for.
1188  */
1189 void add_fd(int fd)
1190 {
1191     if (fd >= FD_SETSIZE)
1192         fatal("internal error: file descriptor too large (%d)", fd);
1193     FD_SET(fd, &in_fds);
1194     if (fd > max_in_fd)
1195         max_in_fd = fd;
1196 }
1197
1198 /*
1199  * remove_fd - remove an fd from the set that wait_input waits for.
1200  */
1201 void remove_fd(int fd)
1202 {
1203     FD_CLR(fd, &in_fds);
1204 }
1205
1206
1207 /********************************************************************
1208  *
1209  * read_packet - get a PPP packet from the serial device.
1210  */
1211
1212 int read_packet (unsigned char *buf)
1213 {
1214     int len, nr;
1215
1216     len = PPP_MRU + PPP_HDRLEN;
1217     if (new_style_driver) {
1218         *buf++ = PPP_ALLSTATIONS;
1219         *buf++ = PPP_UI;
1220         len -= 2;
1221     }
1222     nr = -1;
1223     if (ppp_fd >= 0) {
1224         nr = read(ppp_fd, buf, len);
1225         if (nr < 0 && errno != EWOULDBLOCK && errno != EAGAIN
1226             && errno != EIO && errno != EINTR)
1227             error("read: %m");
1228         if (nr < 0 && errno == ENXIO)
1229             return 0;
1230     }
1231     if (nr < 0 && new_style_driver && ppp_dev_fd >= 0 && !bundle_eof) {
1232         /* N.B. we read ppp_fd first since LCP packets come in there. */
1233         nr = read(ppp_dev_fd, buf, len);
1234         if (nr < 0 && errno != EWOULDBLOCK && errno != EAGAIN
1235             && errno != EIO && errno != EINTR)
1236             error("read /dev/ppp: %m");
1237         if (nr < 0 && errno == ENXIO)
1238             nr = 0;
1239         if (nr == 0 && doing_multilink) {
1240             remove_fd(ppp_dev_fd);
1241             bundle_eof = 1;
1242         }
1243     }
1244     if (new_style_driver && ppp_fd < 0 && ppp_dev_fd < 0)
1245         nr = 0;
1246     return (new_style_driver && nr > 0)? nr+2: nr;
1247 }
1248
1249 /********************************************************************
1250  *
1251  * get_loop_output - get outgoing packets from the ppp device,
1252  * and detect when we want to bring the real link up.
1253  * Return value is 1 if we need to bring up the link, 0 otherwise.
1254  */
1255 int
1256 get_loop_output(void)
1257 {
1258     int rv = 0;
1259     int n;
1260
1261     if (new_style_driver) {
1262         while ((n = read_packet(inpacket_buf)) > 0)
1263             if (loop_frame(inpacket_buf, n))
1264                 rv = 1;
1265         return rv;
1266     }
1267
1268     while ((n = read(master_fd, inbuf, sizeof(inbuf))) > 0)
1269         if (loop_chars(inbuf, n))
1270             rv = 1;
1271
1272     if (n == 0)
1273         fatal("eof on loopback");
1274
1275     if (errno != EWOULDBLOCK && errno != EAGAIN)
1276         fatal("read from loopback: %m(%d)", errno);
1277
1278     return rv;
1279 }
1280
1281 /*
1282  * netif_set_mtu - set the MTU on the PPP network interface.
1283  */
1284 void
1285 netif_set_mtu(int unit, int mtu)
1286 {
1287     struct ifreq ifr;
1288
1289     memset (&ifr, '\0', sizeof (ifr));
1290     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
1291     ifr.ifr_mtu = mtu;
1292
1293     if (ifunit >= 0 && ioctl(sock_fd, SIOCSIFMTU, (caddr_t) &ifr) < 0)
1294         error("ioctl(SIOCSIFMTU): %m (line %d)", __LINE__);
1295 }
1296
1297 /*
1298  * netif_get_mtu - get the MTU on the PPP network interface.
1299  */
1300 int
1301 netif_get_mtu(int unit)
1302 {
1303     struct ifreq ifr;
1304
1305     memset (&ifr, '\0', sizeof (ifr));
1306     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
1307
1308     if (ifunit >= 0 && ioctl(sock_fd, SIOCGIFMTU, (caddr_t) &ifr) < 0) {
1309         error("ioctl(SIOCGIFMTU): %m (line %d)", __LINE__);
1310         return 0;
1311     }
1312     return ifr.ifr_mtu;
1313 }
1314
1315 /********************************************************************
1316  *
1317  * tty_send_config - configure the transmit characteristics of
1318  * the ppp interface.
1319  */
1320
1321 void tty_send_config(int mtu, u_int32_t asyncmap, int pcomp, int accomp)
1322 {
1323         int x;
1324
1325         if (!still_ppp())
1326                 return;
1327         link_mtu = mtu;
1328         if (ioctl(ppp_fd, PPPIOCSASYNCMAP, (caddr_t) &asyncmap) < 0) {
1329                 if (errno != EIO && errno != ENOTTY)
1330                         error("Couldn't set transmit async character map: %m");
1331                 ++error_count;
1332                 return;
1333         }
1334
1335         x = (pcomp? SC_COMP_PROT: 0) | (accomp? SC_COMP_AC: 0)
1336             | (sync_serial? SC_SYNC: 0);
1337         modify_flags(ppp_fd, SC_COMP_PROT|SC_COMP_AC|SC_SYNC, x);
1338 }
1339
1340 /********************************************************************
1341  *
1342  * tty_set_xaccm - set the extended transmit ACCM for the interface.
1343  */
1344
1345 void tty_set_xaccm (ext_accm accm)
1346 {
1347     if (!still_ppp())
1348         return;
1349     if (ioctl(ppp_fd, PPPIOCSXASYNCMAP, accm) < 0 && errno != ENOTTY) {
1350         if ( ! ok_error (errno))
1351             warn("ioctl(set extended ACCM): %m (line %d)", __LINE__);
1352     }
1353 }
1354
1355 /********************************************************************
1356  *
1357  * tty_recv_config - configure the receive-side characteristics of
1358  * the ppp interface.
1359  */
1360
1361 void tty_recv_config(int mru, u_int32_t asyncmap, int pcomp, int accomp)
1362 {
1363 /*
1364  * If we were called because the link has gone down then there is nothing
1365  * which may be done. Just return without incident.
1366  */
1367         if (!still_ppp())
1368                 return;
1369 /*
1370  * Set the receiver parameters
1371  */
1372         if (ioctl(ppp_fd, PPPIOCSMRU, (caddr_t) &mru) < 0) {
1373                 if (errno != EIO && errno != ENOTTY)
1374                         error("Couldn't set channel receive MRU: %m");
1375         }
1376         if (new_style_driver && ppp_dev_fd >= 0
1377             && ioctl(ppp_dev_fd, PPPIOCSMRU, (caddr_t) &mru) < 0)
1378                 error("Couldn't set MRU in generic PPP layer: %m");
1379
1380         if (ioctl(ppp_fd, PPPIOCSRASYNCMAP, (caddr_t) &asyncmap) < 0) {
1381                 if (errno != EIO && errno != ENOTTY)
1382                         error("Couldn't set channel receive asyncmap: %m");
1383         }
1384 }
1385
1386 /********************************************************************
1387  *
1388  * ccp_test - ask kernel whether a given compression method
1389  * is acceptable for use.
1390  */
1391
1392 int
1393 ccp_test(int unit, u_char *opt_ptr, int opt_len, int for_transmit)
1394 {
1395     struct ppp_option_data data;
1396
1397     memset (&data, '\0', sizeof (data));
1398     data.ptr      = opt_ptr;
1399     data.length   = opt_len;
1400     data.transmit = for_transmit;
1401
1402     if (ioctl(ppp_dev_fd, PPPIOCSCOMPRESS, (caddr_t) &data) >= 0)
1403         return 1;
1404
1405     return (errno == ENOBUFS)? 0: -1;
1406 }
1407
1408 /********************************************************************
1409  *
1410  * ccp_flags_set - inform kernel about the current state of CCP.
1411  */
1412
1413 void ccp_flags_set (int unit, int isopen, int isup)
1414 {
1415         int x;
1416
1417         x = (isopen? SC_CCP_OPEN: 0) | (isup? SC_CCP_UP: 0);
1418         if (still_ppp() && ppp_dev_fd >= 0)
1419                 modify_flags(ppp_dev_fd, SC_CCP_OPEN|SC_CCP_UP, x);
1420 }
1421
1422 #ifdef PPP_FILTER
1423 /*
1424  * set_filters - set the active and pass filters in the kernel driver.
1425  */
1426 int set_filters(struct bpf_program *pass, struct bpf_program *active)
1427 {
1428         struct sock_fprog fp;
1429
1430         fp.len = pass->bf_len;
1431         fp.filter = (struct sock_filter *) pass->bf_insns;
1432         if (ioctl(ppp_dev_fd, PPPIOCSPASS, &fp) < 0) {
1433                 if (errno == ENOTTY)
1434                         warn("kernel does not support PPP filtering");
1435                 else
1436                         error("Couldn't set pass-filter in kernel: %m");
1437                 return 0;
1438         }
1439         fp.len = active->bf_len;
1440         fp.filter = (struct sock_filter *) active->bf_insns;
1441         if (ioctl(ppp_dev_fd, PPPIOCSACTIVE, &fp) < 0) {
1442                 error("Couldn't set active-filter in kernel: %m");
1443                 return 0;
1444         }
1445         return 1;
1446 }
1447 #endif /* PPP_FILTER */
1448
1449 /********************************************************************
1450  *
1451  * get_idle_time - return how long the link has been idle.
1452  */
1453 int
1454 get_idle_time(int u, struct ppp_idle *ip)
1455 {
1456     return ioctl(ppp_dev_fd, PPPIOCGIDLE, ip) >= 0;
1457 }
1458
1459 /********************************************************************
1460  *
1461  * get_ppp_stats - return statistics for the link.
1462  */
1463 int
1464 get_ppp_stats(int u, struct pppd_stats *stats)
1465 {
1466     struct ifpppstatsreq req;
1467
1468     memset (&req, 0, sizeof (req));
1469
1470     req.stats_ptr = (caddr_t) &req.stats;
1471     strlcpy(req.ifr__name, ifname, sizeof(req.ifr__name));
1472     if (ioctl(sock_fd, SIOCGPPPSTATS, &req) < 0) {
1473         error("Couldn't get PPP statistics: %m");
1474         return 0;
1475     }
1476     stats->bytes_in = req.stats.p.ppp_ibytes;
1477     stats->bytes_out = req.stats.p.ppp_obytes;
1478     stats->pkts_in = req.stats.p.ppp_ipackets;
1479     stats->pkts_out = req.stats.p.ppp_opackets;
1480     return 1;
1481 }
1482
1483 /********************************************************************
1484  *
1485  * ccp_fatal_error - returns 1 if decompression was disabled as a
1486  * result of an error detected after decompression of a packet,
1487  * 0 otherwise.  This is necessary because of patent nonsense.
1488  */
1489
1490 int ccp_fatal_error (int unit)
1491 {
1492         int flags;
1493
1494         if (ioctl(ppp_dev_fd, PPPIOCGFLAGS, &flags) < 0) {
1495                 error("Couldn't read compression error flags: %m");
1496                 flags = 0;
1497         }
1498         return flags & SC_DC_FERROR;
1499 }
1500
1501 /********************************************************************
1502  *
1503  * path_to_procfs - find the path to the proc file system mount point
1504  */
1505 static char proc_path[MAXPATHLEN];
1506 static int proc_path_len;
1507
1508 static char *path_to_procfs(const char *tail)
1509 {
1510     struct mntent *mntent;
1511     FILE *fp;
1512
1513     if (proc_path_len == 0) {
1514         /* Default the mount location of /proc */
1515         strlcpy (proc_path, "/proc", sizeof(proc_path));
1516         proc_path_len = 5;
1517         fp = fopen(MOUNTED, "r");
1518         if (fp != NULL) {
1519             while ((mntent = getmntent(fp)) != NULL) {
1520                 if (strcmp(mntent->mnt_type, MNTTYPE_IGNORE) == 0)
1521                     continue;
1522                 if (strcmp(mntent->mnt_type, "proc") == 0) {
1523                     strlcpy(proc_path, mntent->mnt_dir, sizeof(proc_path));
1524                     proc_path_len = strlen(proc_path);
1525                     break;
1526                 }
1527             }
1528             fclose (fp);
1529         }
1530     }
1531
1532     strlcpy(proc_path + proc_path_len, tail,
1533             sizeof(proc_path) - proc_path_len);
1534     return proc_path;
1535 }
1536
1537 /*
1538  * /proc/net/route parsing stuff.
1539  */
1540 #define ROUTE_MAX_COLS  12
1541 FILE *route_fd = (FILE *) 0;
1542 static char route_buffer[512];
1543 static int route_dev_col, route_dest_col, route_gw_col;
1544 static int route_flags_col, route_metric_col, route_mask_col;
1545 static int route_num_cols;
1546
1547 static int open_route_table (void);
1548 static void close_route_table (void);
1549 static int read_route_table (struct rtentry *rt);
1550
1551 /********************************************************************
1552  *
1553  * close_route_table - close the interface to the route table
1554  */
1555
1556 static void close_route_table (void)
1557 {
1558     if (route_fd != (FILE *) 0) {
1559         fclose (route_fd);
1560         route_fd = (FILE *) 0;
1561     }
1562 }
1563
1564 /********************************************************************
1565  *
1566  * open_route_table - open the interface to the route table
1567  */
1568 static char route_delims[] = " \t\n";
1569
1570 static int open_route_table (void)
1571 {
1572     char *path;
1573
1574     close_route_table();
1575
1576     path = path_to_procfs("/net/route");
1577     route_fd = fopen (path, "r");
1578     if (route_fd == NULL) {
1579         error("can't open routing table %s: %m", path);
1580         return 0;
1581     }
1582
1583     route_dev_col = 0;          /* default to usual columns */
1584     route_dest_col = 1;
1585     route_gw_col = 2;
1586     route_flags_col = 3;
1587     route_metric_col = 6;
1588     route_mask_col = 7;
1589     route_num_cols = 8;
1590
1591     /* parse header line */
1592     if (fgets(route_buffer, sizeof(route_buffer), route_fd) != 0) {
1593         char *p = route_buffer, *q;
1594         int col;
1595         for (col = 0; col < ROUTE_MAX_COLS; ++col) {
1596             int used = 1;
1597             if ((q = strtok(p, route_delims)) == 0)
1598                 break;
1599             if (strcasecmp(q, "iface") == 0)
1600                 route_dev_col = col;
1601             else if (strcasecmp(q, "destination") == 0)
1602                 route_dest_col = col;
1603             else if (strcasecmp(q, "gateway") == 0)
1604                 route_gw_col = col;
1605             else if (strcasecmp(q, "flags") == 0)
1606                 route_flags_col = col;
1607             else if (strcasecmp(q, "mask") == 0)
1608                 route_mask_col = col;
1609             else
1610                 used = 0;
1611             if (used && col >= route_num_cols)
1612                 route_num_cols = col + 1;
1613             p = NULL;
1614         }
1615     }
1616
1617     return 1;
1618 }
1619
1620 /********************************************************************
1621  *
1622  * read_route_table - read the next entry from the route table
1623  */
1624
1625 static int read_route_table(struct rtentry *rt)
1626 {
1627     char *cols[ROUTE_MAX_COLS], *p;
1628     int col;
1629
1630     memset (rt, '\0', sizeof (struct rtentry));
1631
1632     if (fgets (route_buffer, sizeof (route_buffer), route_fd) == (char *) 0)
1633         return 0;
1634
1635     p = route_buffer;
1636     for (col = 0; col < route_num_cols; ++col) {
1637         cols[col] = strtok(p, route_delims);
1638         if (cols[col] == NULL)
1639             return 0;           /* didn't get enough columns */
1640         p = NULL;
1641     }
1642
1643     SET_SA_FAMILY (rt->rt_dst,     AF_INET);
1644     SET_SA_FAMILY (rt->rt_gateway, AF_INET);
1645
1646     SIN_ADDR(rt->rt_dst) = strtoul(cols[route_dest_col], NULL, 16);
1647     SIN_ADDR(rt->rt_gateway) = strtoul(cols[route_gw_col], NULL, 16);
1648     SIN_ADDR(rt->rt_genmask) = strtoul(cols[route_mask_col], NULL, 16);
1649
1650     rt->rt_flags = (short) strtoul(cols[route_flags_col], NULL, 16);
1651     rt->rt_metric = (short) strtoul(cols[route_metric_col], NULL, 10);
1652     rt->rt_dev   = cols[route_dev_col];
1653
1654     return 1;
1655 }
1656
1657 /********************************************************************
1658  *
1659  * defaultroute_exists - determine if there is a default route
1660  * with the given metric (or negative for any)
1661  */
1662
1663 static int defaultroute_exists (struct rtentry *rt, int metric)
1664 {
1665     int result = 0;
1666
1667     if (!open_route_table())
1668         return 0;
1669
1670     while (read_route_table(rt) != 0) {
1671         if ((rt->rt_flags & RTF_UP) == 0)
1672             continue;
1673
1674         if (kernel_version > KVERSION(2,1,0) && SIN_ADDR(rt->rt_genmask) != 0)
1675             continue;
1676         if (SIN_ADDR(rt->rt_dst) == 0L && (metric < 0
1677                                            || rt->rt_metric == metric)) {
1678             result = 1;
1679             break;
1680         }
1681     }
1682
1683     close_route_table();
1684     return result;
1685 }
1686
1687 /*
1688  * have_route_to - determine if the system has any route to
1689  * a given IP address.  `addr' is in network byte order.
1690  * Return value is 1 if yes, 0 if no, -1 if don't know.
1691  * For demand mode to work properly, we have to ignore routes
1692  * through our own interface.
1693  */
1694 int have_route_to(u_int32_t addr)
1695 {
1696     struct rtentry rt;
1697     int result = 0;
1698
1699     if (!open_route_table())
1700         return -1;              /* don't know */
1701
1702     while (read_route_table(&rt)) {
1703         if ((rt.rt_flags & RTF_UP) == 0 || strcmp(rt.rt_dev, ifname) == 0)
1704             continue;
1705         if ((addr & SIN_ADDR(rt.rt_genmask)) == SIN_ADDR(rt.rt_dst)) {
1706             result = 1;
1707             break;
1708         }
1709     }
1710
1711     close_route_table();
1712     return result;
1713 }
1714
1715 /********************************************************************
1716  *
1717  * sifdefaultroute - assign a default route through the address given.
1718  *
1719  * If the global default_rt_repl_rest flag is set, then this function
1720  * already replaced the original system defaultroute with some other
1721  * route and it should just replace the current defaultroute with
1722  * another one, without saving the current route. Use: demand mode,
1723  * when pppd sets first a defaultroute it it's temporary ppp0 addresses
1724  * and then changes the temporary addresses to the addresses for the real
1725  * ppp connection when it has come up.
1726  */
1727
1728 int sifdefaultroute (int unit, u_int32_t ouraddr, u_int32_t gateway, bool replace)
1729 {
1730     struct rtentry rt, tmp_rt;
1731     struct rtentry *del_rt = NULL;
1732
1733     if (default_rt_repl_rest) {
1734         /* We have already replaced the original defaultroute, if we
1735          * are called again, we will delete the current default route
1736          * and set the new default route in this function.
1737          * - this is normally only the case the doing demand: */
1738         if (defaultroute_exists(&tmp_rt, -1))
1739             del_rt = &tmp_rt;
1740     } else if (defaultroute_exists(&old_def_rt, -1           ) &&
1741                             strcmp( old_def_rt.rt_dev, ifname) != 0) {
1742         /*
1743          * We did not yet replace an existing default route, let's
1744          * check if we should save and replace a default route:
1745          */
1746         u_int32_t old_gateway = SIN_ADDR(old_def_rt.rt_gateway);
1747
1748         if (old_gateway != gateway) {
1749             if (!replace) {
1750                 error("not replacing default route to %s [%I]",
1751                         old_def_rt.rt_dev, old_gateway);
1752                 return 0;
1753             } else {
1754                 /* we need to copy rt_dev because we need it permanent too: */
1755                 char * tmp_dev = malloc(strlen(old_def_rt.rt_dev)+1);
1756                 strcpy(tmp_dev, old_def_rt.rt_dev);
1757                 old_def_rt.rt_dev = tmp_dev;
1758
1759                 notice("replacing old default route to %s [%I]",
1760                         old_def_rt.rt_dev, old_gateway);
1761                 default_rt_repl_rest = 1;
1762                 del_rt = &old_def_rt;
1763             }
1764         }
1765     }
1766
1767     memset (&rt, 0, sizeof (rt));
1768     SET_SA_FAMILY (rt.rt_dst, AF_INET);
1769
1770     rt.rt_dev = ifname;
1771     rt.rt_metric = dfl_route_metric + 1; /* +1 for binary compatibility */
1772
1773     if (kernel_version > KVERSION(2,1,0)) {
1774         SET_SA_FAMILY (rt.rt_genmask, AF_INET);
1775         SIN_ADDR(rt.rt_genmask) = 0L;
1776     }
1777
1778     rt.rt_flags = RTF_UP;
1779     if (ioctl(sock_fd, SIOCADDRT, &rt) < 0) {
1780         if ( ! ok_error ( errno ))
1781             error("default route ioctl(SIOCADDRT): %m");
1782         return 0;
1783     }
1784     if (default_rt_repl_rest && del_rt)
1785         if (ioctl(sock_fd, SIOCDELRT, del_rt) < 0) {
1786             if ( ! ok_error ( errno ))
1787                 error("del old default route ioctl(SIOCDELRT): %m(%d)", errno);
1788             return 0;
1789         }
1790
1791     have_default_route = 1;
1792     return 1;
1793 }
1794
1795 /********************************************************************
1796  *
1797  * cifdefaultroute - delete a default route through the address given.
1798  */
1799
1800 int cifdefaultroute (int unit, u_int32_t ouraddr, u_int32_t gateway)
1801 {
1802     struct rtentry rt;
1803
1804     have_default_route = 0;
1805
1806     memset (&rt, '\0', sizeof (rt));
1807     SET_SA_FAMILY (rt.rt_dst,     AF_INET);
1808     SET_SA_FAMILY (rt.rt_gateway, AF_INET);
1809
1810     rt.rt_dev = ifname;
1811
1812     rt.rt_dev = ifname;
1813     rt.rt_metric = dfl_route_metric + 1; /* +1 for binary compatibility */
1814
1815     if (kernel_version > KVERSION(2,1,0)) {
1816         SET_SA_FAMILY (rt.rt_genmask, AF_INET);
1817         SIN_ADDR(rt.rt_genmask) = 0L;
1818     }
1819
1820     rt.rt_flags = RTF_UP;
1821     if (ioctl(sock_fd, SIOCDELRT, &rt) < 0 && errno != ESRCH) {
1822         if (still_ppp()) {
1823             if ( ! ok_error ( errno ))
1824                 error("default route ioctl(SIOCDELRT): %m");
1825             return 0;
1826         }
1827     }
1828     if (default_rt_repl_rest) {
1829         notice("restoring old default route to %s [%I]",
1830                         old_def_rt.rt_dev, SIN_ADDR(old_def_rt.rt_gateway));
1831         if (ioctl(sock_fd, SIOCADDRT, &old_def_rt) < 0) {
1832             if ( ! ok_error ( errno ))
1833                 error("restore default route ioctl(SIOCADDRT): %m(%d)", errno);
1834             return 0;
1835         }
1836         default_rt_repl_rest = 0;
1837     }
1838
1839     return 1;
1840 }
1841
1842 #ifdef INET6
1843 /*
1844  * /proc/net/ipv6_route parsing stuff.
1845  */
1846 static int route_dest_plen_col;
1847 static int open_route6_table (void);
1848 static int read_route6_table (struct in6_rtmsg *rt);
1849
1850 /********************************************************************
1851  *
1852  * open_route6_table - open the interface to the route table
1853  */
1854 static int open_route6_table (void)
1855 {
1856     char *path;
1857
1858     close_route_table();
1859
1860     path = path_to_procfs("/net/ipv6_route");
1861     route_fd = fopen (path, "r");
1862     if (route_fd == NULL) {
1863         error("can't open routing table %s: %m", path);
1864         return 0;
1865     }
1866
1867     /* default to usual columns */
1868     route_dest_col = 0;
1869     route_dest_plen_col = 1;
1870     route_gw_col = 4;
1871     route_metric_col = 5;
1872     route_flags_col = 8;
1873     route_dev_col = 9;
1874     route_num_cols = 10;
1875
1876     return 1;
1877 }
1878
1879 /********************************************************************
1880  *
1881  * read_route6_table - read the next entry from the route table
1882  */
1883
1884 static void hex_to_in6_addr(struct in6_addr *addr, const char *s)
1885 {
1886     char hex8[9];
1887     unsigned i;
1888     uint32_t v;
1889
1890     hex8[8] = 0;
1891     for (i = 0; i < 4; i++) {
1892         memcpy(hex8, s + 8*i, 8);
1893         v = strtoul(hex8, NULL, 16);
1894         addr->s6_addr32[i] = v;
1895     }
1896 }
1897
1898 static int read_route6_table(struct in6_rtmsg *rt)
1899 {
1900     char *cols[ROUTE_MAX_COLS], *p;
1901     int col;
1902
1903     memset (rt, '\0', sizeof (struct in6_rtmsg));
1904
1905     if (fgets (route_buffer, sizeof (route_buffer), route_fd) == (char *) 0)
1906         return 0;
1907
1908     p = route_buffer;
1909     for (col = 0; col < route_num_cols; ++col) {
1910         cols[col] = strtok(p, route_delims);
1911         if (cols[col] == NULL)
1912             return 0;           /* didn't get enough columns */
1913         p = NULL;
1914     }
1915
1916     hex_to_in6_addr(&rt->rtmsg_dst, cols[route_dest_col]);
1917     rt->rtmsg_dst_len = strtoul(cols[route_dest_plen_col], NULL, 16);
1918     hex_to_in6_addr(&rt->rtmsg_gateway, cols[route_gw_col]);
1919
1920     rt->rtmsg_metric = strtoul(cols[route_metric_col], NULL, 16);
1921     rt->rtmsg_flags = strtoul(cols[route_flags_col], NULL, 16);
1922     rt->rtmsg_ifindex = if_nametoindex(cols[route_dev_col]);
1923
1924     return 1;
1925 }
1926
1927 /********************************************************************
1928  *
1929  * defaultroute6_exists - determine if there is a default route
1930  */
1931
1932 static int defaultroute6_exists (struct in6_rtmsg *rt, int metric)
1933 {
1934     int result = 0;
1935
1936     if (!open_route6_table())
1937         return 0;
1938
1939     while (read_route6_table(rt) != 0) {
1940         if ((rt->rtmsg_flags & RTF_UP) == 0)
1941             continue;
1942
1943         if (rt->rtmsg_dst_len != 0)
1944             continue;
1945         if (rt->rtmsg_dst.s6_addr32[0] == 0L
1946          && rt->rtmsg_dst.s6_addr32[1] == 0L
1947          && rt->rtmsg_dst.s6_addr32[2] == 0L
1948          && rt->rtmsg_dst.s6_addr32[3] == 0L
1949          && (metric < 0 || rt->rtmsg_metric == metric)) {
1950             result = 1;
1951             break;
1952         }
1953     }
1954
1955     close_route_table();
1956     return result;
1957 }
1958
1959 /********************************************************************
1960  *
1961  * sif6defaultroute - assign a default route through the address given.
1962  *
1963  * If the global default_rt_repl_rest flag is set, then this function
1964  * already replaced the original system defaultroute with some other
1965  * route and it should just replace the current defaultroute with
1966  * another one, without saving the current route. Use: demand mode,
1967  * when pppd sets first a defaultroute it it's temporary ppp0 addresses
1968  * and then changes the temporary addresses to the addresses for the real
1969  * ppp connection when it has come up.
1970  */
1971
1972 int sif6defaultroute (int unit, eui64_t ouraddr, eui64_t gateway)
1973 {
1974     struct in6_rtmsg rt;
1975     char buf[IF_NAMESIZE];
1976
1977     if (defaultroute6_exists(&rt, dfl_route_metric) &&
1978             rt.rtmsg_ifindex != if_nametoindex(ifname)) {
1979         if (rt.rtmsg_flags & RTF_GATEWAY)
1980             error("not replacing existing default route via gateway");
1981         else
1982             error("not replacing existing default route through %s",
1983                   if_indextoname(rt.rtmsg_ifindex, buf));
1984         return 0;
1985     }
1986
1987     memset (&rt, 0, sizeof (rt));
1988
1989     rt.rtmsg_ifindex = if_nametoindex(ifname);
1990     rt.rtmsg_metric = dfl_route_metric + 1; /* +1 for binary compatibility */
1991     rt.rtmsg_dst_len = 0;
1992
1993     rt.rtmsg_flags = RTF_UP;
1994     if (ioctl(sock6_fd, SIOCADDRT, &rt) < 0) {
1995         if ( ! ok_error ( errno ))
1996             error("default route ioctl(SIOCADDRT): %m");
1997         return 0;
1998     }
1999
2000     have_default_route6 = 1;
2001     return 1;
2002 }
2003
2004 /********************************************************************
2005  *
2006  * cif6defaultroute - delete a default route through the address given.
2007  */
2008
2009 int cif6defaultroute (int unit, eui64_t ouraddr, eui64_t gateway)
2010 {
2011     struct in6_rtmsg rt;
2012
2013     have_default_route6 = 0;
2014
2015     memset (&rt, '\0', sizeof (rt));
2016
2017     rt.rtmsg_ifindex = if_nametoindex(ifname);
2018     rt.rtmsg_metric = dfl_route_metric + 1; /* +1 for binary compatibility */
2019     rt.rtmsg_dst_len = 0;
2020
2021     rt.rtmsg_flags = RTF_UP;
2022     if (ioctl(sock6_fd, SIOCDELRT, &rt) < 0 && errno != ESRCH) {
2023         if (still_ppp()) {
2024             if ( ! ok_error ( errno ))
2025                 error("default route ioctl(SIOCDELRT): %m");
2026             return 0;
2027         }
2028     }
2029
2030     return 1;
2031 }
2032 #endif /* INET6 */
2033
2034 /********************************************************************
2035  *
2036  * sifproxyarp - Make a proxy ARP entry for the peer.
2037  */
2038
2039 int sifproxyarp (int unit, u_int32_t his_adr)
2040 {
2041     struct arpreq arpreq;
2042     char *forw_path;
2043
2044     if (has_proxy_arp == 0) {
2045         memset (&arpreq, '\0', sizeof(arpreq));
2046
2047         SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
2048         SIN_ADDR(arpreq.arp_pa) = his_adr;
2049         arpreq.arp_flags = ATF_PERM | ATF_PUBL;
2050 /*
2051  * Get the hardware address of an interface on the same subnet
2052  * as our local address.
2053  */
2054         if (!get_ether_addr(his_adr, &arpreq.arp_ha, proxy_arp_dev,
2055                             sizeof(proxy_arp_dev))) {
2056             error("Cannot determine ethernet address for proxy ARP");
2057             return 0;
2058         }
2059         strlcpy(arpreq.arp_dev, proxy_arp_dev, sizeof(arpreq.arp_dev));
2060
2061         if (ioctl(sock_fd, SIOCSARP, (caddr_t)&arpreq) < 0) {
2062             if ( ! ok_error ( errno ))
2063                 error("ioctl(SIOCSARP): %m");
2064             return 0;
2065         }
2066         proxy_arp_addr = his_adr;
2067         has_proxy_arp = 1;
2068
2069         if (tune_kernel) {
2070             forw_path = path_to_procfs("/sys/net/ipv4/ip_forward");
2071             if (forw_path != 0) {
2072                 int fd = open(forw_path, O_WRONLY);
2073                 if (fd >= 0) {
2074                     if (write(fd, "1", 1) != 1)
2075                         error("Couldn't enable IP forwarding: %m");
2076                     close(fd);
2077                 }
2078             }
2079         }
2080     }
2081
2082     return 1;
2083 }
2084
2085 /********************************************************************
2086  *
2087  * cifproxyarp - Delete the proxy ARP entry for the peer.
2088  */
2089
2090 int cifproxyarp (int unit, u_int32_t his_adr)
2091 {
2092     struct arpreq arpreq;
2093
2094     if (has_proxy_arp) {
2095         has_proxy_arp = 0;
2096         memset (&arpreq, '\0', sizeof(arpreq));
2097         SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
2098         SIN_ADDR(arpreq.arp_pa) = his_adr;
2099         arpreq.arp_flags = ATF_PERM | ATF_PUBL;
2100         strlcpy(arpreq.arp_dev, proxy_arp_dev, sizeof(arpreq.arp_dev));
2101
2102         if (ioctl(sock_fd, SIOCDARP, (caddr_t)&arpreq) < 0) {
2103             if ( ! ok_error ( errno ))
2104                 warn("ioctl(SIOCDARP): %m");
2105             return 0;
2106         }
2107     }
2108     return 1;
2109 }
2110
2111 /********************************************************************
2112  *
2113  * get_ether_addr - get the hardware address of an interface on the
2114  * the same subnet as ipaddr.
2115  */
2116
2117 static int get_ether_addr (u_int32_t ipaddr,
2118                            struct sockaddr *hwaddr,
2119                            char *name, int namelen)
2120 {
2121     struct ifreq *ifr, *ifend;
2122     u_int32_t ina, mask;
2123     char *aliasp;
2124     struct ifreq ifreq, bestifreq;
2125     struct ifconf ifc;
2126     struct ifreq ifs[MAX_IFS];
2127
2128     u_int32_t bestmask=0;
2129     int found_interface = 0;
2130
2131     ifc.ifc_len = sizeof(ifs);
2132     ifc.ifc_req = ifs;
2133     if (ioctl(sock_fd, SIOCGIFCONF, &ifc) < 0) {
2134         if ( ! ok_error ( errno ))
2135             error("ioctl(SIOCGIFCONF): %m (line %d)", __LINE__);
2136         return 0;
2137     }
2138
2139 /*
2140  * Scan through looking for an interface with an Internet
2141  * address on the same subnet as `ipaddr'.
2142  */
2143     ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
2144     for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
2145         if (ifr->ifr_addr.sa_family == AF_INET) {
2146             ina = SIN_ADDR(ifr->ifr_addr);
2147             strlcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
2148 /*
2149  * Check that the interface is up, and not point-to-point
2150  * nor loopback.
2151  */
2152             if (ioctl(sock_fd, SIOCGIFFLAGS, &ifreq) < 0)
2153                 continue;
2154
2155             if (((ifreq.ifr_flags ^ FLAGS_GOOD) & FLAGS_MASK) != 0)
2156                 continue;
2157 /*
2158  * Get its netmask and check that it's on the right subnet.
2159  */
2160             if (ioctl(sock_fd, SIOCGIFNETMASK, &ifreq) < 0)
2161                 continue;
2162
2163             mask = SIN_ADDR(ifreq.ifr_addr);
2164
2165             if (((ipaddr ^ ina) & mask) != 0)
2166                 continue; /* no match */
2167             /* matched */
2168             if (mask >= bestmask) {
2169                 /* Compare using >= instead of > -- it is possible for
2170                    an interface to have a netmask of 0.0.0.0 */
2171                 found_interface = 1;
2172                 bestifreq = ifreq;
2173                 bestmask = mask;
2174             }
2175         }
2176     }
2177
2178     if (!found_interface) return 0;
2179
2180     strlcpy(name, bestifreq.ifr_name, namelen);
2181
2182     /* trim off the :1 in eth0:1 */
2183     aliasp = strchr(name, ':');
2184     if (aliasp != 0)
2185         *aliasp = 0;
2186
2187     info("found interface %s for proxy arp", name);
2188 /*
2189  * Now get the hardware address.
2190  */
2191     memset (&bestifreq.ifr_hwaddr, 0, sizeof (struct sockaddr));
2192     if (ioctl (sock_fd, SIOCGIFHWADDR, &bestifreq) < 0) {
2193         error("SIOCGIFHWADDR(%s): %m", bestifreq.ifr_name);
2194         return 0;
2195     }
2196
2197     memcpy (hwaddr,
2198             &bestifreq.ifr_hwaddr,
2199             sizeof (struct sockaddr));
2200
2201     return 1;
2202 }
2203
2204 /*
2205  * get_if_hwaddr - get the hardware address for the specified
2206  * network interface device.
2207  */
2208 int
2209 get_if_hwaddr(u_char *addr, char *name)
2210 {
2211         struct ifreq ifreq;
2212         int ret, sock_fd;
2213
2214         sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
2215         if (sock_fd < 0)
2216                 return -1;
2217         memset(&ifreq.ifr_hwaddr, 0, sizeof(struct sockaddr));
2218         strlcpy(ifreq.ifr_name, name, sizeof(ifreq.ifr_name));
2219         ret = ioctl(sock_fd, SIOCGIFHWADDR, &ifreq);
2220         close(sock_fd);
2221         if (ret >= 0)
2222                 memcpy(addr, ifreq.ifr_hwaddr.sa_data, 6);
2223         return ret;
2224 }
2225
2226 /*
2227  * get_first_ether_hwaddr - get the hardware address for the first
2228  * ethernet-style interface on this system.
2229  */
2230 int
2231 get_first_ether_hwaddr(u_char *addr)
2232 {
2233         struct if_nameindex *if_ni, *i;
2234         struct ifreq ifreq;
2235         int ret, sock_fd;
2236
2237         sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
2238         if (sock_fd < 0)
2239                 return -1;
2240
2241         if_ni = if_nameindex();
2242         if (!if_ni) {
2243                 close(sock_fd);
2244                 return -1;
2245         }
2246
2247         ret = -1;
2248
2249         for (i = if_ni; !(i->if_index == 0 && i->if_name == NULL); i++) {
2250                 memset(&ifreq.ifr_hwaddr, 0, sizeof(struct sockaddr));
2251                 strlcpy(ifreq.ifr_name, i->if_name, sizeof(ifreq.ifr_name));
2252                 ret = ioctl(sock_fd, SIOCGIFHWADDR, &ifreq);
2253                 if (ret >= 0 && ifreq.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
2254                         memcpy(addr, ifreq.ifr_hwaddr.sa_data, 6);
2255                         break;
2256                 }
2257                 ret = -1;
2258         }
2259
2260         if_freenameindex(if_ni);
2261         close(sock_fd);
2262
2263         return ret;
2264 }
2265
2266 /********************************************************************
2267  *
2268  * Return user specified netmask, modified by any mask we might determine
2269  * for address `addr' (in network byte order).
2270  * Here we scan through the system's list of interfaces, looking for
2271  * any non-point-to-point interfaces which might appear to be on the same
2272  * network as `addr'.  If we find any, we OR in their netmask to the
2273  * user-specified netmask.
2274  */
2275
2276 u_int32_t GetMask (u_int32_t addr)
2277 {
2278     u_int32_t mask, nmask, ina;
2279     struct ifreq *ifr, *ifend, ifreq;
2280     struct ifconf ifc;
2281     struct ifreq ifs[MAX_IFS];
2282
2283     addr = ntohl(addr);
2284
2285     if (IN_CLASSA(addr))        /* determine network mask for address class */
2286         nmask = IN_CLASSA_NET;
2287     else if (IN_CLASSB(addr))
2288             nmask = IN_CLASSB_NET;
2289     else
2290             nmask = IN_CLASSC_NET;
2291
2292     /* class D nets are disallowed by bad_ip_adrs */
2293     mask = netmask | htonl(nmask);
2294 /*
2295  * Scan through the system's network interfaces.
2296  */
2297     ifc.ifc_len = sizeof(ifs);
2298     ifc.ifc_req = ifs;
2299     if (ioctl(sock_fd, SIOCGIFCONF, &ifc) < 0) {
2300         if ( ! ok_error ( errno ))
2301             warn("ioctl(SIOCGIFCONF): %m (line %d)", __LINE__);
2302         return mask;
2303     }
2304
2305     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
2306     for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
2307 /*
2308  * Check the interface's internet address.
2309  */
2310         if (ifr->ifr_addr.sa_family != AF_INET)
2311             continue;
2312         ina = SIN_ADDR(ifr->ifr_addr);
2313         if (((ntohl(ina) ^ addr) & nmask) != 0)
2314             continue;
2315 /*
2316  * Check that the interface is up, and not point-to-point nor loopback.
2317  */
2318         strlcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
2319         if (ioctl(sock_fd, SIOCGIFFLAGS, &ifreq) < 0)
2320             continue;
2321
2322         if (((ifreq.ifr_flags ^ FLAGS_GOOD) & FLAGS_MASK) != 0)
2323             continue;
2324 /*
2325  * Get its netmask and OR it into our mask.
2326  */
2327         if (ioctl(sock_fd, SIOCGIFNETMASK, &ifreq) < 0)
2328             continue;
2329         mask |= SIN_ADDR(ifreq.ifr_addr);
2330         break;
2331     }
2332     return mask;
2333 }
2334
2335 /********************************************************************
2336  *
2337  * Internal routine to decode the version.modification.patch level
2338  */
2339
2340 static void decode_version (char *buf, int *version,
2341                             int *modification, int *patch)
2342 {
2343     char *endp;
2344
2345     *version      = (int) strtoul (buf, &endp, 10);
2346     *modification = 0;
2347     *patch        = 0;
2348
2349     if (endp != buf && *endp == '.') {
2350         buf = endp + 1;
2351         *modification = (int) strtoul (buf, &endp, 10);
2352         if (endp != buf && *endp == '.') {
2353             buf = endp + 1;
2354             *patch = (int) strtoul (buf, &buf, 10);
2355         }
2356     }
2357 }
2358
2359 /********************************************************************
2360  *
2361  * Procedure to determine if the PPP line discipline is registered.
2362  */
2363
2364 static int
2365 ppp_registered(void)
2366 {
2367     int local_fd;
2368     int mfd = -1;
2369     int ret = 0;
2370     char slave[16];
2371
2372     /*
2373      * We used to open the serial device and set it to the ppp line
2374      * discipline here, in order to create a ppp unit.  But that is
2375      * not a good idea - the user might have specified a device that
2376      * they can't open (permission, or maybe it doesn't really exist).
2377      * So we grab a pty master/slave pair and use that.
2378      */
2379     if (!get_pty(&mfd, &local_fd, slave, 0)) {
2380         no_ppp_msg = "Couldn't determine if PPP is supported (no free ptys)";
2381         return 0;
2382     }
2383
2384     /*
2385      * Try to put the device into the PPP discipline.
2386      */
2387     if (ioctl(local_fd, TIOCSETD, &ppp_disc) < 0) {
2388         error("ioctl(TIOCSETD(PPP)): %m (line %d)", __LINE__);
2389     } else
2390         ret = 1;
2391
2392     close(local_fd);
2393     close(mfd);
2394     return ret;
2395 }
2396
2397 /********************************************************************
2398  *
2399  * ppp_available - check whether the system has any ppp interfaces
2400  * (in fact we check whether we can do an ioctl on ppp0).
2401  */
2402
2403 int ppp_available(void)
2404 {
2405     int s, ok, fd;
2406     struct ifreq ifr;
2407     int    size;
2408     int    my_version, my_modification, my_patch;
2409     int osmaj, osmin, ospatch;
2410
2411     /* get the kernel version now, since we are called before sys_init */
2412     uname(&utsname);
2413     osmaj = osmin = ospatch = 0;
2414     sscanf(utsname.release, "%d.%d.%d", &osmaj, &osmin, &ospatch);
2415     kernel_version = KVERSION(osmaj, osmin, ospatch);
2416
2417     fd = open("/dev/ppp", O_RDWR);
2418     if (fd >= 0) {
2419         new_style_driver = 1;
2420
2421         /* XXX should get from driver */
2422         driver_version = 2;
2423         driver_modification = 4;
2424         driver_patch = 0;
2425         close(fd);
2426         return 1;
2427     }
2428
2429     if (kernel_version >= KVERSION(2,3,13)) {
2430         error("Couldn't open the /dev/ppp device: %m");
2431         if (errno == ENOENT)
2432             no_ppp_msg =
2433                 "You need to create the /dev/ppp device node by\n"
2434                 "executing the following command as root:\n"
2435                 "       mknod /dev/ppp c 108 0\n";
2436         else if (errno == ENODEV || errno == ENXIO)
2437             no_ppp_msg =
2438                 "Please load the ppp_generic kernel module.\n";
2439         return 0;
2440     }
2441
2442     /* we are running on a really really old kernel */
2443     no_ppp_msg =
2444         "This system lacks kernel support for PPP.  This could be because\n"
2445         "the PPP kernel module could not be loaded, or because PPP was not\n"
2446         "included in the kernel configuration.  If PPP was included as a\n"
2447         "module, try `/sbin/modprobe -v ppp'.  If that fails, check that\n"
2448         "ppp.o exists in /lib/modules/`uname -r`/net.\n"
2449         "See README.linux file in the ppp distribution for more details.\n";
2450
2451 /*
2452  * Open a socket for doing the ioctl operations.
2453  */
2454     s = socket(AF_INET, SOCK_DGRAM, 0);
2455     if (s < 0)
2456         return 0;
2457
2458     strlcpy (ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name));
2459     ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0;
2460 /*
2461  * If the device did not exist then attempt to create one by putting the
2462  * current tty into the PPP discipline. If this works then obtain the
2463  * flags for the device again.
2464  */
2465     if (!ok) {
2466         if (ppp_registered()) {
2467             strlcpy (ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name));
2468             ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0;
2469         }
2470     }
2471 /*
2472  * Ensure that the hardware address is for PPP and not something else
2473  */
2474     if (ok)
2475         ok = ioctl (s, SIOCGIFHWADDR, (caddr_t) &ifr) >= 0;
2476
2477     if (ok && ((ifr.ifr_hwaddr.sa_family & ~0xFF) != ARPHRD_PPP))
2478         ok = 0;
2479
2480 /*
2481  *  This is the PPP device. Validate the version of the driver at this
2482  *  point to ensure that this program will work with the driver.
2483  */
2484     if (ok) {
2485         char   abBuffer [1024];
2486
2487         ifr.ifr_data = abBuffer;
2488         size = ioctl (s, SIOCGPPPVER, (caddr_t) &ifr);
2489         if (size < 0) {
2490             error("Couldn't read driver version: %m");
2491             ok = 0;
2492             no_ppp_msg = "Sorry, couldn't verify kernel driver version\n";
2493
2494         } else {
2495             decode_version(abBuffer,
2496                            &driver_version,
2497                            &driver_modification,
2498                            &driver_patch);
2499 /*
2500  * Validate the version of the driver against the version that we used.
2501  */
2502             decode_version(VERSION,
2503                            &my_version,
2504                            &my_modification,
2505                            &my_patch);
2506
2507             /* The version numbers must match */
2508             if (driver_version != my_version)
2509                 ok = 0;
2510
2511             /* The modification levels must be legal */
2512             if (driver_modification < 3) {
2513                 if (driver_modification >= 2) {
2514                     /* we can cope with 2.2.0 and above */
2515                     driver_is_old = 1;
2516                 } else {
2517                     ok = 0;
2518                 }
2519             }
2520
2521             if (!ok) {
2522                 slprintf(route_buffer, sizeof(route_buffer),
2523                          "Sorry - PPP driver version %d.%d.%d is out of date\n",
2524                          driver_version, driver_modification, driver_patch);
2525
2526                 no_ppp_msg = route_buffer;
2527             }
2528         }
2529     }
2530     close(s);
2531     return ok;
2532 }
2533
2534 #ifndef HAVE_LOGWTMP
2535 /********************************************************************
2536  *
2537  * Update the wtmp file with the appropriate user name and tty device.
2538  */
2539
2540 void logwtmp (const char *line, const char *name, const char *host)
2541 {
2542     struct utmp ut, *utp;
2543     pid_t  mypid = getpid();
2544 #if __GLIBC__ < 2
2545     int    wtmp;
2546 #endif
2547
2548 /*
2549  * Update the signon database for users.
2550  * Christoph Lameter: Copied from poeigl-1.36 Jan 3, 1996
2551  */
2552     utmpname(_PATH_UTMP);
2553     setutent();
2554     while ((utp = getutent()) && (utp->ut_pid != mypid))
2555         /* nothing */;
2556
2557     if (utp)
2558         memcpy(&ut, utp, sizeof(ut));
2559     else
2560         /* some gettys/telnetds don't initialize utmp... */
2561         memset(&ut, 0, sizeof(ut));
2562
2563     if (ut.ut_id[0] == 0)
2564         strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
2565
2566     strncpy(ut.ut_user, name, sizeof(ut.ut_user));
2567     strncpy(ut.ut_line, line, sizeof(ut.ut_line));
2568
2569     time(&ut.ut_time);
2570
2571     ut.ut_type = USER_PROCESS;
2572     ut.ut_pid  = mypid;
2573
2574     /* Insert the host name if one is supplied */
2575     if (*host)
2576         strncpy (ut.ut_host, host, sizeof(ut.ut_host));
2577
2578     /* Insert the IP address of the remote system if IP is enabled */
2579     if (ipcp_protent.enabled_flag && ipcp_hisoptions[0].neg_addr)
2580         memcpy(&ut.ut_addr, (char *) &ipcp_hisoptions[0].hisaddr,
2581                  sizeof(ut.ut_addr));
2582
2583     /* CL: Makes sure that the logout works */
2584     if (*host == 0 && *name==0)
2585         ut.ut_host[0]=0;
2586
2587     pututline(&ut);
2588     endutent();
2589 /*
2590  * Update the wtmp file.
2591  */
2592 #if __GLIBC__ >= 2
2593     updwtmp(_PATH_WTMP, &ut);
2594 #else
2595     wtmp = open(_PATH_WTMP, O_APPEND|O_WRONLY);
2596     if (wtmp >= 0) {
2597         flock(wtmp, LOCK_EX);
2598
2599         if (write (wtmp, (char *)&ut, sizeof(ut)) != sizeof(ut))
2600             warn("error writing %s: %m", _PATH_WTMP);
2601
2602         flock(wtmp, LOCK_UN);
2603
2604         close (wtmp);
2605     }
2606 #endif
2607 }
2608 #endif /* HAVE_LOGWTMP */
2609
2610 /********************************************************************
2611  *
2612  * sifvjcomp - config tcp header compression
2613  */
2614
2615 int sifvjcomp (int u, int vjcomp, int cidcomp, int maxcid)
2616 {
2617         u_int x;
2618
2619         if (vjcomp) {
2620                 if (ioctl(ppp_dev_fd, PPPIOCSMAXCID, (caddr_t) &maxcid) < 0) {
2621                         error("Couldn't set up TCP header compression: %m");
2622                         vjcomp = 0;
2623                 }
2624         }
2625
2626         x = (vjcomp? SC_COMP_TCP: 0) | (cidcomp? 0: SC_NO_TCP_CCID);
2627         modify_flags(ppp_dev_fd, SC_COMP_TCP|SC_NO_TCP_CCID, x);
2628
2629         return 1;
2630 }
2631
2632 /********************************************************************
2633  *
2634  * sifup - Config the interface up and enable IP packets to pass.
2635  */
2636
2637 int sifup(int u)
2638 {
2639     int ret;
2640
2641     if ((ret = setifstate(u, 1)))
2642         if_is_up++;
2643
2644     return ret;
2645 }
2646
2647 /********************************************************************
2648  *
2649  * sifdown - Disable the indicated protocol and config the interface
2650  *           down if there are no remaining protocols.
2651  */
2652
2653 int sifdown (int u)
2654 {
2655     if (if_is_up && --if_is_up > 0)
2656         return 1;
2657
2658 #ifdef INET6
2659     if (if6_is_up)
2660         return 1;
2661 #endif /* INET6 */
2662
2663     return setifstate(u, 0);
2664 }
2665
2666 #ifdef INET6
2667 /********************************************************************
2668  *
2669  * sif6up - Config the interface up for IPv6
2670  */
2671
2672 int sif6up(int u)
2673 {
2674     int ret;
2675
2676     if ((ret = setifstate(u, 1)))
2677         if6_is_up = 1;
2678
2679     return ret;
2680 }
2681
2682 /********************************************************************
2683  *
2684  * sif6down - Disable the IPv6CP protocol and config the interface
2685  *            down if there are no remaining protocols.
2686  */
2687
2688 int sif6down (int u)
2689 {
2690     if6_is_up = 0;
2691
2692     if (if_is_up)
2693         return 1;
2694
2695     return setifstate(u, 0);
2696 }
2697 #endif /* INET6 */
2698
2699 /********************************************************************
2700  *
2701  * setifstate - Config the interface up or down
2702  */
2703
2704 static int setifstate (int u, int state)
2705 {
2706     struct ifreq ifr;
2707
2708     memset (&ifr, '\0', sizeof (ifr));
2709     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
2710     if (ioctl(sock_fd, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
2711         if (! ok_error (errno))
2712             error("ioctl (SIOCGIFFLAGS): %m (line %d)", __LINE__);
2713         return 0;
2714     }
2715
2716     if (state)
2717         ifr.ifr_flags |= IFF_UP;
2718     else
2719         ifr.ifr_flags &= ~IFF_UP;
2720     ifr.ifr_flags |= IFF_POINTOPOINT;
2721     if (ioctl(sock_fd, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) {
2722         if (! ok_error (errno))
2723             error("ioctl(SIOCSIFFLAGS): %m (line %d)", __LINE__);
2724         return 0;
2725     }
2726     return 1;
2727 }
2728
2729 /********************************************************************
2730  *
2731  * sifaddr - Config the interface IP addresses and netmask.
2732  */
2733
2734 int sifaddr (int unit, u_int32_t our_adr, u_int32_t his_adr,
2735              u_int32_t net_mask)
2736 {
2737     struct ifreq   ifr;
2738     struct rtentry rt;
2739
2740     memset (&ifr, '\0', sizeof (ifr));
2741     memset (&rt,  '\0', sizeof (rt));
2742
2743     SET_SA_FAMILY (ifr.ifr_addr,    AF_INET);
2744     SET_SA_FAMILY (ifr.ifr_dstaddr, AF_INET);
2745     SET_SA_FAMILY (ifr.ifr_netmask, AF_INET);
2746
2747     strlcpy (ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
2748 /*
2749  *  Set our IP address
2750  */
2751     SIN_ADDR(ifr.ifr_addr) = our_adr;
2752     if (ioctl(sock_fd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
2753         if (errno != EEXIST) {
2754             if (! ok_error (errno))
2755                 error("ioctl(SIOCSIFADDR): %m (line %d)", __LINE__);
2756         }
2757         else {
2758             warn("ioctl(SIOCSIFADDR): Address already exists");
2759         }
2760         return (0);
2761     }
2762 /*
2763  *  Set the gateway address
2764  */
2765     if (his_adr != 0) {
2766         SIN_ADDR(ifr.ifr_dstaddr) = his_adr;
2767         if (ioctl(sock_fd, SIOCSIFDSTADDR, (caddr_t) &ifr) < 0) {
2768             if (! ok_error (errno))
2769                 error("ioctl(SIOCSIFDSTADDR): %m (line %d)", __LINE__);
2770             return (0);
2771         }
2772     }
2773 /*
2774  *  Set the netmask.
2775  *  For recent kernels, force the netmask to 255.255.255.255.
2776  */
2777     if (kernel_version >= KVERSION(2,1,16))
2778         net_mask = ~0L;
2779     if (net_mask != 0) {
2780         SIN_ADDR(ifr.ifr_netmask) = net_mask;
2781         if (ioctl(sock_fd, SIOCSIFNETMASK, (caddr_t) &ifr) < 0) {
2782             if (! ok_error (errno))
2783                 error("ioctl(SIOCSIFNETMASK): %m (line %d)", __LINE__);
2784             return (0);
2785         }
2786     }
2787 /*
2788  *  Add the device route
2789  */
2790     if (kernel_version < KVERSION(2,1,16)) {
2791         SET_SA_FAMILY (rt.rt_dst,     AF_INET);
2792         SET_SA_FAMILY (rt.rt_gateway, AF_INET);
2793         rt.rt_dev = ifname;
2794
2795         SIN_ADDR(rt.rt_gateway) = 0L;
2796         SIN_ADDR(rt.rt_dst)     = his_adr;
2797         rt.rt_flags = RTF_UP | RTF_HOST;
2798
2799         if (kernel_version > KVERSION(2,1,0)) {
2800             SET_SA_FAMILY (rt.rt_genmask, AF_INET);
2801             SIN_ADDR(rt.rt_genmask) = -1L;
2802         }
2803
2804         if (ioctl(sock_fd, SIOCADDRT, &rt) < 0) {
2805             if (! ok_error (errno))
2806                 error("ioctl(SIOCADDRT) device route: %m (line %d)", __LINE__);
2807             return (0);
2808         }
2809     }
2810
2811     /* set ip_dynaddr in demand mode if address changes */
2812     if (demand && tune_kernel && !dynaddr_set
2813         && our_old_addr && our_old_addr != our_adr) {
2814         /* set ip_dynaddr if possible */
2815         char *path;
2816         int fd;
2817
2818         path = path_to_procfs("/sys/net/ipv4/ip_dynaddr");
2819         if (path != 0 && (fd = open(path, O_WRONLY)) >= 0) {
2820             if (write(fd, "1", 1) != 1)
2821                 error("Couldn't enable dynamic IP addressing: %m");
2822             close(fd);
2823         }
2824         dynaddr_set = 1;        /* only 1 attempt */
2825     }
2826     our_old_addr = 0;
2827
2828     return 1;
2829 }
2830
2831 /********************************************************************
2832  *
2833  * cifaddr - Clear the interface IP addresses, and delete routes
2834  * through the interface if possible.
2835  */
2836
2837 int cifaddr (int unit, u_int32_t our_adr, u_int32_t his_adr)
2838 {
2839     struct ifreq ifr;
2840
2841     if (kernel_version < KVERSION(2,1,16)) {
2842 /*
2843  *  Delete the route through the device
2844  */
2845         struct rtentry rt;
2846         memset (&rt, '\0', sizeof (rt));
2847
2848         SET_SA_FAMILY (rt.rt_dst,     AF_INET);
2849         SET_SA_FAMILY (rt.rt_gateway, AF_INET);
2850         rt.rt_dev = ifname;
2851
2852         SIN_ADDR(rt.rt_gateway) = 0;
2853         SIN_ADDR(rt.rt_dst)     = his_adr;
2854         rt.rt_flags = RTF_UP | RTF_HOST;
2855
2856         if (kernel_version > KVERSION(2,1,0)) {
2857             SET_SA_FAMILY (rt.rt_genmask, AF_INET);
2858             SIN_ADDR(rt.rt_genmask) = -1L;
2859         }
2860
2861         if (ioctl(sock_fd, SIOCDELRT, &rt) < 0 && errno != ESRCH) {
2862             if (still_ppp() && ! ok_error (errno))
2863                 error("ioctl(SIOCDELRT) device route: %m (line %d)", __LINE__);
2864             return (0);
2865         }
2866     }
2867
2868     /* This way it is possible to have an IPX-only or IPv6-only interface */
2869     memset(&ifr, 0, sizeof(ifr));
2870     SET_SA_FAMILY(ifr.ifr_addr, AF_INET);
2871     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
2872
2873     if (ioctl(sock_fd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
2874         if (! ok_error (errno)) {
2875             error("ioctl(SIOCSIFADDR): %m (line %d)", __LINE__);
2876             return 0;
2877         }
2878     }
2879
2880     our_old_addr = our_adr;
2881
2882     return 1;
2883 }
2884
2885 #ifdef INET6
2886 /********************************************************************
2887  *
2888  * sif6addr_rtnetlink - Config the interface with both IPv6 link-local addresses via rtnetlink
2889  */
2890 static int sif6addr_rtnetlink(unsigned int iface, eui64_t our_eui64, eui64_t his_eui64)
2891 {
2892     struct {
2893         struct nlmsghdr nlh;
2894         struct ifaddrmsg ifa;
2895         struct {
2896             struct rtattr rta;
2897             struct in6_addr addr;
2898         } addrs[2];
2899     } nlreq;
2900     struct {
2901         struct nlmsghdr nlh;
2902         struct nlmsgerr nlerr;
2903     } nlresp;
2904     struct sockaddr_nl nladdr;
2905     struct iovec iov;
2906     struct msghdr msg;
2907     ssize_t nlresplen;
2908     int one;
2909     int fd;
2910
2911     fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
2912     if (fd < 0) {
2913         error("sif6addr_rtnetlink: socket(NETLINK_ROUTE): %m (line %d)", __LINE__);
2914         return 0;
2915     }
2916
2917     /*
2918      * Tell kernel to not send to us payload of acknowledgment error message.
2919      * NETLINK_CAP_ACK option is supported since Linux kernel version 4.3 and
2920      * older kernel versions always send full payload in acknowledgment netlink
2921      * message. We ignore payload of this message as we need only error code,
2922      * to check if our set remote peer address request succeeded or failed.
2923      * So ignore return value from the following setsockopt() call as setting
2924      * option NETLINK_CAP_ACK means for us just a kernel hint / optimization.
2925      */
2926     one = 1;
2927     setsockopt(fd, SOL_NETLINK, NETLINK_CAP_ACK, &one, sizeof(one));
2928
2929     memset(&nladdr, 0, sizeof(nladdr));
2930     nladdr.nl_family = AF_NETLINK;
2931
2932     if (bind(fd, (struct sockaddr *)&nladdr, sizeof(nladdr)) < 0) {
2933         error("sif6addr_rtnetlink: bind(AF_NETLINK): %m (line %d)", __LINE__);
2934         close(fd);
2935         return 0;
2936     }
2937
2938     memset(&nlreq, 0, sizeof(nlreq));
2939     nlreq.nlh.nlmsg_len = sizeof(nlreq);
2940     nlreq.nlh.nlmsg_type = RTM_NEWADDR;
2941     nlreq.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_EXCL | NLM_F_CREATE;
2942     nlreq.ifa.ifa_family = AF_INET6;
2943     nlreq.ifa.ifa_prefixlen = 128;
2944     nlreq.ifa.ifa_flags = IFA_F_NODAD | IFA_F_PERMANENT;
2945     nlreq.ifa.ifa_scope = RT_SCOPE_LINK;
2946     nlreq.ifa.ifa_index = iface;
2947     nlreq.addrs[0].rta.rta_len = sizeof(nlreq.addrs[0]);
2948     nlreq.addrs[0].rta.rta_type = IFA_LOCAL;
2949     IN6_LLADDR_FROM_EUI64(nlreq.addrs[0].addr, our_eui64);
2950     nlreq.addrs[1].rta.rta_len = sizeof(nlreq.addrs[1]);
2951     nlreq.addrs[1].rta.rta_type = IFA_ADDRESS;
2952     IN6_LLADDR_FROM_EUI64(nlreq.addrs[1].addr, his_eui64);
2953
2954     memset(&nladdr, 0, sizeof(nladdr));
2955     nladdr.nl_family = AF_NETLINK;
2956
2957     memset(&iov, 0, sizeof(iov));
2958     iov.iov_base = &nlreq;
2959     iov.iov_len = sizeof(nlreq);
2960
2961     memset(&msg, 0, sizeof(msg));
2962     msg.msg_name = &nladdr;
2963     msg.msg_namelen = sizeof(nladdr);
2964     msg.msg_iov = &iov;
2965     msg.msg_iovlen = 1;
2966
2967     if (sendmsg(fd, &msg, 0) < 0) {
2968         error("sif6addr_rtnetlink: sendmsg(RTM_NEWADDR/NLM_F_CREATE): %m (line %d)", __LINE__);
2969         close(fd);
2970         return 0;
2971     }
2972
2973     memset(&iov, 0, sizeof(iov));
2974     iov.iov_base = &nlresp;
2975     iov.iov_len = sizeof(nlresp);
2976
2977     memset(&msg, 0, sizeof(msg));
2978     msg.msg_name = &nladdr;
2979     msg.msg_namelen = sizeof(nladdr);
2980     msg.msg_iov = &iov;
2981     msg.msg_iovlen = 1;
2982
2983     nlresplen = recvmsg(fd, &msg, 0);
2984
2985     if (nlresplen < 0) {
2986         error("sif6addr_rtnetlink: recvmsg(NLM_F_ACK): %m (line %d)", __LINE__);
2987         close(fd);
2988         return 0;
2989     }
2990
2991     close(fd);
2992
2993     if (nladdr.nl_family != AF_NETLINK) {
2994         error("sif6addr_rtnetlink: recvmsg(NLM_F_ACK): Not a netlink packet (line %d)", __LINE__);
2995         return 0;
2996     }
2997
2998     if ((size_t)nlresplen != sizeof(nlresp) || nlresp.nlh.nlmsg_len < sizeof(nlresp)) {
2999         error("sif6addr_rtnetlink: recvmsg(NLM_F_ACK): Acknowledgment netlink packet too short (line %d)", __LINE__);
3000         return 0;
3001     }
3002
3003     /* acknowledgment packet for NLM_F_ACK is NLMSG_ERROR */
3004     if (nlresp.nlh.nlmsg_type != NLMSG_ERROR) {
3005         error("sif6addr_rtnetlink: recvmsg(NLM_F_ACK): Not an acknowledgment netlink packet (line %d)", __LINE__);
3006         return 0;
3007     }
3008
3009     /* error == 0 indicates success, negative value is errno code */
3010     if (nlresp.nlerr.error != 0) {
3011         error("sif6addr_rtnetlink: %s (line %d)", strerror(-nlresp.nlerr.error), __LINE__);
3012         return 0;
3013     }
3014
3015     return 1;
3016 }
3017
3018 /********************************************************************
3019  *
3020  * sif6addr - Config the interface with an IPv6 link-local address
3021  */
3022 int sif6addr (int unit, eui64_t our_eui64, eui64_t his_eui64)
3023 {
3024     struct in6_ifreq ifr6;
3025     struct ifreq ifr;
3026     struct in6_rtmsg rt6;
3027
3028     if (sock6_fd < 0) {
3029         errno = -sock6_fd;
3030         error("IPv6 socket creation failed: %m");
3031         return 0;
3032     }
3033     memset(&ifr, 0, sizeof (ifr));
3034     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
3035     if (ioctl(sock6_fd, SIOCGIFINDEX, (caddr_t) &ifr) < 0) {
3036         error("sif6addr: ioctl(SIOCGIFINDEX): %m (line %d)", __LINE__);
3037         return 0;
3038     }
3039
3040     if (kernel_version >= KVERSION(2,1,16)) {
3041         /* Set both local address and remote peer address (with route for it) via rtnetlink */
3042         return sif6addr_rtnetlink(ifr.ifr_ifindex, our_eui64, his_eui64);
3043     } else {
3044         /* Local interface */
3045         memset(&ifr6, 0, sizeof(ifr6));
3046         IN6_LLADDR_FROM_EUI64(ifr6.ifr6_addr, our_eui64);
3047         ifr6.ifr6_ifindex = ifr.ifr_ifindex;
3048         ifr6.ifr6_prefixlen = 128;
3049
3050         if (ioctl(sock6_fd, SIOCSIFADDR, &ifr6) < 0) {
3051             error("sif6addr: ioctl(SIOCSIFADDR): %m (line %d)", __LINE__);
3052             return 0;
3053         }
3054
3055         /*
3056          * Linux kernel does not provide AF_INET6 ioctl SIOCSIFDSTADDR for
3057          * setting remote peer host address, so set only route to remote host.
3058          */
3059
3060         /* Route to remote host */
3061         memset(&rt6, 0, sizeof(rt6));
3062         IN6_LLADDR_FROM_EUI64(rt6.rtmsg_dst, his_eui64);
3063         rt6.rtmsg_flags = RTF_UP;
3064         rt6.rtmsg_dst_len = 128;
3065         rt6.rtmsg_ifindex = ifr.ifr_ifindex;
3066         rt6.rtmsg_metric = 1;
3067
3068         if (ioctl(sock6_fd, SIOCADDRT, &rt6) < 0) {
3069             error("sif6addr: ioctl(SIOCADDRT): %m (line %d)", __LINE__);
3070             return 0;
3071         }
3072     }
3073
3074     return 1;
3075 }
3076
3077
3078 /********************************************************************
3079  *
3080  * cif6addr - Remove IPv6 address from interface
3081  */
3082 int cif6addr (int unit, eui64_t our_eui64, eui64_t his_eui64)
3083 {
3084     struct ifreq ifr;
3085     struct in6_ifreq ifr6;
3086
3087     if (sock6_fd < 0) {
3088         errno = -sock6_fd;
3089         error("IPv6 socket creation failed: %m");
3090         return 0;
3091     }
3092     memset(&ifr, 0, sizeof(ifr));
3093     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
3094     if (ioctl(sock6_fd, SIOCGIFINDEX, (caddr_t) &ifr) < 0) {
3095         error("cif6addr: ioctl(SIOCGIFINDEX): %m (line %d)", __LINE__);
3096         return 0;
3097     }
3098
3099     memset(&ifr6, 0, sizeof(ifr6));
3100     IN6_LLADDR_FROM_EUI64(ifr6.ifr6_addr, our_eui64);
3101     ifr6.ifr6_ifindex = ifr.ifr_ifindex;
3102     ifr6.ifr6_prefixlen = 128;
3103
3104     if (ioctl(sock6_fd, SIOCDIFADDR, &ifr6) < 0) {
3105         if (errno != EADDRNOTAVAIL) {
3106             if (! ok_error (errno))
3107                 error("cif6addr: ioctl(SIOCDIFADDR): %m (line %d)", __LINE__);
3108         }
3109         else {
3110             warn("cif6addr: ioctl(SIOCDIFADDR): No such address");
3111         }
3112         return (0);
3113     }
3114     return 1;
3115 }
3116 #endif /* INET6 */
3117
3118 /*
3119  * get_pty - get a pty master/slave pair and chown the slave side
3120  * to the uid given.  Assumes slave_name points to >= 16 bytes of space.
3121  */
3122 int
3123 get_pty(int *master_fdp, int *slave_fdp, char *slave_name, int uid)
3124 {
3125     int i, mfd, sfd = -1;
3126     char pty_name[16];
3127     struct termios tios;
3128
3129 #ifdef TIOCGPTN
3130     /*
3131      * Try the unix98 way first.
3132      */
3133     mfd = open("/dev/ptmx", O_RDWR);
3134     if (mfd >= 0) {
3135         int ptn;
3136         if (ioctl(mfd, TIOCGPTN, &ptn) >= 0) {
3137             slprintf(pty_name, sizeof(pty_name), "/dev/pts/%d", ptn);
3138             chmod(pty_name, S_IRUSR | S_IWUSR);
3139 #ifdef TIOCSPTLCK
3140             ptn = 0;
3141             if (ioctl(mfd, TIOCSPTLCK, &ptn) < 0)
3142                 warn("Couldn't unlock pty slave %s: %m", pty_name);
3143 #endif
3144             if ((sfd = open(pty_name, O_RDWR | O_NOCTTY)) < 0)
3145             {
3146                 warn("Couldn't open pty slave %s: %m", pty_name);
3147                 close(mfd);
3148             }
3149         }
3150     }
3151 #endif /* TIOCGPTN */
3152
3153     if (sfd < 0) {
3154         /* the old way - scan through the pty name space */
3155         for (i = 0; i < 64; ++i) {
3156             slprintf(pty_name, sizeof(pty_name), "/dev/pty%c%x",
3157                      'p' + i / 16, i % 16);
3158             mfd = open(pty_name, O_RDWR, 0);
3159             if (mfd >= 0) {
3160                 pty_name[5] = 't';
3161                 sfd = open(pty_name, O_RDWR | O_NOCTTY, 0);
3162                 if (sfd >= 0) {
3163                     fchown(sfd, uid, -1);
3164                     fchmod(sfd, S_IRUSR | S_IWUSR);
3165                     break;
3166                 }
3167                 close(mfd);
3168             }
3169         }
3170     }
3171
3172     if (sfd < 0)
3173         return 0;
3174
3175     strlcpy(slave_name, pty_name, 16);
3176     *master_fdp = mfd;
3177     *slave_fdp = sfd;
3178     if (tcgetattr(sfd, &tios) == 0) {
3179         tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB);
3180         tios.c_cflag |= CS8 | CREAD | CLOCAL;
3181         tios.c_iflag  = IGNPAR;
3182         tios.c_oflag  = 0;
3183         tios.c_lflag  = 0;
3184         if (tcsetattr(sfd, TCSAFLUSH, &tios) < 0)
3185             warn("couldn't set attributes on pty: %m");
3186     } else
3187         warn("couldn't get attributes on pty: %m");
3188
3189     return 1;
3190 }
3191
3192 /********************************************************************
3193  *
3194  * open_loopback - open the device we use for getting packets
3195  * in demand mode.  Under Linux, we use a pty master/slave pair.
3196  */
3197 int
3198 open_ppp_loopback(void)
3199 {
3200     int flags;
3201
3202     looped = 1;
3203     if (new_style_driver) {
3204         /* allocate ourselves a ppp unit */
3205         if (make_ppp_unit() < 0)
3206             die(1);
3207         modify_flags(ppp_dev_fd, 0, SC_LOOP_TRAFFIC);
3208         set_kdebugflag(kdebugflag);
3209         ppp_fd = -1;
3210         return ppp_dev_fd;
3211     }
3212
3213     if (!get_pty(&master_fd, &slave_fd, loop_name, 0))
3214         fatal("No free pty for loopback");
3215
3216     set_ppp_fd(slave_fd);
3217
3218     flags = fcntl(master_fd, F_GETFL);
3219     if (flags == -1 ||
3220         fcntl(master_fd, F_SETFL, flags | O_NONBLOCK) == -1)
3221         warn("couldn't set master loopback to nonblock: %m");
3222
3223     flags = fcntl(ppp_fd, F_GETFL);
3224     if (flags == -1 ||
3225         fcntl(ppp_fd, F_SETFL, flags | O_NONBLOCK) == -1)
3226         warn("couldn't set slave loopback to nonblock: %m");
3227
3228     if (ioctl(ppp_fd, TIOCSETD, &ppp_disc) < 0)
3229         fatal("ioctl(TIOCSETD): %m (line %d)", __LINE__);
3230 /*
3231  * Find out which interface we were given.
3232  */
3233     if (ioctl(ppp_fd, PPPIOCGUNIT, &ifunit) < 0)
3234         fatal("ioctl(PPPIOCGUNIT): %m (line %d)", __LINE__);
3235 /*
3236  * Enable debug in the driver if requested.
3237  */
3238     set_kdebugflag (kdebugflag);
3239
3240     return master_fd;
3241 }
3242
3243 /********************************************************************
3244  *
3245  * sifnpmode - Set the mode for handling packets for a given NP.
3246  */
3247
3248 int
3249 sifnpmode(int u, int proto, enum NPmode mode)
3250 {
3251     struct npioctl npi;
3252
3253     npi.protocol = proto;
3254     npi.mode     = mode;
3255     if (ioctl(ppp_dev_fd, PPPIOCSNPMODE, (caddr_t) &npi) < 0) {
3256         if (! ok_error (errno))
3257             error("ioctl(PPPIOCSNPMODE, %d, %d): %m", proto, mode);
3258         return 0;
3259     }
3260     return 1;
3261 }
3262
3263 \f
3264 /********************************************************************
3265  *
3266  * sipxfaddr - Config the interface IPX networknumber
3267  */
3268
3269 int sipxfaddr (int unit, unsigned long int network, unsigned char * node )
3270 {
3271     int    result = 1;
3272
3273 #ifdef IPX_CHANGE
3274     int    skfd;
3275     struct ifreq         ifr;
3276     struct sockaddr_ipx *sipx = (struct sockaddr_ipx *) &ifr.ifr_addr;
3277
3278     skfd = socket (AF_IPX, SOCK_DGRAM, 0);
3279     if (skfd < 0) {
3280         if (! ok_error (errno))
3281             dbglog("socket(AF_IPX): %m (line %d)", __LINE__);
3282         result = 0;
3283     }
3284     else {
3285         memset (&ifr, '\0', sizeof (ifr));
3286         strlcpy (ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
3287
3288         memcpy (sipx->sipx_node, node, IPX_NODE_LEN);
3289         sipx->sipx_family  = AF_IPX;
3290         sipx->sipx_port    = 0;
3291         sipx->sipx_network = htonl (network);
3292         sipx->sipx_type    = IPX_FRAME_ETHERII;
3293         sipx->sipx_action  = IPX_CRTITF;
3294 /*
3295  *  Set the IPX device
3296  */
3297         if (ioctl(skfd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
3298             result = 0;
3299             if (errno != EEXIST) {
3300                 if (! ok_error (errno))
3301                     dbglog("ioctl(SIOCSIFADDR, CRTITF): %m (line %d)", __LINE__);
3302             }
3303             else {
3304                 warn("ioctl(SIOCSIFADDR, CRTITF): Address already exists");
3305             }
3306         }
3307         close (skfd);
3308     }
3309 #endif
3310     return result;
3311 }
3312
3313 /********************************************************************
3314  *
3315  * cipxfaddr - Clear the information for the IPX network. The IPX routes
3316  *             are removed and the device is no longer able to pass IPX
3317  *             frames.
3318  */
3319
3320 int cipxfaddr (int unit)
3321 {
3322     int    result = 1;
3323
3324 #ifdef IPX_CHANGE
3325     int    skfd;
3326     struct ifreq         ifr;
3327     struct sockaddr_ipx *sipx = (struct sockaddr_ipx *) &ifr.ifr_addr;
3328
3329     skfd = socket (AF_IPX, SOCK_DGRAM, 0);
3330     if (skfd < 0) {
3331         if (! ok_error (errno))
3332             dbglog("socket(AF_IPX): %m (line %d)", __LINE__);
3333         result = 0;
3334     }
3335     else {
3336         memset (&ifr, '\0', sizeof (ifr));
3337         strlcpy (ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
3338
3339         sipx->sipx_type    = IPX_FRAME_ETHERII;
3340         sipx->sipx_action  = IPX_DLTITF;
3341         sipx->sipx_family  = AF_IPX;
3342 /*
3343  *  Set the IPX device
3344  */
3345         if (ioctl(skfd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
3346             if (! ok_error (errno))
3347                 info("ioctl(SIOCSIFADDR, IPX_DLTITF): %m (line %d)", __LINE__);
3348             result = 0;
3349         }
3350         close (skfd);
3351     }
3352 #endif
3353     return result;
3354 }
3355
3356 /*
3357  * Use the hostname as part of the random number seed.
3358  */
3359 int
3360 get_host_seed(void)
3361 {
3362     int h;
3363     char *p = hostname;
3364
3365     h = 407;
3366     for (p = hostname; *p != 0; ++p)
3367         h = h * 37 + *p;
3368     return h;
3369 }
3370
3371 /********************************************************************
3372  *
3373  * sys_check_options - check the options that the user specified
3374  */
3375
3376 int
3377 sys_check_options(void)
3378 {
3379 #ifdef IPX_CHANGE
3380 /*
3381  * Disable the IPX protocol if the support is not present in the kernel.
3382  */
3383     char *path;
3384
3385     if (ipxcp_protent.enabled_flag) {
3386         struct stat stat_buf;
3387         if (  ((path = path_to_procfs("/net/ipx/interface")) == NULL
3388             && (path = path_to_procfs("/net/ipx_interface")) == NULL)
3389             || lstat(path, &stat_buf) < 0) {
3390             error("IPX support is not present in the kernel\n");
3391             ipxcp_protent.enabled_flag = 0;
3392         }
3393     }
3394 #endif
3395     if (demand && driver_is_old) {
3396         option_error("demand dialling is not supported by kernel driver "
3397                      "version %d.%d.%d", driver_version, driver_modification,
3398                      driver_patch);
3399         return 0;
3400     }
3401     if (multilink && !new_style_driver) {
3402         warn("Warning: multilink is not supported by the kernel driver");
3403         multilink = 0;
3404     }
3405     return 1;
3406 }
3407
3408 /********************************************************************
3409  *
3410  * get_time - Get current time, monotonic if possible.
3411  */
3412 int
3413 get_time(struct timeval *tv)
3414 {
3415 /* Old glibc (< 2.3.4) does define CLOCK_MONOTONIC, but kernel may have it.
3416  * Runtime checking makes it safe. */
3417 #ifndef CLOCK_MONOTONIC
3418 #define CLOCK_MONOTONIC 1
3419 #endif
3420     static int monotonic = -1;
3421     struct timespec ts;
3422     int ret;
3423
3424     if (monotonic) {
3425         ret = clock_gettime(CLOCK_MONOTONIC, &ts);
3426         if (ret == 0) {
3427             monotonic = 1;
3428             if (tv) {
3429                 tv->tv_sec = ts.tv_sec;
3430                 tv->tv_usec = ts.tv_nsec / 1000;
3431             }
3432             return ret;
3433         } else if (monotonic > 0)
3434             return ret;
3435
3436         monotonic = 0;
3437         warn("Couldn't use monotonic clock source: %m");
3438     }
3439
3440     return gettimeofday(tv, NULL);
3441 }