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