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