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