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