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