]> git.ozlabs.org Git - ppp.git/blob - pppd/sys-linux.c
cope with /proc not being in mtab
[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) 1989 Carnegie Mellon University.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms are permitted
9  * provided that the above copyright notice and this paragraph are
10  * duplicated in all such forms and that any documentation,
11  * advertising materials, and other materials related to such
12  * distribution and use acknowledge that the software was developed
13  * by Carnegie Mellon University.  The name of the
14  * University may not be used to endorse or promote products derived
15  * from this software without specific prior written permission.
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19  */
20
21 #include <sys/ioctl.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <sys/time.h>
25 #include <sys/errno.h>
26 #include <sys/file.h>
27 #include <sys/stat.h>
28 #include <sys/utsname.h>
29 #include <sys/sysmacros.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <syslog.h>
34 #include <string.h>
35 #include <time.h>
36 #include <memory.h>
37 #include <utmp.h>
38 #include <mntent.h>
39 #include <signal.h>
40 #include <fcntl.h>
41 #include <ctype.h>
42 #include <termios.h>
43 #include <unistd.h>
44
45 /* This is in netdevice.h. However, this compile will fail miserably if
46    you attempt to include netdevice.h because it has so many references
47    to __memcpy functions which it should not attempt to do. So, since I
48    really don't use it, but it must be defined, define it now. */
49
50 #ifndef MAX_ADDR_LEN
51 #define MAX_ADDR_LEN 7
52 #endif
53
54 #if __GLIBC__ >= 2
55 #include <asm/types.h>          /* glibc 2 conflicts with linux/types.h */
56 #include <net/if.h>
57 #include <net/if_arp.h>
58 #include <net/route.h>
59 #include <netinet/if_ether.h>
60 #else
61 #include <linux/types.h>
62 #include <linux/if.h>
63 #include <linux/if_arp.h>
64 #include <linux/route.h>
65 #include <linux/if_ether.h>
66 #endif
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69
70 #include <linux/ppp_defs.h>
71 #include <linux/if_ppp.h>
72
73 #include "pppd.h"
74 #include "fsm.h"
75 #include "ipcp.h"
76 #include "patchlevel.h"
77
78 #ifdef IPX_CHANGE
79 #include "ipxcp.h"
80 #if __GLIBC__ >= 2 && \
81     !(defined(__powerpc__) && __GLIBC__ == 2 && __GLIBC_MINOR__ == 0)
82 #include <netipx/ipx.h>
83 #else
84 #include <linux/ipx.h>
85 #endif
86 #endif /* IPX_CHANGE */
87
88 #ifdef LOCKLIB
89 #include <sys/locks.h>
90 #endif
91
92 #ifdef INET6
93 #ifndef _LINUX_IN6_H
94 /*
95  *    This is in linux/include/net/ipv6.h.
96  */
97
98 struct in6_ifreq {
99     struct in6_addr ifr6_addr;
100     __u32 ifr6_prefixlen;
101     unsigned int ifr6_ifindex;
102 };
103 #endif
104
105 #define IN6_LLADDR_FROM_EUI64(sin6, eui64) do {                 \
106         memset(&sin6.s6_addr, 0, sizeof(struct in6_addr));      \
107         sin6.s6_addr16[0] = htons(0xfe80);                      \
108         eui64_copy(eui64, sin6.s6_addr32[2]);                   \
109         } while (0)
110
111 #endif /* INET6 */
112
113 /* We can get an EIO error on an ioctl if the modem has hung up */
114 #define ok_error(num) ((num)==EIO)
115
116 static int tty_disc = N_TTY;    /* The TTY discipline */
117 static int ppp_disc = N_PPP;    /* The PPP discpline */
118 static int initfdflags = -1;    /* Initial file descriptor flags for fd */
119 static int ppp_fd = -1;         /* fd which is set to PPP discipline */
120 static int sock_fd = -1;        /* socket for doing interface ioctls */
121 static int slave_fd = -1;
122 static int master_fd = -1;
123 #ifdef INET6
124 static int sock6_fd = -1;
125 #endif /* INET6 */
126 static int ppp_dev_fd = -1;     /* fd for /dev/ppp (new style driver) */
127
128 static fd_set in_fds;           /* set of fds that wait_input waits for */
129 static int max_in_fd;           /* highest fd set in in_fds */
130
131 static int has_proxy_arp       = 0;
132 static int driver_version      = 0;
133 static int driver_modification = 0;
134 static int driver_patch        = 0;
135 static int driver_is_old       = 0;
136 static int restore_term        = 0;     /* 1 => we've munged the terminal */
137 static struct termios inittermios;      /* Initial TTY termios */
138
139 static int new_style_driver = 0;
140
141 static char loop_name[20];
142 static unsigned char inbuf[512]; /* buffer for chars read from loopback */
143
144 static int      if_is_up;       /* Interface has been marked up */
145 static u_int32_t default_route_gateway; /* Gateway for default route added */
146 static u_int32_t proxy_arp_addr;        /* Addr for proxy arp entry added */
147 static char proxy_arp_dev[16];          /* Device for proxy arp entry */
148 static u_int32_t our_old_addr;          /* for detecting address changes */
149 static int      dynaddr_set;            /* 1 if ip_dynaddr set */
150 static int      looped;                 /* 1 if using loop */
151
152 static struct utsname utsname;  /* for the kernel version */
153 static int kernel_version;
154 #define KVERSION(j,n,p) ((j)*1000000 + (n)*1000 + (p))
155
156 #define MAX_IFS         100
157
158 #define FLAGS_GOOD (IFF_UP          | IFF_BROADCAST)
159 #define FLAGS_MASK (IFF_UP          | IFF_BROADCAST | \
160                     IFF_POINTOPOINT | IFF_LOOPBACK  | IFF_NOARP)
161
162 #define SIN_ADDR(x)     (((struct sockaddr_in *) (&(x)))->sin_addr.s_addr)
163
164 /* Prototypes for procedures local to this file. */
165 static int get_flags (int fd);
166 static void set_flags (int fd, int flags);
167 static int translate_speed (int bps);
168 static int baud_rate_of (int speed);
169 static void close_route_table (void);
170 static int open_route_table (void);
171 static int read_route_table (struct rtentry *rt);
172 static int defaultroute_exists (struct rtentry *rt);
173 static int get_ether_addr (u_int32_t ipaddr, struct sockaddr *hwaddr,
174                            char *name, int namelen);
175 static void decode_version (char *buf, int *version, int *mod, int *patch);
176 static int set_kdebugflag(int level);
177 static int ppp_registered(void);
178
179 extern u_char   inpacket_buf[]; /* borrowed from main.c */
180
181 /*
182  * SET_SA_FAMILY - set the sa_family field of a struct sockaddr,
183  * if it exists.
184  */
185
186 #define SET_SA_FAMILY(addr, family)                     \
187     memset ((char *) &(addr), '\0', sizeof(addr));      \
188     addr.sa_family = (family);
189
190 /*
191  * Determine if the PPP connection should still be present.
192  */
193
194 extern int hungup;
195
196 /* new_fd is the fd of a tty */
197 static void set_ppp_fd (int new_fd)
198 {
199         SYSDEBUG ((LOG_DEBUG, "setting ppp_fd to %d\n", new_fd));
200         ppp_fd = new_fd;
201         if (!new_style_driver)
202                 ppp_dev_fd = new_fd;
203 }
204
205 static int still_ppp(void)
206 {
207         if (new_style_driver)
208                 return !hungup && ppp_fd >= 0;
209         if (!hungup || ppp_fd == slave_fd)
210                 return 1;
211         if (slave_fd >= 0) {
212                 set_ppp_fd(slave_fd);
213                 return 1;
214         }
215         return 0;
216 }
217
218 /********************************************************************
219  *
220  * Functions to read and set the flags value in the device driver
221  */
222
223 static int get_flags (int fd)
224 {    
225     int flags;
226
227     if (ioctl(fd, PPPIOCGFLAGS, (caddr_t) &flags) < 0) {
228         if ( ok_error (errno) )
229             flags = 0;
230         else
231             fatal("ioctl(PPPIOCGFLAGS): %m");
232     }
233
234     SYSDEBUG ((LOG_DEBUG, "get flags = %x\n", flags));
235     return flags;
236 }
237
238 /********************************************************************/
239
240 static void set_flags (int fd, int flags)
241 {    
242     SYSDEBUG ((LOG_DEBUG, "set flags = %x\n", flags));
243
244     if (ioctl(fd, PPPIOCSFLAGS, (caddr_t) &flags) < 0) {
245         if (! ok_error (errno) )
246             fatal("ioctl(PPPIOCSFLAGS, %x): %m", flags, errno);
247     }
248 }
249
250 /********************************************************************
251  *
252  * sys_init - System-dependent initialization.
253  */
254
255 void sys_init(void)
256 {
257     int flags;
258
259     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
260     setlogmask(LOG_UPTO(LOG_INFO));
261     if (debug)
262         setlogmask(LOG_UPTO(LOG_DEBUG));
263
264     if (new_style_driver) {
265         ppp_dev_fd = open("/dev/ppp", O_RDWR);
266         if (ppp_dev_fd < 0)
267             fatal("Couldn't open /dev/ppp: %m");
268         flags = fcntl(ppp_dev_fd, F_GETFL);
269         if (flags == -1
270             || fcntl(ppp_dev_fd, F_SETFL, flags | O_NONBLOCK) == -1)
271             warn("Couldn't set /dev/ppp to nonblock: %m");
272     }
273
274     /* Get an internet socket for doing socket ioctls. */
275     sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
276     if (sock_fd < 0)
277         fatal("Couldn't create IP socket: %m(%d)", errno);
278
279 #ifdef INET6
280     sock6_fd = socket(AF_INET6, SOCK_DGRAM, 0);
281     if (sock6_fd < 0)
282         fatal("Couldn't create IPv6 socket: %m(%d)", errno);
283 #endif
284
285     FD_ZERO(&in_fds);
286     max_in_fd = 0;
287 }
288
289 /********************************************************************
290  *
291  * sys_cleanup - restore any system state we modified before exiting:
292  * mark the interface down, delete default route and/or proxy arp entry.
293  * This shouldn't call die() because it's called from die().
294  */
295
296 void sys_cleanup(void)
297 {
298 /*
299  * Take down the device
300  */
301     if (if_is_up) {
302         if_is_up = 0;
303         sifdown(0);
304     }
305 /*
306  * Delete any routes through the device.
307  */
308     if (default_route_gateway != 0)
309         cifdefaultroute(0, 0, default_route_gateway);
310
311     if (has_proxy_arp)
312         cifproxyarp(0, proxy_arp_addr);
313 }
314
315 /********************************************************************
316  *
317  * sys_close - Clean up in a child process before execing.
318  */
319 void
320 sys_close(void)
321 {
322     if (new_style_driver)
323         close(ppp_dev_fd);
324     if (sock_fd >= 0)
325         close(sock_fd);
326     if (slave_fd >= 0)
327         close(slave_fd);
328     if (master_fd >= 0)
329         close(master_fd);
330     closelog();
331 }
332
333 /********************************************************************
334  *
335  * set_kdebugflag - Define the debugging level for the kernel
336  */
337
338 static int set_kdebugflag (int requested_level)
339 {
340     if (ioctl(ppp_dev_fd, PPPIOCSDEBUG, &requested_level) < 0) {
341         if ( ! ok_error (errno) )
342             error("ioctl(PPPIOCSDEBUG): %m");
343         return (0);
344     }
345     SYSDEBUG ((LOG_INFO, "set kernel debugging level to %d",
346                 requested_level));
347     return (1);
348 }
349
350 /********************************************************************
351  *
352  * establish_ppp - Turn the serial port into a ppp interface.
353  */
354
355 int establish_ppp (int tty_fd)
356 {
357     int x;
358
359 /*
360  * The current PPP device will be the tty file.
361  */
362     set_ppp_fd (tty_fd);
363     if (new_style_driver)
364         add_fd(tty_fd);
365 /*
366  * Ensure that the tty device is in exclusive mode.
367  */
368     if (ioctl(tty_fd, TIOCEXCL, 0) < 0) {
369         if ( ! ok_error ( errno ))
370             warn("ioctl(TIOCEXCL): %m");
371     }
372 /*
373  * Demand mode - prime the old ppp device to relinquish the unit.
374  */
375     if (!new_style_driver && looped
376         && ioctl(slave_fd, PPPIOCXFERUNIT, 0) < 0)
377         fatal("ioctl(transfer ppp unit): %m(%d)", errno);
378 /*
379  * Set the current tty to the PPP discpline
380  */
381
382 #ifndef N_SYNC_PPP
383 #define N_SYNC_PPP 14
384 #endif
385     if (new_style_driver)
386             ppp_disc = sync_serial ? N_SYNC_PPP:N_PPP;
387
388     if (ioctl(tty_fd, TIOCSETD, &ppp_disc) < 0) {
389         if ( ! ok_error (errno) )
390             fatal("ioctl(TIOCSETD): %m(%d)", errno);
391     }
392 /*
393  * Find out which interface we were given.
394  */
395     if (new_style_driver) {
396         if (!looped) {
397             /* allocate ourselves a ppp unit */
398             ifunit = -1;
399             if (ioctl(ppp_dev_fd, PPPIOCNEWUNIT, &ifunit) < 0)
400                 fatal("Couldn't create new ppp unit: %m");
401             set_kdebugflag(kdebugflag);
402         } else {
403             set_flags(ppp_dev_fd, get_flags(ppp_dev_fd) & ~SC_LOOP_TRAFFIC);
404         }
405         if (ioctl(tty_fd, PPPIOCATTACH, &ifunit) < 0) {
406             if (errno == EIO)
407                 return -1;
408             fatal("Couldn't attach tty to PPP unit %d: %m", ifunit);
409         }
410     } else {
411         if (ioctl(tty_fd, PPPIOCGUNIT, &x) < 0) {       
412             if ( ! ok_error (errno))
413                 fatal("ioctl(PPPIOCGUNIT): %m(%d)", errno);
414         }
415         /* Check that we got the same unit again. */
416         if (looped && x != ifunit)
417             fatal("transfer_ppp failed: wanted unit %d, got %d", ifunit, x);
418         ifunit = x;
419     }
420
421 /*
422  * Enable debug in the driver if requested.
423  */
424     if (!looped)
425         set_kdebugflag (kdebugflag);
426     looped = 0;
427
428     set_flags(tty_fd, get_flags(tty_fd) & ~(SC_RCV_B7_0 | SC_RCV_B7_1 |
429                                             SC_RCV_EVNP | SC_RCV_ODDP));
430
431     SYSDEBUG ((LOG_NOTICE, "Using version %d.%d.%d of PPP driver",
432             driver_version, driver_modification, driver_patch));
433
434 /*
435  * Fetch the initial file flags and reset blocking mode on the file.
436  */
437     initfdflags = fcntl(tty_fd, F_GETFL);
438     if (initfdflags == -1 ||
439         fcntl(tty_fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
440         if ( ! ok_error (errno))
441             warn("Couldn't set device to non-blocking mode: %m");
442     }
443
444     return ppp_dev_fd;
445 }
446
447 /********************************************************************
448  *
449  * disestablish_ppp - Restore the serial port to normal operation.
450  * This shouldn't call die() because it's called from die().
451  */
452
453 void disestablish_ppp(int tty_fd)
454 {
455     if (new_style_driver)
456         remove_fd(tty_fd);
457     if (!hungup) {
458 /*
459  * Flush the tty output buffer so that the TIOCSETD doesn't hang.
460  */
461         if (tcflush(tty_fd, TCIOFLUSH) < 0)
462             warn("tcflush failed: %m");
463 /*
464  * Restore the previous line discipline
465  */
466         if (ioctl(tty_fd, TIOCSETD, &tty_disc) < 0) {
467             if ( ! ok_error (errno))
468                 error("ioctl(TIOCSETD, N_TTY): %m");
469         }
470         
471         if (ioctl(tty_fd, TIOCNXCL, 0) < 0) {
472             if ( ! ok_error (errno))
473                 warn("ioctl(TIOCNXCL): %m(%d)", errno);
474         }
475
476         /* Reset non-blocking mode on fd. */
477         if (initfdflags != -1 && fcntl(tty_fd, F_SETFL, initfdflags) < 0) {
478             if ( ! ok_error (errno))
479                 warn("Couldn't restore device fd flags: %m");
480         }
481     }
482     initfdflags = -1;
483     if (new_style_driver && !looped) {
484         if (ioctl(ppp_dev_fd, PPPIOCDETACH) < 0) {
485             if (errno == ENOTTY) {
486                 /* first version of new driver didn't have PPPIOCDETACH */
487                 int flags;
488
489                 close(ppp_dev_fd);
490                 ppp_dev_fd = open("/dev/ppp", O_RDWR);
491                 if (ppp_dev_fd < 0)
492                     fatal("Couldn't reopen /dev/ppp: %m");
493                 flags = fcntl(ppp_dev_fd, F_GETFL);
494                 if (flags == -1
495                     || fcntl(ppp_dev_fd, F_SETFL, flags | O_NONBLOCK) == -1)
496                     warn("Couldn't set /dev/ppp to nonblock: %m");
497             } else
498                 error("Couldn't release PPP unit: %m");
499         }
500         set_ppp_fd(-1);
501     }
502 }
503
504 /********************************************************************
505  *
506  * clean_check - Fetch the flags for the device and generate
507  * appropriate error messages.
508  */
509 void clean_check(void)
510 {
511     int x;
512     char *s;
513
514     if (still_ppp()) {
515         if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &x) == 0) {
516             s = NULL;
517             switch (~x & (SC_RCV_B7_0|SC_RCV_B7_1|SC_RCV_EVNP|SC_RCV_ODDP)) {
518             case SC_RCV_B7_0:
519                 s = "all had bit 7 set to 1";
520                 break;
521                 
522             case SC_RCV_B7_1:
523                 s = "all had bit 7 set to 0";
524                 break;
525                 
526             case SC_RCV_EVNP:
527                 s = "all had odd parity";
528                 break;
529                 
530             case SC_RCV_ODDP:
531                 s = "all had even parity";
532                 break;
533             }
534             
535             if (s != NULL) {
536                 warn("Receive serial link is not 8-bit clean:");
537                 warn("Problem: %s", s);
538             }
539         }
540     }
541 }
542         
543
544 /*
545  * List of valid speeds.
546  */
547
548 struct speed {
549     int speed_int, speed_val;
550 } speeds[] = {
551 #ifdef B50
552     { 50, B50 },
553 #endif
554 #ifdef B75
555     { 75, B75 },
556 #endif
557 #ifdef B110
558     { 110, B110 },
559 #endif
560 #ifdef B134
561     { 134, B134 },
562 #endif
563 #ifdef B150
564     { 150, B150 },
565 #endif
566 #ifdef B200
567     { 200, B200 },
568 #endif
569 #ifdef B300
570     { 300, B300 },
571 #endif
572 #ifdef B600
573     { 600, B600 },
574 #endif
575 #ifdef B1200
576     { 1200, B1200 },
577 #endif
578 #ifdef B1800
579     { 1800, B1800 },
580 #endif
581 #ifdef B2000
582     { 2000, B2000 },
583 #endif
584 #ifdef B2400
585     { 2400, B2400 },
586 #endif
587 #ifdef B3600
588     { 3600, B3600 },
589 #endif
590 #ifdef B4800
591     { 4800, B4800 },
592 #endif
593 #ifdef B7200
594     { 7200, B7200 },
595 #endif
596 #ifdef B9600
597     { 9600, B9600 },
598 #endif
599 #ifdef B19200
600     { 19200, B19200 },
601 #endif
602 #ifdef B38400
603     { 38400, B38400 },
604 #endif
605 #ifdef B57600
606     { 57600, B57600 },
607 #endif
608 #ifdef B115200
609     { 115200, B115200 },
610 #endif
611 #ifdef EXTA
612     { 19200, EXTA },
613 #endif
614 #ifdef EXTB
615     { 38400, EXTB },
616 #endif
617 #ifdef B230400
618     { 230400, B230400 },
619 #endif
620 #ifdef B460800
621     { 460800, B460800 },
622 #endif
623     { 0, 0 }
624 };
625
626 /********************************************************************
627  *
628  * Translate from bits/second to a speed_t.
629  */
630
631 static int translate_speed (int bps)
632 {
633     struct speed *speedp;
634
635     if (bps != 0) {
636         for (speedp = speeds; speedp->speed_int; speedp++) {
637             if (bps == speedp->speed_int)
638                 return speedp->speed_val;
639         }
640         warn("speed %d not supported", bps);
641     }
642     return 0;
643 }
644
645 /********************************************************************
646  *
647  * Translate from a speed_t to bits/second.
648  */
649
650 static int baud_rate_of (int speed)
651 {
652     struct speed *speedp;
653     
654     if (speed != 0) {
655         for (speedp = speeds; speedp->speed_int; speedp++) {
656             if (speed == speedp->speed_val)
657                 return speedp->speed_int;
658         }
659     }
660     return 0;
661 }
662
663 /********************************************************************
664  *
665  * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
666  * at the requested speed, etc.  If `local' is true, set CLOCAL
667  * regardless of whether the modem option was specified.
668  */
669
670 void set_up_tty(int tty_fd, int local)
671 {
672     int speed;
673     struct termios tios;
674
675     setdtr(tty_fd, 1);
676     if (tcgetattr(tty_fd, &tios) < 0) {
677         if (!ok_error(errno))
678             fatal("tcgetattr: %m(%d)", errno);
679         return;
680     }
681     
682     if (!restore_term)
683         inittermios = tios;
684     
685     tios.c_cflag     &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
686     tios.c_cflag     |= CS8 | CREAD | HUPCL;
687
688     tios.c_iflag      = IGNBRK | IGNPAR;
689     tios.c_oflag      = 0;
690     tios.c_lflag      = 0;
691     tios.c_cc[VMIN]   = 1;
692     tios.c_cc[VTIME]  = 0;
693     
694     if (local || !modem)
695         tios.c_cflag ^= (CLOCAL | HUPCL);
696
697     switch (crtscts) {
698     case 1:
699         tios.c_cflag |= CRTSCTS;
700         break;
701
702     case -2:
703         tios.c_iflag     |= IXON | IXOFF;
704         tios.c_cc[VSTOP]  = 0x13;       /* DC3 = XOFF = ^S */
705         tios.c_cc[VSTART] = 0x11;       /* DC1 = XON  = ^Q */
706         break;
707
708     case -1:
709         tios.c_cflag &= ~CRTSCTS;
710         break;
711
712     default:
713         break;
714     }
715     
716     speed = translate_speed(inspeed);
717     if (speed) {
718         cfsetospeed (&tios, speed);
719         cfsetispeed (&tios, speed);
720     }
721 /*
722  * We can't proceed if the serial port speed is B0,
723  * since that implies that the serial port is disabled.
724  */
725     else {
726         speed = cfgetospeed(&tios);
727         if (speed == B0)
728             fatal("Baud rate for %s is 0; need explicit baud rate", devnam);
729     }
730
731     if (tcsetattr(tty_fd, TCSAFLUSH, &tios) < 0)
732         if (!ok_error(errno))
733             fatal("tcsetattr: %m");
734     
735     baud_rate    = baud_rate_of(speed);
736     restore_term = 1;
737 }
738
739 /********************************************************************
740  *
741  * setdtr - control the DTR line on the serial port.
742  * This is called from die(), so it shouldn't call die().
743  */
744
745 void setdtr (int tty_fd, int on)
746 {
747     int modembits = TIOCM_DTR;
748
749     ioctl(tty_fd, (on ? TIOCMBIS : TIOCMBIC), &modembits);
750 }
751
752 /********************************************************************
753  *
754  * restore_tty - restore the terminal to the saved settings.
755  */
756
757 void restore_tty (int tty_fd)
758 {
759     if (restore_term) {
760         restore_term = 0;
761 /*
762  * Turn off echoing, because otherwise we can get into
763  * a loop with the tty and the modem echoing to each other.
764  * We presume we are the sole user of this tty device, so
765  * when we close it, it will revert to its defaults anyway.
766  */
767         if (!default_device)
768             inittermios.c_lflag &= ~(ECHO | ECHONL);
769         
770         if (tcsetattr(tty_fd, TCSAFLUSH, &inittermios) < 0) {
771             if (! ok_error (errno))
772                 warn("tcsetattr: %m");
773         }
774     }
775 }
776
777 /********************************************************************
778  *
779  * output - Output PPP packet.
780  */
781
782 void output (int unit, unsigned char *p, int len)
783 {
784     if (debug)
785         dbglog("sent %P", p, len);
786
787     if (len < PPP_HDRLEN)
788         return;
789     if (new_style_driver) {
790         p += 2;
791         len -= 2;
792     }
793     if (write(ppp_dev_fd, p, len) < 0) {
794         if (errno == EWOULDBLOCK || errno == ENOBUFS
795             || errno == ENXIO || errno == EIO || errno == EINTR)
796             warn("write: warning: %m (%d)", errno);
797         else
798             error("write: %m (%d)", errno);
799     }
800 }
801
802 /********************************************************************
803  *
804  * wait_input - wait until there is data available,
805  * for the length of time specified by *timo (indefinite
806  * if timo is NULL).
807  */
808
809 void wait_input(struct timeval *timo)
810 {
811     fd_set ready;
812     int n;
813
814     ready = in_fds;
815     n = select(max_in_fd + 1, &ready, NULL, &ready, timo);
816     if (n < 0 && errno != EINTR)
817         fatal("select: %m(%d)", errno);
818 }
819
820 /*
821  * add_fd - add an fd to the set that wait_input waits for.
822  */
823 void add_fd(int fd)
824 {
825     FD_SET(fd, &in_fds);
826     if (fd > max_in_fd)
827         max_in_fd = fd;
828 }
829
830 /*
831  * remove_fd - remove an fd from the set that wait_input waits for.
832  */
833 void remove_fd(int fd)
834 {
835     FD_CLR(fd, &in_fds);
836 }
837
838
839 /********************************************************************
840  *
841  * read_packet - get a PPP packet from the serial device.
842  */
843
844 int read_packet (unsigned char *buf)
845 {
846     int len, nr;
847
848     len = PPP_MRU + PPP_HDRLEN;
849     if (new_style_driver) {
850         *buf++ = PPP_ALLSTATIONS;
851         *buf++ = PPP_UI;
852         len -= 2;
853     }
854     nr = read(ppp_fd, buf, len);
855     if (new_style_driver && nr < 0 && (errno == EWOULDBLOCK || errno == EIO))
856         nr = read(ppp_dev_fd, buf, len);
857     if (nr < 0) {
858         if (errno == EWOULDBLOCK || errno == EIO)
859             return -1;
860         fatal("read: %m(%d)", errno);
861     }
862     return (new_style_driver && nr > 0)? nr+2: nr;
863 }
864
865 /********************************************************************
866  *
867  * get_loop_output - get outgoing packets from the ppp device,
868  * and detect when we want to bring the real link up.
869  * Return value is 1 if we need to bring up the link, 0 otherwise.
870  */
871 int
872 get_loop_output(void)
873 {
874     int rv = 0;
875     int n;
876
877     if (new_style_driver) {
878         while ((n = read_packet(inpacket_buf)) > 0)
879             if (loop_frame(inpacket_buf, n))
880                 rv = 1;
881         return rv;
882     }
883
884     while ((n = read(master_fd, inbuf, sizeof(inbuf))) > 0)
885         if (loop_chars(inbuf, n))
886             rv = 1;
887
888     if (n == 0)
889         fatal("eof on loopback");
890
891     if (errno != EWOULDBLOCK)
892         fatal("read from loopback: %m(%d)", errno);
893
894     return rv;
895 }
896
897 /********************************************************************
898  *
899  * ppp_send_config - configure the transmit characteristics of
900  * the ppp interface.
901  */
902
903 void ppp_send_config (int unit,int mtu,u_int32_t asyncmap,int pcomp,int accomp)
904 {
905     u_int x;
906     struct ifreq ifr;
907   
908     SYSDEBUG ((LOG_DEBUG, "send_config: mtu = %d\n", mtu));
909 /*
910  * Set the MTU and other parameters for the ppp device
911  */
912     memset (&ifr, '\0', sizeof (ifr));
913     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
914     ifr.ifr_mtu = mtu;
915         
916     if (ioctl(sock_fd, SIOCSIFMTU, (caddr_t) &ifr) < 0)
917         fatal("ioctl(SIOCSIFMTU): %m(%d)", errno);
918         
919     if (!still_ppp())
920         return;
921     SYSDEBUG ((LOG_DEBUG, "send_config: asyncmap = %lx\n", asyncmap));
922     if (ioctl(ppp_fd, PPPIOCSASYNCMAP, (caddr_t) &asyncmap) < 0) {
923         if (!ok_error(errno))
924             fatal("ioctl(PPPIOCSASYNCMAP): %m(%d)", errno);
925         return;
926     }
927     
928     x = get_flags(ppp_fd);
929     x = pcomp  ? x | SC_COMP_PROT : x & ~SC_COMP_PROT;
930     x = accomp ? x | SC_COMP_AC   : x & ~SC_COMP_AC;
931     x = sync_serial ? x | SC_SYNC : x & ~SC_SYNC;
932     set_flags(ppp_fd, x);
933 }
934
935 /********************************************************************
936  *
937  * ppp_set_xaccm - set the extended transmit ACCM for the interface.
938  */
939
940 void ppp_set_xaccm (int unit, ext_accm accm)
941 {
942     SYSDEBUG ((LOG_DEBUG, "set_xaccm: %08lx %08lx %08lx %08lx\n",
943                 accm[0], accm[1], accm[2], accm[3]));
944
945     if (!still_ppp())
946         return;
947     if (ioctl(ppp_fd, PPPIOCSXASYNCMAP, accm) < 0 && errno != ENOTTY) {
948         if ( ! ok_error (errno))
949             warn("ioctl(set extended ACCM): %m(%d)", errno);
950     }
951 }
952
953 /********************************************************************
954  *
955  * ppp_recv_config - configure the receive-side characteristics of
956  * the ppp interface.
957  */
958
959 void ppp_recv_config (int unit,int mru,u_int32_t asyncmap,int pcomp,int accomp)
960 {
961     SYSDEBUG ((LOG_DEBUG, "recv_config: mru = %d\n", mru));
962 /*
963  * If we were called because the link has gone down then there is nothing
964  * which may be done. Just return without incident.
965  */
966     if (!still_ppp())
967         return;
968 /*
969  * Set the receiver parameters
970  */
971     if (ioctl(ppp_fd, PPPIOCSMRU, (caddr_t) &mru) < 0) {
972         if ( ! ok_error (errno))
973             error("ioctl(PPPIOCSMRU): %m(%d)", errno);
974     }
975     if (new_style_driver && ioctl(ppp_dev_fd, PPPIOCSMRU, (caddr_t) &mru) < 0)
976         error("Couldn't set MRU in generic PPP layer: %m");
977
978     SYSDEBUG ((LOG_DEBUG, "recv_config: asyncmap = %lx\n", asyncmap));
979     if (ioctl(ppp_fd, PPPIOCSRASYNCMAP, (caddr_t) &asyncmap) < 0) {
980         if (!ok_error(errno))
981             error("ioctl(PPPIOCSRASYNCMAP): %m(%d)", errno);
982     }
983 }
984
985 /********************************************************************
986  *
987  * ccp_test - ask kernel whether a given compression method
988  * is acceptable for use.
989  */
990
991 int ccp_test (int unit, u_char *opt_ptr, int opt_len, int for_transmit)
992 {
993     struct ppp_option_data data;
994
995     memset (&data, '\0', sizeof (data));
996     data.ptr      = opt_ptr;
997     data.length   = opt_len;
998     data.transmit = for_transmit;
999
1000     if (ioctl(ppp_dev_fd, PPPIOCSCOMPRESS, (caddr_t) &data) >= 0)
1001         return 1;
1002
1003     return (errno == ENOBUFS)? 0: -1;
1004 }
1005
1006 /********************************************************************
1007  *
1008  * ccp_flags_set - inform kernel about the current state of CCP.
1009  */
1010
1011 void ccp_flags_set (int unit, int isopen, int isup)
1012 {
1013     if (still_ppp()) {
1014         int x = get_flags(ppp_dev_fd);
1015         x = isopen? x | SC_CCP_OPEN : x &~ SC_CCP_OPEN;
1016         x = isup?   x | SC_CCP_UP   : x &~ SC_CCP_UP;
1017         set_flags (ppp_dev_fd, x);
1018     }
1019 }
1020
1021 /********************************************************************
1022  *
1023  * get_idle_time - return how long the link has been idle.
1024  */
1025 int
1026 get_idle_time(u, ip)
1027     int u;
1028     struct ppp_idle *ip;
1029 {
1030     return ioctl(ppp_dev_fd, PPPIOCGIDLE, ip) >= 0;
1031
1032
1033 /********************************************************************
1034  *
1035  * get_ppp_stats - return statistics for the link.
1036  */
1037 int
1038 get_ppp_stats(u, stats)
1039     int u;
1040     struct pppd_stats *stats;
1041 {
1042     struct ifpppstatsreq req;
1043
1044     memset (&req, 0, sizeof (req));
1045
1046     req.stats_ptr = (caddr_t) &req.stats;
1047     strlcpy(req.ifr__name, ifname, sizeof(req.ifr__name));
1048     if (ioctl(sock_fd, SIOCGPPPSTATS, &req) < 0) {
1049         error("Couldn't get PPP statistics: %m");
1050         return 0;
1051     }
1052     stats->bytes_in = req.stats.p.ppp_ibytes;
1053     stats->bytes_out = req.stats.p.ppp_obytes;
1054     return 1;
1055 }
1056
1057 /********************************************************************
1058  *
1059  * ccp_fatal_error - returns 1 if decompression was disabled as a
1060  * result of an error detected after decompression of a packet,
1061  * 0 otherwise.  This is necessary because of patent nonsense.
1062  */
1063
1064 int ccp_fatal_error (int unit)
1065 {
1066     int x = get_flags(ppp_dev_fd);
1067
1068     return x & SC_DC_FERROR;
1069 }
1070
1071 /********************************************************************
1072  *
1073  * path_to_procfs - find the path to the proc file system mount point
1074  */
1075 static char proc_path[MAXPATHLEN];
1076 static int proc_path_len;
1077
1078 static char *path_to_procfs(const char *tail)
1079 {
1080     struct mntent *mntent;
1081     FILE *fp;
1082
1083     if (proc_path_len == 0) {
1084         /* Default the mount location of /proc */
1085         strlcpy (proc_path, "/proc", sizeof(proc_path));
1086         proc_path_len = 5;
1087         fp = fopen(MOUNTED, "r");
1088         if (fp != NULL) {
1089             while ((mntent = getmntent(fp)) != NULL) {
1090                 if (strcmp(mntent->mnt_type, MNTTYPE_IGNORE) == 0)
1091                     continue;
1092                 if (strcmp(mntent->mnt_type, "proc") == 0) {
1093                     strlcpy(proc_path, mntent->mnt_dir, sizeof(proc_path));
1094                     proc_path_len = strlen(proc_path);
1095                     break;
1096                 }
1097             }
1098             fclose (fp);
1099         }
1100     }
1101
1102     strlcpy(proc_path + proc_path_len, tail,
1103             sizeof(proc_path) - proc_path_len);
1104     return proc_path;
1105 }
1106
1107 /*
1108  * /proc/net/route parsing stuff.
1109  */
1110 #define ROUTE_MAX_COLS  12
1111 FILE *route_fd = (FILE *) 0;
1112 static char route_buffer[512];
1113 static int route_dev_col, route_dest_col, route_gw_col;
1114 static int route_flags_col, route_mask_col;
1115 static int route_num_cols;
1116
1117 static int open_route_table (void);
1118 static void close_route_table (void);
1119 static int read_route_table (struct rtentry *rt);
1120
1121 /********************************************************************
1122  *
1123  * close_route_table - close the interface to the route table
1124  */
1125
1126 static void close_route_table (void)
1127 {
1128     if (route_fd != (FILE *) 0) {
1129         fclose (route_fd);
1130         route_fd = (FILE *) 0;
1131     }
1132 }
1133
1134 /********************************************************************
1135  *
1136  * open_route_table - open the interface to the route table
1137  */
1138 static char route_delims[] = " \t\n";
1139
1140 static int open_route_table (void)
1141 {
1142     char *path;
1143
1144     close_route_table();
1145
1146     path = path_to_procfs("/net/route");
1147     route_fd = fopen (path, "r");
1148     if (route_fd == NULL) {
1149         error("can't open routing table %s: %m", path);
1150         return 0;
1151     }
1152
1153     route_dev_col = 0;          /* default to usual columns */
1154     route_dest_col = 1;
1155     route_gw_col = 2;
1156     route_flags_col = 3;
1157     route_mask_col = 7;
1158     route_num_cols = 8;
1159
1160     /* parse header line */
1161     if (fgets(route_buffer, sizeof(route_buffer), route_fd) != 0) {
1162         char *p = route_buffer, *q;
1163         int col;
1164         for (col = 0; col < ROUTE_MAX_COLS; ++col) {
1165             int used = 1;
1166             if ((q = strtok(p, route_delims)) == 0)
1167                 break;
1168             if (strcasecmp(q, "iface") == 0)
1169                 route_dev_col = col;
1170             else if (strcasecmp(q, "destination") == 0)
1171                 route_dest_col = col;
1172             else if (strcasecmp(q, "gateway") == 0)
1173                 route_gw_col = col;
1174             else if (strcasecmp(q, "flags") == 0)
1175                 route_flags_col = col;
1176             else if (strcasecmp(q, "mask") == 0)
1177                 route_mask_col = col;
1178             else
1179                 used = 0;
1180             if (used && col >= route_num_cols)
1181                 route_num_cols = col + 1;
1182             p = NULL;
1183         }
1184     }
1185
1186     return 1;
1187 }
1188
1189 /********************************************************************
1190  *
1191  * read_route_table - read the next entry from the route table
1192  */
1193
1194 static int read_route_table(struct rtentry *rt)
1195 {
1196     char *cols[ROUTE_MAX_COLS], *p;
1197     int col;
1198         
1199     memset (rt, '\0', sizeof (struct rtentry));
1200
1201     if (fgets (route_buffer, sizeof (route_buffer), route_fd) == (char *) 0)
1202         return 0;
1203
1204     p = route_buffer;
1205     for (col = 0; col < route_num_cols; ++col) {
1206         cols[col] = strtok(p, route_delims);
1207         if (cols[col] == NULL)
1208             return 0;           /* didn't get enough columns */
1209         p = NULL;
1210     }
1211
1212     SIN_ADDR(rt->rt_dst) = strtoul(cols[route_dest_col], NULL, 16);
1213     SIN_ADDR(rt->rt_gateway) = strtoul(cols[route_gw_col], NULL, 16);
1214     SIN_ADDR(rt->rt_genmask) = strtoul(cols[route_mask_col], NULL, 16);
1215
1216     rt->rt_flags = (short) strtoul(cols[route_flags_col], NULL, 16);
1217     rt->rt_dev   = cols[route_dev_col];
1218
1219     return 1;
1220 }
1221
1222 /********************************************************************
1223  *
1224  * defaultroute_exists - determine if there is a default route
1225  */
1226
1227 static int defaultroute_exists (struct rtentry *rt)
1228 {
1229     int result = 0;
1230
1231     if (!open_route_table())
1232         return 0;
1233
1234     while (read_route_table(rt) != 0) {
1235         if ((rt->rt_flags & RTF_UP) == 0)
1236             continue;
1237
1238         if (kernel_version > KVERSION(2,1,0) && SIN_ADDR(rt->rt_genmask) != 0)
1239             continue;
1240         if (SIN_ADDR(rt->rt_dst) == 0L) {
1241             result = 1;
1242             break;
1243         }
1244     }
1245
1246     close_route_table();
1247     return result;
1248 }
1249
1250 /*
1251  * have_route_to - determine if the system has any route to
1252  * a given IP address.  `addr' is in network byte order.
1253  * Return value is 1 if yes, 0 if no, -1 if don't know.
1254  * For demand mode to work properly, we have to ignore routes
1255  * through our own interface.
1256  */
1257 int have_route_to(u_int32_t addr)
1258 {
1259     struct rtentry rt;
1260     int result = 0;
1261
1262     if (!open_route_table())
1263         return -1;              /* don't know */
1264
1265     while (read_route_table(&rt)) {
1266         if ((rt.rt_flags & RTF_UP) == 0 || strcmp(rt.rt_dev, ifname) == 0)
1267             continue;
1268         if ((addr & SIN_ADDR(rt.rt_genmask)) == SIN_ADDR(rt.rt_dst)) {
1269             result = 1;
1270             break;
1271         }
1272     }
1273
1274     close_route_table();
1275     return result;
1276 }
1277
1278 /********************************************************************
1279  *
1280  * sifdefaultroute - assign a default route through the address given.
1281  */
1282
1283 int sifdefaultroute (int unit, u_int32_t ouraddr, u_int32_t gateway)
1284 {
1285     struct rtentry rt;
1286
1287     if (defaultroute_exists(&rt) && strcmp(rt.rt_dev, ifname) != 0) {
1288         u_int32_t old_gateway = SIN_ADDR(rt.rt_gateway);
1289
1290         if (old_gateway != gateway)
1291             error("not replacing existing default route to %s [%I]",
1292                   rt.rt_dev, old_gateway);
1293         return 0;
1294     }
1295
1296     memset (&rt, '\0', sizeof (rt));
1297     SET_SA_FAMILY (rt.rt_dst,     AF_INET);
1298     SET_SA_FAMILY (rt.rt_gateway, AF_INET);
1299
1300     if (kernel_version > KVERSION(2,1,0)) {
1301         SET_SA_FAMILY (rt.rt_genmask, AF_INET);
1302         SIN_ADDR(rt.rt_genmask) = 0L;
1303     }
1304
1305     SIN_ADDR(rt.rt_gateway) = gateway;
1306     
1307     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1308     if (ioctl(sock_fd, SIOCADDRT, &rt) < 0) {
1309         if ( ! ok_error ( errno ))
1310             error("default route ioctl(SIOCADDRT): %m(%d)", errno);
1311         return 0;
1312     }
1313
1314     default_route_gateway = gateway;
1315     return 1;
1316 }
1317
1318 /********************************************************************
1319  *
1320  * cifdefaultroute - delete a default route through the address given.
1321  */
1322
1323 int cifdefaultroute (int unit, u_int32_t ouraddr, u_int32_t gateway)
1324 {
1325     struct rtentry rt;
1326
1327     default_route_gateway = 0;
1328
1329     memset (&rt, '\0', sizeof (rt));
1330     SET_SA_FAMILY (rt.rt_dst,     AF_INET);
1331     SET_SA_FAMILY (rt.rt_gateway, AF_INET);
1332
1333     if (kernel_version > KVERSION(2,1,0)) {
1334         SET_SA_FAMILY (rt.rt_genmask, AF_INET);
1335         SIN_ADDR(rt.rt_genmask) = 0L;
1336     }
1337
1338     SIN_ADDR(rt.rt_gateway) = gateway;
1339     
1340     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1341     if (ioctl(sock_fd, SIOCDELRT, &rt) < 0 && errno != ESRCH) {
1342         if (still_ppp()) {
1343             if ( ! ok_error ( errno ))
1344                 error("default route ioctl(SIOCDELRT): %m (%d)", errno);
1345             return 0;
1346         }
1347     }
1348
1349     return 1;
1350 }
1351
1352 /********************************************************************
1353  *
1354  * sifproxyarp - Make a proxy ARP entry for the peer.
1355  */
1356
1357 int sifproxyarp (int unit, u_int32_t his_adr)
1358 {
1359     struct arpreq arpreq;
1360     char *forw_path;
1361
1362     if (has_proxy_arp == 0) {
1363         memset (&arpreq, '\0', sizeof(arpreq));
1364     
1365         SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
1366         SIN_ADDR(arpreq.arp_pa) = his_adr;
1367         arpreq.arp_flags = ATF_PERM | ATF_PUBL;
1368 /*
1369  * Get the hardware address of an interface on the same subnet
1370  * as our local address.
1371  */
1372         if (!get_ether_addr(his_adr, &arpreq.arp_ha, proxy_arp_dev,
1373                             sizeof(proxy_arp_dev))) {
1374             error("Cannot determine ethernet address for proxy ARP");
1375             return 0;
1376         }
1377         strlcpy(arpreq.arp_dev, proxy_arp_dev, sizeof(arpreq.arp_dev));
1378
1379         if (ioctl(sock_fd, SIOCSARP, (caddr_t)&arpreq) < 0) {
1380             if ( ! ok_error ( errno ))
1381                 error("ioctl(SIOCSARP): %m(%d)", errno);
1382             return 0;
1383         }
1384         proxy_arp_addr = his_adr;
1385         has_proxy_arp = 1;
1386
1387         if (tune_kernel) {
1388             forw_path = path_to_procfs("/sys/net/ipv4/ip_forward");
1389             if (forw_path != 0) {
1390                 int fd = open(forw_path, O_WRONLY);
1391                 if (fd >= 0) {
1392                     if (write(fd, "1", 1) != 1)
1393                         error("Couldn't enable IP forwarding: %m");
1394                     close(fd);
1395                 }
1396             }
1397         }
1398     }
1399
1400     return 1;
1401 }
1402
1403 /********************************************************************
1404  *
1405  * cifproxyarp - Delete the proxy ARP entry for the peer.
1406  */
1407
1408 int cifproxyarp (int unit, u_int32_t his_adr)
1409 {
1410     struct arpreq arpreq;
1411
1412     if (has_proxy_arp) {
1413         has_proxy_arp = 0;
1414         memset (&arpreq, '\0', sizeof(arpreq));
1415         SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
1416         SIN_ADDR(arpreq.arp_pa) = his_adr;
1417         arpreq.arp_flags = ATF_PERM | ATF_PUBL;
1418         strlcpy(arpreq.arp_dev, proxy_arp_dev, sizeof(arpreq.arp_dev));
1419
1420         if (ioctl(sock_fd, SIOCDARP, (caddr_t)&arpreq) < 0) {
1421             if ( ! ok_error ( errno ))
1422                 warn("ioctl(SIOCDARP): %m(%d)", errno);
1423             return 0;
1424         }
1425     }
1426     return 1;
1427 }
1428      
1429 /********************************************************************
1430  *
1431  * get_ether_addr - get the hardware address of an interface on the
1432  * the same subnet as ipaddr.
1433  */
1434
1435 static int get_ether_addr (u_int32_t ipaddr,
1436                            struct sockaddr *hwaddr,
1437                            char *name, int namelen)
1438 {
1439     struct ifreq *ifr, *ifend;
1440     u_int32_t ina, mask;
1441     char *aliasp;
1442     struct ifreq ifreq;
1443     struct ifconf ifc;
1444     struct ifreq ifs[MAX_IFS];
1445     
1446     ifc.ifc_len = sizeof(ifs);
1447     ifc.ifc_req = ifs;
1448     if (ioctl(sock_fd, SIOCGIFCONF, &ifc) < 0) {
1449         if ( ! ok_error ( errno ))
1450             error("ioctl(SIOCGIFCONF): %m(%d)", errno);
1451         return 0;
1452     }
1453
1454     SYSDEBUG ((LOG_DEBUG, "proxy arp: scanning %d interfaces for IP %s",
1455                 ifc.ifc_len / sizeof(struct ifreq), ip_ntoa(ipaddr)));
1456 /*
1457  * Scan through looking for an interface with an Internet
1458  * address on the same subnet as `ipaddr'.
1459  */
1460     ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
1461     for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
1462         if (ifr->ifr_addr.sa_family == AF_INET) {
1463             ina = SIN_ADDR(ifr->ifr_addr);
1464             strlcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
1465             SYSDEBUG ((LOG_DEBUG, "proxy arp: examining interface %s",
1466                         ifreq.ifr_name));
1467 /*
1468  * Check that the interface is up, and not point-to-point
1469  * nor loopback.
1470  */
1471             if (ioctl(sock_fd, SIOCGIFFLAGS, &ifreq) < 0)
1472                 continue;
1473
1474             if (((ifreq.ifr_flags ^ FLAGS_GOOD) & FLAGS_MASK) != 0)
1475                 continue;
1476 /*
1477  * Get its netmask and check that it's on the right subnet.
1478  */
1479             if (ioctl(sock_fd, SIOCGIFNETMASK, &ifreq) < 0)
1480                 continue;
1481
1482             mask = SIN_ADDR(ifreq.ifr_addr);
1483             SYSDEBUG ((LOG_DEBUG, "proxy arp: interface addr %s mask %lx",
1484                         ip_ntoa(ina), ntohl(mask)));
1485
1486             if (((ipaddr ^ ina) & mask) != 0)
1487                 continue;
1488             break;
1489         }
1490     }
1491     
1492     if (ifr >= ifend)
1493         return 0;
1494
1495     strlcpy(name, ifreq.ifr_name, namelen);
1496
1497     /* trim off the :1 in eth0:1 */
1498     aliasp = strchr(name, ':');
1499     if (aliasp != 0)
1500         *aliasp = 0;
1501
1502     info("found interface %s for proxy arp", name);
1503 /*
1504  * Now get the hardware address.
1505  */
1506     memset (&ifreq.ifr_hwaddr, 0, sizeof (struct sockaddr));
1507     if (ioctl (sock_fd, SIOCGIFHWADDR, &ifreq) < 0) {
1508         error("SIOCGIFHWADDR(%s): %m(%d)", ifreq.ifr_name, errno);
1509         return 0;
1510     }
1511
1512     memcpy (hwaddr,
1513             &ifreq.ifr_hwaddr,
1514             sizeof (struct sockaddr));
1515
1516     SYSDEBUG ((LOG_DEBUG,
1517            "proxy arp: found hwaddr %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
1518                 (int) ((unsigned char *) &hwaddr->sa_data)[0],
1519                 (int) ((unsigned char *) &hwaddr->sa_data)[1],
1520                 (int) ((unsigned char *) &hwaddr->sa_data)[2],
1521                 (int) ((unsigned char *) &hwaddr->sa_data)[3],
1522                 (int) ((unsigned char *) &hwaddr->sa_data)[4],
1523                 (int) ((unsigned char *) &hwaddr->sa_data)[5],
1524                 (int) ((unsigned char *) &hwaddr->sa_data)[6],
1525                 (int) ((unsigned char *) &hwaddr->sa_data)[7]));
1526     return 1;
1527 }
1528
1529 /********************************************************************
1530  *
1531  * Return user specified netmask, modified by any mask we might determine
1532  * for address `addr' (in network byte order).
1533  * Here we scan through the system's list of interfaces, looking for
1534  * any non-point-to-point interfaces which might appear to be on the same
1535  * network as `addr'.  If we find any, we OR in their netmask to the
1536  * user-specified netmask.
1537  */
1538
1539 u_int32_t GetMask (u_int32_t addr)
1540 {
1541     u_int32_t mask, nmask, ina;
1542     struct ifreq *ifr, *ifend, ifreq;
1543     struct ifconf ifc;
1544     struct ifreq ifs[MAX_IFS];
1545
1546     addr = ntohl(addr);
1547     
1548     if (IN_CLASSA(addr))        /* determine network mask for address class */
1549         nmask = IN_CLASSA_NET;
1550     else if (IN_CLASSB(addr))
1551             nmask = IN_CLASSB_NET;
1552     else
1553             nmask = IN_CLASSC_NET;
1554     
1555     /* class D nets are disallowed by bad_ip_adrs */
1556     mask = netmask | htonl(nmask);
1557 /*
1558  * Scan through the system's network interfaces.
1559  */
1560     ifc.ifc_len = sizeof(ifs);
1561     ifc.ifc_req = ifs;
1562     if (ioctl(sock_fd, SIOCGIFCONF, &ifc) < 0) {
1563         if ( ! ok_error ( errno ))
1564             warn("ioctl(SIOCGIFCONF): %m(%d)", errno);
1565         return mask;
1566     }
1567     
1568     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
1569     for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
1570 /*
1571  * Check the interface's internet address.
1572  */
1573         if (ifr->ifr_addr.sa_family != AF_INET)
1574             continue;
1575         ina = SIN_ADDR(ifr->ifr_addr);
1576         if (((ntohl(ina) ^ addr) & nmask) != 0)
1577             continue;
1578 /*
1579  * Check that the interface is up, and not point-to-point nor loopback.
1580  */
1581         strlcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
1582         if (ioctl(sock_fd, SIOCGIFFLAGS, &ifreq) < 0)
1583             continue;
1584         
1585         if (((ifreq.ifr_flags ^ FLAGS_GOOD) & FLAGS_MASK) != 0)
1586             continue;
1587 /*
1588  * Get its netmask and OR it into our mask.
1589  */
1590         if (ioctl(sock_fd, SIOCGIFNETMASK, &ifreq) < 0)
1591             continue;
1592         mask |= SIN_ADDR(ifreq.ifr_addr);
1593         break;
1594     }
1595     return mask;
1596 }
1597
1598 /********************************************************************
1599  *
1600  * Internal routine to decode the version.modification.patch level
1601  */
1602
1603 static void decode_version (char *buf, int *version,
1604                             int *modification, int *patch)
1605 {
1606     *version      = (int) strtoul (buf, &buf, 10);
1607     *modification = 0;
1608     *patch        = 0;
1609     
1610     if (*buf == '.') {
1611         ++buf;
1612         *modification = (int) strtoul (buf, &buf, 10);
1613         if (*buf == '.') {
1614             ++buf;
1615             *patch = (int) strtoul (buf, &buf, 10);
1616         }
1617     }
1618     
1619     if (*buf != '\0') {
1620         *version      =
1621         *modification =
1622         *patch        = 0;
1623     }
1624 }
1625
1626 /********************************************************************
1627  *
1628  * Procedure to determine if the PPP line discipline is registered.
1629  */
1630
1631 static int
1632 ppp_registered(void)
1633 {
1634     int local_fd;
1635     int mfd = -1;
1636     int ret = 0;
1637     char slave[16];
1638
1639     /*
1640      * We used to open the serial device and set it to the ppp line
1641      * discipline here, in order to create a ppp unit.  But that is
1642      * not a good idea - the user might have specified a device that
1643      * they can't open (permission, or maybe it doesn't really exist).
1644      * So we grab a pty master/slave pair and use that.
1645      */
1646     if (!get_pty(&mfd, &local_fd, slave, 0)) {
1647         no_ppp_msg = "Couldn't determine if PPP is supported (no free ptys)";
1648         return 0;
1649     }
1650
1651     /*
1652      * Try to put the device into the PPP discipline.
1653      */
1654     if (ioctl(local_fd, TIOCSETD, &ppp_disc) < 0) {
1655         error("ioctl(TIOCSETD(PPP)): %m(%d)", errno);
1656     } else
1657         ret = 1;
1658     
1659     close(local_fd);
1660     close(mfd);
1661     return ret;
1662 }
1663
1664 /********************************************************************
1665  *
1666  * ppp_available - check whether the system has any ppp interfaces
1667  * (in fact we check whether we can do an ioctl on ppp0).
1668  */
1669
1670 int ppp_available(void)
1671 {
1672     int s, ok, fd;
1673     struct ifreq ifr;
1674     int    size;
1675     int    my_version, my_modification, my_patch;
1676     int osmaj, osmin, ospatch;
1677
1678     no_ppp_msg = 
1679         "This system lacks kernel support for PPP.  This could be because\n"
1680         "the PPP kernel module could not be loaded, or because PPP was not\n"
1681         "included in the kernel configuration.  If PPP was included as a\n"
1682         "module, try `/sbin/modprobe -v ppp'.  If that fails, check that\n"
1683         "ppp.o exists in /lib/modules/`uname -r`/net.\n"
1684         "See README.linux file in the ppp distribution for more details.\n";
1685
1686     /* get the kernel version now, since we are called before sys_init */
1687     uname(&utsname);
1688     osmaj = osmin = ospatch = 0;
1689     sscanf(utsname.release, "%d.%d.%d", &osmaj, &osmin, &ospatch);
1690     kernel_version = KVERSION(osmaj, osmin, ospatch);
1691
1692     if (kernel_version >= KVERSION(2,3,13)) {
1693         fd = open("/dev/ppp", O_RDWR);
1694         if (fd < 0 && errno == ENOENT) {
1695             /* try making it and see if that helps. */
1696             if (mknod("/dev/ppp", S_IFCHR | S_IRUSR | S_IWUSR,
1697                       makedev(108, 0)) >= 0) {
1698                 fd = open("/dev/ppp", O_RDWR);
1699                 if (fd >= 0)
1700                     info("Created /dev/ppp device node");
1701                 else
1702                     unlink("/dev/ppp"); /* didn't work, undo the mknod */
1703             } else if (errno == EEXIST) {
1704                 fd = open("/dev/ppp", O_RDWR);
1705             }
1706         }
1707         if (fd >= 0) {
1708             new_style_driver = 1;
1709
1710             /* XXX should get from driver */
1711             driver_version = 2;
1712             driver_modification = 4;
1713             driver_patch = 0;
1714             close(fd);
1715             return 1;
1716         }
1717     }
1718
1719 /*
1720  * Open a socket for doing the ioctl operations.
1721  */    
1722     s = socket(AF_INET, SOCK_DGRAM, 0);
1723     if (s < 0)
1724         return 0;
1725     
1726     strlcpy (ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name));
1727     ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0;
1728 /*
1729  * If the device did not exist then attempt to create one by putting the
1730  * current tty into the PPP discipline. If this works then obtain the
1731  * flags for the device again.
1732  */
1733     if (!ok) {
1734         if (ppp_registered()) {
1735             strlcpy (ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name));
1736             ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0;
1737         }
1738     }
1739 /*
1740  * Ensure that the hardware address is for PPP and not something else
1741  */
1742     if (ok)
1743         ok = ioctl (s, SIOCGIFHWADDR, (caddr_t) &ifr) >= 0;
1744
1745     if (ok && ((ifr.ifr_hwaddr.sa_family & ~0xFF) != ARPHRD_PPP))
1746         ok = 0;
1747
1748 /*
1749  *  This is the PPP device. Validate the version of the driver at this
1750  *  point to ensure that this program will work with the driver.
1751  */
1752     if (ok) {
1753         char   abBuffer [1024];
1754
1755         ifr.ifr_data = abBuffer;
1756         size = ioctl (s, SIOCGPPPVER, (caddr_t) &ifr);
1757         if (size < 0) {
1758             error("Couldn't read driver version: %m");
1759             ok = 0;
1760             no_ppp_msg = "Sorry, couldn't verify kernel driver version\n";
1761
1762         } else {
1763             decode_version(abBuffer,
1764                            &driver_version,
1765                            &driver_modification,
1766                            &driver_patch);
1767 /*
1768  * Validate the version of the driver against the version that we used.
1769  */
1770             decode_version(VERSION,
1771                            &my_version,
1772                            &my_modification,
1773                            &my_patch);
1774
1775             /* The version numbers must match */
1776             if (driver_version != my_version)
1777                 ok = 0;
1778       
1779             /* The modification levels must be legal */
1780             if (driver_modification < 3) {
1781                 if (driver_modification >= 2) {
1782                     /* we can cope with 2.2.0 and above */
1783                     driver_is_old = 1;
1784                 } else {
1785                     ok = 0;
1786                 }
1787             }
1788
1789             close (s);
1790             if (!ok) {
1791                 slprintf(route_buffer, sizeof(route_buffer),
1792                          "Sorry - PPP driver version %d.%d.%d is out of date\n",
1793                          driver_version, driver_modification, driver_patch);
1794
1795                 no_ppp_msg = route_buffer;
1796             }
1797         }
1798     }
1799     return ok;
1800 }
1801
1802 /********************************************************************
1803  *
1804  * Update the wtmp file with the appropriate user name and tty device.
1805  */
1806
1807 void logwtmp (const char *line, const char *name, const char *host)
1808 {
1809     struct utmp ut, *utp;
1810     pid_t  mypid = getpid();
1811 #if __GLIBC__ < 2
1812     int    wtmp;
1813 #endif
1814
1815 /*
1816  * Update the signon database for users.
1817  * Christoph Lameter: Copied from poeigl-1.36 Jan 3, 1996
1818  */
1819     utmpname(_PATH_UTMP);
1820     setutent();
1821     while ((utp = getutent()) && (utp->ut_pid != mypid))
1822         /* nothing */;
1823
1824     /* Is this call really necessary? There is another one after the 'put' */
1825     endutent();
1826     
1827     if (utp)
1828         memcpy(&ut, utp, sizeof(ut));
1829     else
1830         /* some gettys/telnetds don't initialize utmp... */
1831         memset(&ut, 0, sizeof(ut));
1832
1833     if (ut.ut_id[0] == 0)
1834         strncpy(ut.ut_id, line + 3, sizeof(ut.ut_id));
1835         
1836     strncpy(ut.ut_user, name, sizeof(ut.ut_user));
1837     strncpy(ut.ut_line, line, sizeof(ut.ut_line));
1838
1839     time(&ut.ut_time);
1840
1841     ut.ut_type = USER_PROCESS;
1842     ut.ut_pid  = mypid;
1843
1844     /* Insert the host name if one is supplied */
1845     if (*host)
1846         strncpy (ut.ut_host, host, sizeof(ut.ut_host));
1847
1848     /* Insert the IP address of the remote system if IP is enabled */
1849     if (ipcp_protent.enabled_flag && ipcp_hisoptions[0].neg_addr)
1850         memcpy(&ut.ut_addr, (char *) &ipcp_hisoptions[0].hisaddr,
1851                  sizeof(ut.ut_addr));
1852         
1853     /* CL: Makes sure that the logout works */
1854     if (*host == 0 && *name==0)
1855         ut.ut_host[0]=0;
1856
1857     pututline(&ut);
1858     endutent();
1859 /*
1860  * Update the wtmp file.
1861  */
1862 #if __GLIBC__ >= 2
1863     updwtmp(_PATH_WTMP, &ut);
1864 #else
1865     wtmp = open(_PATH_WTMP, O_APPEND|O_WRONLY);
1866     if (wtmp >= 0) {
1867         flock(wtmp, LOCK_EX);
1868
1869         if (write (wtmp, (char *)&ut, sizeof(ut)) != sizeof(ut))
1870             warn("error writing %s: %m", _PATH_WTMP);
1871
1872         flock(wtmp, LOCK_UN);
1873
1874         close (wtmp);
1875     }
1876 #endif
1877 }
1878
1879
1880 /********************************************************************
1881  *
1882  * sifvjcomp - config tcp header compression
1883  */
1884
1885 int sifvjcomp (int u, int vjcomp, int cidcomp, int maxcid)
1886 {
1887     u_int x = get_flags(ppp_dev_fd);
1888
1889     if (vjcomp) {
1890         if (ioctl (ppp_dev_fd, PPPIOCSMAXCID, (caddr_t) &maxcid) < 0) {
1891             if (! ok_error (errno))
1892                 error("ioctl(PPPIOCSMAXCID): %m(%d)", errno);
1893             vjcomp = 0;
1894         }
1895     }
1896
1897     x = vjcomp  ? x | SC_COMP_TCP     : x &~ SC_COMP_TCP;
1898     x = cidcomp ? x & ~SC_NO_TCP_CCID : x | SC_NO_TCP_CCID;
1899     set_flags (ppp_dev_fd, x);
1900
1901     return 1;
1902 }
1903
1904 /********************************************************************
1905  *
1906  * sifup - Config the interface up and enable IP packets to pass.
1907  */
1908
1909 int sifup(int u)
1910 {
1911     struct ifreq ifr;
1912
1913     memset (&ifr, '\0', sizeof (ifr));
1914     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
1915     if (ioctl(sock_fd, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
1916         if (! ok_error (errno))
1917             error("ioctl (SIOCGIFFLAGS): %m(%d)", errno);
1918         return 0;
1919     }
1920
1921     ifr.ifr_flags |= (IFF_UP | IFF_POINTOPOINT);
1922     if (ioctl(sock_fd, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) {
1923         if (! ok_error (errno))
1924             error("ioctl(SIOCSIFFLAGS): %m(%d)", errno);
1925         return 0;
1926     }
1927     if_is_up++;
1928
1929     return 1;
1930 }
1931
1932 /********************************************************************
1933  *
1934  * sifdown - Disable the indicated protocol and config the interface
1935  *           down if there are no remaining protocols.
1936  */
1937
1938 int sifdown (int u)
1939 {
1940     struct ifreq ifr;
1941
1942     if (if_is_up && --if_is_up > 0)
1943         return 1;
1944
1945     memset (&ifr, '\0', sizeof (ifr));
1946     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
1947     if (ioctl(sock_fd, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
1948         if (! ok_error (errno))
1949             error("ioctl (SIOCGIFFLAGS): %m(%d)", errno);
1950         return 0;
1951     }
1952
1953     ifr.ifr_flags &= ~IFF_UP;
1954     ifr.ifr_flags |= IFF_POINTOPOINT;
1955     if (ioctl(sock_fd, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) {
1956         if (! ok_error (errno))
1957             error("ioctl(SIOCSIFFLAGS): %m(%d)", errno);
1958         return 0;
1959     }
1960     return 1;
1961 }
1962
1963 /********************************************************************
1964  *
1965  * sifaddr - Config the interface IP addresses and netmask.
1966  */
1967
1968 int sifaddr (int unit, u_int32_t our_adr, u_int32_t his_adr,
1969              u_int32_t net_mask)
1970 {
1971     struct ifreq   ifr; 
1972     struct rtentry rt;
1973     
1974     memset (&ifr, '\0', sizeof (ifr));
1975     memset (&rt,  '\0', sizeof (rt));
1976     
1977     SET_SA_FAMILY (ifr.ifr_addr,    AF_INET); 
1978     SET_SA_FAMILY (ifr.ifr_dstaddr, AF_INET); 
1979     SET_SA_FAMILY (ifr.ifr_netmask, AF_INET); 
1980
1981     strlcpy (ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
1982 /*
1983  *  Set our IP address
1984  */
1985     SIN_ADDR(ifr.ifr_addr) = our_adr;
1986     if (ioctl(sock_fd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
1987         if (errno != EEXIST) {
1988             if (! ok_error (errno))
1989                 error("ioctl(SIOCSIFADDR): %m(%d)", errno);
1990         }
1991         else {
1992             warn("ioctl(SIOCSIFADDR): Address already exists");
1993         }
1994         return (0);
1995     }
1996 /*
1997  *  Set the gateway address
1998  */
1999     SIN_ADDR(ifr.ifr_dstaddr) = his_adr;
2000     if (ioctl(sock_fd, SIOCSIFDSTADDR, (caddr_t) &ifr) < 0) {
2001         if (! ok_error (errno))
2002             error("ioctl(SIOCSIFDSTADDR): %m(%d)", errno); 
2003         return (0);
2004     } 
2005 /*
2006  *  Set the netmask.
2007  *  For recent kernels, force the netmask to 255.255.255.255.
2008  */
2009     if (kernel_version >= KVERSION(2,1,16))
2010         net_mask = ~0L;
2011     if (net_mask != 0) {
2012         SIN_ADDR(ifr.ifr_netmask) = net_mask;
2013         if (ioctl(sock_fd, SIOCSIFNETMASK, (caddr_t) &ifr) < 0) {
2014             if (! ok_error (errno))
2015                 error("ioctl(SIOCSIFNETMASK): %m(%d)", errno); 
2016             return (0);
2017         } 
2018     }
2019 /*
2020  *  Add the device route
2021  */
2022     if (kernel_version < KVERSION(2,1,16)) {
2023         SET_SA_FAMILY (rt.rt_dst,     AF_INET);
2024         SET_SA_FAMILY (rt.rt_gateway, AF_INET);
2025         rt.rt_dev = ifname;
2026
2027         SIN_ADDR(rt.rt_gateway) = 0L;
2028         SIN_ADDR(rt.rt_dst)     = his_adr;
2029         rt.rt_flags = RTF_UP | RTF_HOST;
2030
2031         if (kernel_version > KVERSION(2,1,0)) {
2032             SET_SA_FAMILY (rt.rt_genmask, AF_INET);
2033             SIN_ADDR(rt.rt_genmask) = -1L;
2034         }
2035
2036         if (ioctl(sock_fd, SIOCADDRT, &rt) < 0) {
2037             if (! ok_error (errno))
2038                 error("ioctl(SIOCADDRT) device route: %m(%d)", errno);
2039             return (0);
2040         }
2041     }
2042
2043     /* set ip_dynaddr in demand mode if address changes */
2044     if (demand && tune_kernel && !dynaddr_set
2045         && our_old_addr && our_old_addr != our_adr) {
2046         /* set ip_dynaddr if possible */
2047         char *path;
2048         int fd;
2049
2050         path = path_to_procfs("/sys/net/ipv4/ip_dynaddr");
2051         if (path != 0 && (fd = open(path, O_WRONLY)) >= 0) {
2052             if (write(fd, "1", 1) != 1)
2053                 error("Couldn't enable dynamic IP addressing: %m");
2054             close(fd);
2055         }
2056         dynaddr_set = 1;        /* only 1 attempt */
2057     }
2058     our_old_addr = 0;
2059
2060     return 1;
2061 }
2062
2063 /********************************************************************
2064  *
2065  * cifaddr - Clear the interface IP addresses, and delete routes
2066  * through the interface if possible.
2067  */
2068
2069 int cifaddr (int unit, u_int32_t our_adr, u_int32_t his_adr)
2070 {
2071     struct ifreq ifr;
2072
2073     if (kernel_version < KVERSION(2,1,16)) {
2074 /*
2075  *  Delete the route through the device
2076  */
2077         struct rtentry rt;
2078         memset (&rt, '\0', sizeof (rt));
2079
2080         SET_SA_FAMILY (rt.rt_dst,     AF_INET);
2081         SET_SA_FAMILY (rt.rt_gateway, AF_INET);
2082         rt.rt_dev = ifname;
2083
2084         SIN_ADDR(rt.rt_gateway) = 0;
2085         SIN_ADDR(rt.rt_dst)     = his_adr;
2086         rt.rt_flags = RTF_UP | RTF_HOST;
2087
2088         if (kernel_version > KVERSION(2,1,0)) {
2089             SET_SA_FAMILY (rt.rt_genmask, AF_INET);
2090             SIN_ADDR(rt.rt_genmask) = -1L;
2091         }
2092
2093         if (ioctl(sock_fd, SIOCDELRT, &rt) < 0 && errno != ESRCH) {
2094             if (still_ppp() && ! ok_error (errno))
2095                 error("ioctl(SIOCDELRT) device route: %m(%d)", errno);
2096             return (0);
2097         }
2098     }
2099
2100     /* This way it is possible to have an IPX-only or IPv6-only interface */
2101     memset(&ifr, 0, sizeof(ifr));
2102     SET_SA_FAMILY(ifr.ifr_addr, AF_INET);
2103     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
2104     
2105     if (ioctl(sock_fd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
2106         if (! ok_error (errno)) {
2107             error("ioctl(SIOCSIFADDR): %m(%d)", errno);
2108             return 0;
2109         }
2110     }
2111
2112     our_old_addr = our_adr;
2113
2114     return 1;
2115 }
2116
2117 #ifdef INET6
2118 /********************************************************************
2119  * 
2120  * sif6addr - Config the interface with an IPv6 link-local address
2121  */
2122 int sif6addr (int unit, eui64_t our_eui64, eui64_t his_eui64)
2123 {
2124     struct in6_ifreq ifr6;
2125     struct ifreq ifr;
2126     struct in6_rtmsg rt6;
2127
2128     memset(&ifr, 0, sizeof (ifr));
2129     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
2130     if (ioctl(sock6_fd, SIOCGIFINDEX, (caddr_t) &ifr) < 0) {
2131         error("sif6addr: ioctl(SIOCGIFINDEX): %m (%d)", errno);
2132         return 0;
2133     }
2134     
2135     /* Local interface */
2136     memset(&ifr6, 0, sizeof(ifr6));
2137     IN6_LLADDR_FROM_EUI64(ifr6.ifr6_addr, our_eui64);
2138     ifr6.ifr6_ifindex = ifr.ifr_ifindex;
2139     ifr6.ifr6_prefixlen = 10;
2140
2141     if (ioctl(sock6_fd, SIOCSIFADDR, &ifr6) < 0) {
2142         error("sif6addr: ioctl(SIOCSIFADDR): %m (%d)", errno);
2143         return 0;
2144     }
2145     
2146     /* Route to remote host */
2147     memset(&rt6, 0, sizeof(rt6));
2148     IN6_LLADDR_FROM_EUI64(rt6.rtmsg_dst, his_eui64);
2149     rt6.rtmsg_flags = RTF_UP;
2150     rt6.rtmsg_dst_len = 10;
2151     rt6.rtmsg_ifindex = ifr.ifr_ifindex;
2152     rt6.rtmsg_metric = 1;
2153     
2154     if (ioctl(sock6_fd, SIOCADDRT, &rt6) < 0) {
2155         error("sif6addr: ioctl(SIOCADDRT): %m (%d)", errno);
2156         return 0;
2157     }
2158
2159     return 1;
2160 }
2161
2162
2163 /********************************************************************
2164  *
2165  * cif6addr - Remove IPv6 address from interface
2166  */
2167 int cif6addr (int unit, eui64_t our_eui64, eui64_t his_eui64)
2168 {
2169     struct ifreq ifr;
2170     struct in6_ifreq ifr6;
2171
2172     memset(&ifr, 0, sizeof(ifr));
2173     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
2174     if (ioctl(sock6_fd, SIOCGIFINDEX, (caddr_t) &ifr) < 0) {
2175         error("cif6addr: ioctl(SIOCGIFINDEX): %m (%d)", errno);
2176         return 0;
2177     }
2178     
2179     memset(&ifr6, 0, sizeof(ifr6));
2180     IN6_LLADDR_FROM_EUI64(ifr6.ifr6_addr, our_eui64);
2181     ifr6.ifr6_ifindex = ifr.ifr_ifindex;
2182     ifr6.ifr6_prefixlen = 10;
2183
2184     if (ioctl(sock6_fd, SIOCDIFADDR, &ifr6) < 0) {
2185         if (errno != EADDRNOTAVAIL) {
2186             if (! ok_error (errno))
2187                 error("cif6addr: ioctl(SIOCDIFADDR): %m (%d)", errno);
2188         }
2189         else {
2190             warn("cif6addr: ioctl(SIOCDIFADDR): No such address");
2191         }
2192         return (0);
2193     }
2194     return 1;
2195 }
2196 #endif /* INET6 */
2197
2198 /*
2199  * get_pty - get a pty master/slave pair and chown the slave side
2200  * to the uid given.  Assumes slave_name points to >= 16 bytes of space.
2201  */
2202 int
2203 get_pty(master_fdp, slave_fdp, slave_name, uid)
2204     int *master_fdp;
2205     int *slave_fdp;
2206     char *slave_name;
2207     int uid;
2208 {
2209     int i, mfd, sfd = -1;
2210     char pty_name[16];
2211     struct termios tios;
2212
2213 #ifdef TIOCGPTN
2214     /*
2215      * Try the unix98 way first.
2216      */
2217     mfd = open("/dev/ptmx", O_RDWR);
2218     if (mfd >= 0) {
2219         int ptn;
2220         if (ioctl(mfd, TIOCGPTN, &ptn) >= 0) {
2221             slprintf(pty_name, sizeof(pty_name), "/dev/pts/%d", ptn);
2222             chmod(pty_name, S_IRUSR | S_IWUSR);
2223 #ifdef TIOCSPTLCK
2224             ptn = 0;
2225             if (ioctl(mfd, TIOCSPTLCK, &ptn) < 0)
2226                 warn("Couldn't unlock pty slave %s: %m", pty_name);
2227 #endif
2228             if ((sfd = open(pty_name, O_RDWR | O_NOCTTY)) < 0)
2229                 warn("Couldn't open pty slave %s: %m", pty_name);
2230         }
2231     }
2232 #endif /* TIOCGPTN */
2233
2234     if (sfd < 0) {
2235         /* the old way - scan through the pty name space */
2236         for (i = 0; i < 64; ++i) {
2237             slprintf(pty_name, sizeof(pty_name), "/dev/pty%c%x",
2238                      'p' + i / 16, i % 16);
2239             mfd = open(pty_name, O_RDWR, 0);
2240             if (mfd >= 0) {
2241                 pty_name[5] = 't';
2242                 sfd = open(pty_name, O_RDWR | O_NOCTTY, 0);
2243                 if (sfd >= 0) {
2244                     fchown(sfd, uid, -1);
2245                     fchmod(sfd, S_IRUSR | S_IWUSR);
2246                     break;
2247                 }
2248                 close(mfd);
2249             }
2250         }
2251     }
2252
2253     if (sfd < 0)
2254         return 0;
2255
2256     strlcpy(slave_name, pty_name, 16);
2257     *master_fdp = mfd;
2258     *slave_fdp = sfd;
2259     if (tcgetattr(sfd, &tios) == 0) {
2260         tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB);
2261         tios.c_cflag |= CS8 | CREAD;
2262         tios.c_iflag  = IGNPAR | CLOCAL;
2263         tios.c_oflag  = 0;
2264         tios.c_lflag  = 0;
2265         if (tcsetattr(sfd, TCSAFLUSH, &tios) < 0)
2266             warn("couldn't set attributes on pty: %m");
2267     } else
2268         warn("couldn't get attributes on pty: %m");
2269
2270     return 1;
2271 }
2272
2273 /********************************************************************
2274  *
2275  * open_loopback - open the device we use for getting packets
2276  * in demand mode.  Under Linux, we use a pty master/slave pair.
2277  */
2278 int
2279 open_ppp_loopback(void)
2280 {
2281     int flags;
2282
2283     looped = 1;
2284     if (new_style_driver) {
2285         /* allocate ourselves a ppp unit */
2286         ifunit = -1;
2287         if (ioctl(ppp_dev_fd, PPPIOCNEWUNIT, &ifunit) < 0)
2288             fatal("Couldn't create PPP unit: %m");
2289         set_flags(ppp_dev_fd, SC_LOOP_TRAFFIC);
2290         set_kdebugflag(kdebugflag);
2291         ppp_fd = -1;
2292         return ppp_dev_fd;
2293     }
2294
2295     if (!get_pty(&master_fd, &slave_fd, loop_name, 0))
2296         fatal("No free pty for loopback");
2297     SYSDEBUG(("using %s for loopback", loop_name));
2298
2299     set_ppp_fd(slave_fd);
2300
2301     flags = fcntl(master_fd, F_GETFL);
2302     if (flags == -1 ||
2303         fcntl(master_fd, F_SETFL, flags | O_NONBLOCK) == -1)
2304         warn("couldn't set master loopback to nonblock: %m(%d)", errno);
2305
2306     flags = fcntl(ppp_fd, F_GETFL);
2307     if (flags == -1 ||
2308         fcntl(ppp_fd, F_SETFL, flags | O_NONBLOCK) == -1)
2309         warn("couldn't set slave loopback to nonblock: %m(%d)", errno);
2310
2311     if (ioctl(ppp_fd, TIOCSETD, &ppp_disc) < 0)
2312         fatal("ioctl(TIOCSETD): %m(%d)", errno);
2313 /*
2314  * Find out which interface we were given.
2315  */
2316     if (ioctl(ppp_fd, PPPIOCGUNIT, &ifunit) < 0)
2317         fatal("ioctl(PPPIOCGUNIT): %m(%d)", errno);
2318 /*
2319  * Enable debug in the driver if requested.
2320  */
2321     set_kdebugflag (kdebugflag);
2322
2323     return master_fd;
2324 }
2325
2326 /********************************************************************
2327  *
2328  * restore_loop - reattach the ppp unit to the loopback.
2329  *
2330  * The kernel ppp driver automatically reattaches the ppp unit to
2331  * the loopback if the serial port is set to a line discipline other
2332  * than ppp, or if it detects a modem hangup.  The former will happen
2333  * in disestablish_ppp if the latter hasn't already happened, so we
2334  * shouldn't need to do anything.
2335  *
2336  * Just to be sure, set the real serial port to the normal discipline.
2337  */
2338
2339 void
2340 restore_loop(void)
2341 {
2342     looped = 1;
2343     if (new_style_driver) {
2344         set_flags(ppp_dev_fd, get_flags(ppp_dev_fd) | SC_LOOP_TRAFFIC);
2345         return;
2346     }
2347     if (ppp_fd != slave_fd) {
2348         (void) ioctl(ppp_fd, TIOCSETD, &tty_disc);
2349         set_ppp_fd(slave_fd);
2350     }
2351 }
2352
2353 /********************************************************************
2354  *
2355  * sifnpmode - Set the mode for handling packets for a given NP.
2356  */
2357
2358 int
2359 sifnpmode(u, proto, mode)
2360     int u;
2361     int proto;
2362     enum NPmode mode;
2363 {
2364     struct npioctl npi;
2365
2366     npi.protocol = proto;
2367     npi.mode     = mode;
2368     if (ioctl(ppp_dev_fd, PPPIOCSNPMODE, (caddr_t) &npi) < 0) {
2369         if (! ok_error (errno))
2370             error("ioctl(PPPIOCSNPMODE, %d, %d): %m (%d)",
2371                    proto, mode, errno);
2372         return 0;
2373     }
2374     return 1;
2375 }
2376
2377 \f
2378 /********************************************************************
2379  *
2380  * sipxfaddr - Config the interface IPX networknumber
2381  */
2382
2383 int sipxfaddr (int unit, unsigned long int network, unsigned char * node )
2384 {
2385     int    result = 1;
2386
2387 #ifdef IPX_CHANGE
2388     int    skfd; 
2389     struct ifreq         ifr;
2390     struct sockaddr_ipx *sipx = (struct sockaddr_ipx *) &ifr.ifr_addr;
2391
2392     skfd = socket (AF_IPX, SOCK_DGRAM, 0);
2393     if (skfd < 0) { 
2394         if (! ok_error (errno))
2395             dbglog("socket(AF_IPX): %m (%d)", errno);
2396         result = 0;
2397     }
2398     else {
2399         memset (&ifr, '\0', sizeof (ifr));
2400         strlcpy (ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
2401
2402         memcpy (sipx->sipx_node, node, IPX_NODE_LEN);
2403         sipx->sipx_family  = AF_IPX;
2404         sipx->sipx_port    = 0;
2405         sipx->sipx_network = htonl (network);
2406         sipx->sipx_type    = IPX_FRAME_ETHERII;
2407         sipx->sipx_action  = IPX_CRTITF;
2408 /*
2409  *  Set the IPX device
2410  */
2411         if (ioctl(skfd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
2412             result = 0;
2413             if (errno != EEXIST) {
2414                 if (! ok_error (errno))
2415                     dbglog("ioctl(SIOCSIFADDR, CRTITF): %m (%d)", errno);
2416             }
2417             else {
2418                 warn("ioctl(SIOCSIFADDR, CRTITF): Address already exists");
2419             }
2420         }
2421         close (skfd);
2422     }
2423 #endif
2424     return result;
2425 }
2426
2427 /********************************************************************
2428  *
2429  * cipxfaddr - Clear the information for the IPX network. The IPX routes
2430  *             are removed and the device is no longer able to pass IPX
2431  *             frames.
2432  */
2433
2434 int cipxfaddr (int unit)
2435 {
2436     int    result = 1;
2437
2438 #ifdef IPX_CHANGE
2439     int    skfd; 
2440     struct ifreq         ifr;
2441     struct sockaddr_ipx *sipx = (struct sockaddr_ipx *) &ifr.ifr_addr;
2442
2443     skfd = socket (AF_IPX, SOCK_DGRAM, 0);
2444     if (skfd < 0) { 
2445         if (! ok_error (errno))
2446             dbglog("socket(AF_IPX): %m (%d)", errno);
2447         result = 0;
2448     }
2449     else {
2450         memset (&ifr, '\0', sizeof (ifr));
2451         strlcpy (ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
2452
2453         sipx->sipx_type    = IPX_FRAME_ETHERII;
2454         sipx->sipx_action  = IPX_DLTITF;
2455         sipx->sipx_family  = AF_IPX;
2456 /*
2457  *  Set the IPX device
2458  */
2459         if (ioctl(skfd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
2460             if (! ok_error (errno))
2461                 info("ioctl(SIOCSIFADDR, IPX_DLTITF): %m (%d)", errno);
2462             result = 0;
2463         }
2464         close (skfd);
2465     }
2466 #endif
2467     return result;
2468 }
2469
2470 /*
2471  * Use the hostname as part of the random number seed.
2472  */
2473 int
2474 get_host_seed()
2475 {
2476     int h;
2477     char *p = hostname;
2478
2479     h = 407;
2480     for (p = hostname; *p != 0; ++p)
2481         h = h * 37 + *p;
2482     return h;
2483 }
2484
2485 /********************************************************************
2486  *
2487  * sys_check_options - check the options that the user specified
2488  */
2489
2490 int
2491 sys_check_options(void)
2492 {
2493 #ifdef IPX_CHANGE
2494 /*
2495  * Disable the IPX protocol if the support is not present in the kernel.
2496  */
2497     char *path;
2498
2499     if (ipxcp_protent.enabled_flag) {
2500         struct stat stat_buf;
2501         if ((path = path_to_procfs("/net/ipx_interface")) == 0
2502             || lstat(path, &stat_buf) < 0) {
2503             error("IPX support is not present in the kernel\n");
2504             ipxcp_protent.enabled_flag = 0;
2505         }
2506     }
2507 #endif
2508     if (demand && driver_is_old) {
2509         option_error("demand dialling is not supported by kernel driver "
2510                      "version %d.%d.%d", driver_version, driver_modification,
2511                      driver_patch);
2512         return 0;
2513     }
2514     return 1;
2515 }