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