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