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