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