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