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