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