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