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