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