]> git.ozlabs.org Git - ppp.git/blob - pppd/sys-osf.c
94b3dd2576d41902d54aad8c17cfec28dc4cb640
[ppp.git] / pppd / sys-osf.c
1 /*
2  * System-dependent procedures for pppd under Digital UNIX (OSF/1).
3  *
4  * Copyright (c) 1994 The Australian National University.
5  * All rights reserved.
6  *
7  * Permission to use, copy, modify, and distribute this software and its
8  * documentation is hereby granted, provided that the above copyright
9  * notice appears in all copies.  This software is provided without any
10  * warranty, express or implied. The Australian National University
11  * makes no representations about the suitability of this software for
12  * any purpose.
13  *
14  * IN NO EVENT SHALL THE AUSTRALIAN NATIONAL UNIVERSITY BE LIABLE TO ANY
15  * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
16  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
17  * THE AUSTRALIAN NATIONAL UNIVERSITY HAVE BEEN ADVISED OF THE POSSIBILITY
18  * OF SUCH DAMAGE.
19  *
20  * THE AUSTRALIAN NATIONAL UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
21  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
23  * ON AN "AS IS" BASIS, AND THE AUSTRALIAN NATIONAL UNIVERSITY HAS NO
24  * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
25  * OR MODIFICATIONS.
26  */
27
28 #ifndef lint
29 static char rcsid[] = "$Id: sys-osf.c,v 1.23 1999/03/22 05:55:38 paulus Exp $";
30 #endif
31
32 #include <stdio.h>
33 #include <stddef.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <unistd.h>
40 #include <termios.h>
41 #include <signal.h>
42 #include <malloc.h>
43 #include <utmp.h>
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/socket.h>
47 #include <sys/stream.h>
48 #include <sys/stropts.h>
49 #include <sys/stat.h>
50 #include <sys/time.h>
51 #include <sys/poll.h>
52 #include <sys/ioctl.h>
53 #include <net/if.h>
54 #include <net/if_dl.h>
55 #include <net/if_arp.h>
56 #include <net/route.h>
57 #include <net/ppp_defs.h>
58 #include <net/pppio.h>
59 #include <netinet/in.h>
60 #include <arpa/inet.h>
61
62 #include "pppd.h"
63
64 static int      pppfd;
65 static int      fdmuxid = -1;
66 static int      iffd;
67 static int      sockfd;
68
69 static int      restore_term;
70 static struct termios inittermios;
71 static struct winsize wsinfo;   /* Initial window size info */
72 static pid_t    tty_sid;        /* PID of our session leader */
73
74 extern u_char   inpacket_buf[]; /* borrowed from main.c */
75
76 static int      link_mtu, link_mru;
77
78 #define NMODULES        32
79 static int      tty_nmodules;
80 static char     tty_modules[NMODULES][FMNAMESZ+1];
81
82 static int closed_stdio;
83 static int initfdflags = -1;
84 static int orig_ttyfd = -1;
85
86 static int      if_is_up;       /* Interface has been marked up */
87 static u_int32_t ifaddrs[2];    /* local and remote addresses */
88 static u_int32_t default_route_gateway; /* Gateway for default route added */
89 static u_int32_t proxy_arp_addr;        /* Addr for proxy arp entry added */
90
91 #define MAX_POLLFDS     32
92 static struct pollfd pollfds[MAX_POLLFDS];
93 static int n_pollfds;
94
95 /* Prototypes for procedures local to this file. */
96 static int translate_speed __P((int));
97 static int baud_rate_of __P((int));
98 static int get_ether_addr __P((u_int32_t, struct sockaddr *));
99 static int strioctl __P((int, int, void *, int, int));
100
101
102 /*
103  * sys_init - System-dependent initialization.
104  */
105 void
106 sys_init()
107 {
108     int x;
109
110     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
111     setlogmask(LOG_UPTO(LOG_INFO));
112     if (debug)
113         setlogmask(LOG_UPTO(LOG_DEBUG));
114
115     /* Get an internet socket for doing socket ioctl's on. */
116     if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
117         fatal("Couldn't create IP socket: %m");
118
119     if (default_device)
120         tty_sid = getsid((pid_t)0);
121
122     /*
123      * Open the ppp device.
124      */
125     pppfd = open("/dev/streams/ppp", O_RDWR | O_NONBLOCK, 0);
126     if (pppfd < 0)
127         fatal("Can't open /dev/streams/ppp: %m");
128     if (kdebugflag) {
129         x = PPPDBG_LOG + PPPDBG_DRIVER;
130         strioctl(pppfd, PPPIO_DEBUG, &x, sizeof(int), 0);
131     }
132
133     /* Assign a new PPA and get its unit number. */
134     if (strioctl(pppfd, PPPIO_NEWPPA, &ifunit, 0, sizeof(int)) < 0)
135         fatal("Can't create new PPP interface: %m");
136
137     /*
138      * Open the ppp device again and push the if_ppp module on it.
139      */
140     iffd = open("/dev/streams/ppp", O_RDWR, 0);
141     if (iffd < 0)
142         fatal("Can't open /dev/streams/ppp (2): %m");
143     if (kdebugflag) {
144         x = PPPDBG_LOG + PPPDBG_DRIVER;
145         strioctl(iffd, PPPIO_DEBUG, &x, sizeof(int), 0);
146     }
147     if (strioctl(iffd, PPPIO_ATTACH, &ifunit, sizeof(int), 0) < 0)
148         fatal("Couldn't attach ppp interface to device: %m");
149     if (ioctl(iffd, I_PUSH, "if_ppp") < 0)
150         fatal("Can't push ppp interface module: %m");
151     if (kdebugflag) {
152         x = PPPDBG_LOG + PPPDBG_IF;
153         strioctl(iffd, PPPIO_DEBUG, &x, sizeof(int), 0);
154     }
155     if (strioctl(iffd, PPPIO_NEWPPA, &ifunit, sizeof(int), 0) < 0)
156         fatal("Couldn't create ppp interface unit: %m");
157     x = PPP_IP;
158     if (strioctl(iffd, PPPIO_BIND, &x, sizeof(int), 0) < 0)
159         fatal("Couldn't bind ppp interface to IP SAP: %m");
160
161     n_pollfds = 0;
162 }
163
164 /*
165  * sys_cleanup - restore any system state we modified before exiting:
166  * mark the interface down, delete default route and/or proxy arp entry.
167  * This shouldn't call die() because it's called from die().
168  */
169 void
170 sys_cleanup()
171 {
172     if (if_is_up)
173         sifdown(0);
174     if (ifaddrs[0])
175         cifaddr(0, ifaddrs[0], ifaddrs[1]);
176     if (default_route_gateway)
177         cifdefaultroute(0, 0, default_route_gateway);
178     if (proxy_arp_addr)
179         cifproxyarp(0, proxy_arp_addr);
180 }
181
182 /*
183  * sys_close - Clean up in a child process before execing.
184  */
185 void
186 sys_close()
187 {
188     close(iffd);
189     close(pppfd);
190     close(sockfd);
191     closelog();
192 }
193
194 /*
195  * sys_check_options - check the options that the user specified
196  */
197 int
198 sys_check_options()
199 {
200     return 1;
201 }
202
203
204 /*
205  * daemon - Detach us from controlling terminal session.
206  */
207 int
208 daemon(nochdir, noclose)
209     int nochdir, noclose;
210 {
211     int pid;
212
213     if ((pid = fork()) < 0)
214         return -1;
215     if (pid != 0)
216         exit(0);                /* parent dies */
217     setsid();
218     if (!nochdir)
219         chdir("/");
220     if (!noclose) {
221         fclose(stdin);          /* don't need stdin, stdout, stderr */
222         fclose(stdout);
223         fclose(stderr);
224     }
225     return 0;
226 }
227
228 /*
229  * ppp_available - check whether the system has any ppp interfaces
230  */
231 int
232 ppp_available()
233 {
234     struct stat buf;
235
236     return stat("/dev/streams/ppp", &buf) >= 0;
237 }
238
239 char pipename[] = "/dev/streams/pipe";
240
241 /*
242  *  streampipe -- Opens a STREAMS based pipe.  Used by streamify().
243  */
244
245 int 
246 streampipe(int fd[2])
247 {
248     if ((fd[0]=open(pipename, O_RDWR)) == -1)
249         return(-1);
250     else if ((fd[1]=open(pipename, O_RDWR)) == -1) {
251         close(fd[0]);
252         return(-1);
253     } else if (ioctl(fd[0], I_PIPE, fd[1]) != 0) {
254         close(fd[0]);
255         close(fd[1]);
256         return(-1);
257     } else {
258         return(ioctl(fd[0], I_PUSH, "pipemod"));
259     }
260 }
261
262 /*
263  *  streamify -- Needed for Digital UNIX, since some tty devices are not STREAMS
264  *               modules (but ptys are, and pipes can be).
265  */
266
267 #define BUFFSIZE 1000     /*  Size of buffer for streamify()  */
268
269 int 
270 streamify(int fd)
271 {
272     int fdes[2];
273     fd_set readfds;
274     int ret, fret, rret, maxfd;
275     static char buffer[BUFFSIZE];
276     struct sigaction sa;
277
278     if (streampipe(fdes) != 0)
279         error("streampipe(): %m\n");
280     else if (isastream(fdes[0]) == 1) {
281         if ((fret=fork()) < 0) {
282             error("fork(): %m\n");
283         } else if (fret == 0) {
284             /*  Process to forward things from pipe to tty  */
285             sigemptyset(&(sa.sa_mask));
286             sa.sa_handler = SIG_DFL;
287             sa.sa_flags = 0;
288             sigaction(SIGHUP, &sa, NULL);   /*  Go back to default actions */
289             sigaction(SIGINT, &sa, NULL);   /*  for changed signals.  */
290             sigaction(SIGTERM, &sa, NULL);
291             sigaction(SIGCHLD, &sa, NULL);
292             sigaction(SIGUSR1, &sa, NULL);
293             sigaction(SIGUSR2, &sa, NULL);
294             close(fdes[0]);
295
296             maxfd = (fdes[1]>fd)?fdes[1]:fd;
297             while (1) {
298                 FD_ZERO(&readfds);
299                 FD_SET(fdes[1], &readfds);
300                 FD_SET(fd, &readfds);
301                 ret = select(maxfd+1, &readfds, NULL, NULL, NULL);
302                 if (FD_ISSET(fd, &readfds)) {
303                     rret = read(fd, buffer, BUFFSIZE);
304                     if (rret == 0) {
305                         SYSDEBUG(("slave died:  EOF on tty."));
306                         exit(0);
307                     } else {
308                         write(fdes[1], buffer, rret);
309                     }
310                 }
311                 if (FD_ISSET(fdes[1], &readfds)) {
312                     rret = read(fdes[1], buffer, BUFFSIZE);
313                     if (rret == 0) {
314                         SYSDEBUG(("slave died:  EOF on pipe."));
315                         exit(0);
316                     } else {
317                         write(fd, buffer, rret);
318                     }
319                 }
320             }
321         } else {
322             close(fdes[1]);
323             orig_ttyfd = fd;
324             return(fdes[0]);
325         }
326     }
327
328     return(-1);
329 }
330
331 /*
332  * establish_ppp - Turn the serial port into a ppp interface.
333  */
334 int
335 establish_ppp(fd)
336     int fd;
337 {
338     int i;
339
340     if (isastream(fd) != 1) {
341         if ((ttyfd = fd = streamify(fd)) < 0)
342             fatal("Couldn't get a STREAMS module!\n");
343     }
344
345     /* Pop any existing modules off the tty stream. */
346     for (i = 0;; ++i) {
347         if (ioctl(fd, I_LOOK, tty_modules[i]) < 0
348             || ioctl(fd, I_POP, 0) < 0)
349             break;
350         error("popping module %s\n", tty_modules[i]);
351     }
352
353     tty_nmodules = i;
354
355     /* Push the async hdlc module and the compressor module. */
356     if (ioctl(fd, I_PUSH, "ppp_ahdl") < 0)
357         fatal("Couldn't push PPP Async HDLC module: %m");
358     if (ioctl(fd, I_PUSH, "ppp_comp") < 0)
359         error("Couldn't push PPP compression module: %m");
360
361     /* read mode, message non-discard mode */
362     if (ioctl(fd, I_SRDOPT, RMSGN|RPROTNORM) < 0)
363         fatal("ioctl(I_SRDOPT, RMSGN): %m");
364
365     /* Link the serial port under the PPP multiplexor. */
366     if ((fdmuxid = ioctl(pppfd, I_LINK, fd)) < 0)
367         fatal("Can't link tty to PPP mux: %m");
368
369     /* close stdin, stdout, stderr if they might refer to the device */
370     if (default_device && !closed_stdio) {
371         int i;
372
373         for (i = 0; i <= 2; ++i)
374             if (i != fd && i != sockfd)
375                 close(i);
376         closed_stdio = 1;
377     }
378
379     /*
380      * Set device for non-blocking reads.
381      * XXX why do we need to do this?  don't we use pppfd not fd?
382      */
383     if ((initfdflags = fcntl(fd, F_GETFL)) == -1
384         || fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
385         warn("Couldn't set device to non-blocking mode: %m");
386     }
387
388     return pppfd;
389 }
390
391 /*
392  * restore_loop - reattach the ppp unit to the loopback.
393  * This doesn't need to do anything because disestablish_ppp does it.
394  */
395 void
396 restore_loop()
397 {
398 }
399
400 /*
401  * disestablish_ppp - Restore the serial port to normal operation.
402  * It attempts to reconstruct the stream with the previously popped
403  * modules.  This shouldn't call die() because it's called from die().
404  */
405 void
406 disestablish_ppp(fd)
407     int fd;
408 {
409     int i;
410
411     if (fdmuxid >= 0) {
412         if (ioctl(pppfd, I_UNLINK, fdmuxid) < 0) {
413             if (!hungup)
414                 error("Can't unlink tty from PPP mux: %m");
415         }
416         fdmuxid = -1;
417
418         /* Reset non-blocking mode on the file descriptor. */
419         if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
420             warn("Couldn't restore device fd flags: %m");
421         initfdflags = -1;
422
423         if (!hungup) {
424             while (ioctl(fd, I_POP, 0) >= 0)
425                 ;
426             for (i = tty_nmodules - 1; i >= 0; --i)
427                 if (ioctl(fd, I_PUSH, tty_modules[i]) < 0)
428                     error("Couldn't restore tty module %s: %m",
429                            tty_modules[i]);
430         }
431
432         if (hungup && default_device && tty_sid > 0) {
433             /*
434              * If we have received a hangup, we need to send a SIGHUP
435              * to the terminal's controlling process.  The reason is
436              * that the original stream head for the terminal hasn't
437              * seen the M_HANGUP message (it went up through the ppp
438              * driver to the stream head for our fd to /dev/ppp).
439              */
440             dbglog("sending hangup to %d", tty_sid);
441             if (kill(tty_sid, SIGHUP) < 0)
442                 error("couldn't kill pgrp: %m");
443         }
444         if (orig_ttyfd >= 0) {
445             close(fd);
446             (void)wait((void *)0);
447             ttyfd = orig_ttyfd;
448             orig_ttyfd = -1;
449         }
450     }
451 }
452
453 /*
454  * Check whether the link seems not to be 8-bit clean.
455  */
456 void
457 clean_check()
458 {
459     int x;
460     char *s;
461
462     if (strioctl(pppfd, PPPIO_GCLEAN, &x, 0, sizeof(x)) < 0)
463         return;
464     s = NULL;
465     switch (~x) {
466     case RCV_B7_0:
467         s = "bit 7 set to 1";
468         break;
469     case RCV_B7_1:
470         s = "bit 7 set to 0";
471         break;
472     case RCV_EVNP:
473         s = "odd parity";
474         break;
475     case RCV_ODDP:
476         s = "even parity";
477         break;
478     }
479     if (s != NULL) {
480         warn("Serial link is not 8-bit clean:");
481         warn("All received characters had %s", s);
482     }
483 }
484
485 /*
486  * List of valid speeds.
487  */
488 struct speed {
489     int speed_int, speed_val;
490 } speeds[] = {
491 #ifdef B50
492     { 50, B50 },
493 #endif
494 #ifdef B75
495     { 75, B75 },
496 #endif
497 #ifdef B110
498     { 110, B110 },
499 #endif
500 #ifdef B134
501     { 134, B134 },
502 #endif
503 #ifdef B150
504     { 150, B150 },
505 #endif
506 #ifdef B200
507     { 200, B200 },
508 #endif
509 #ifdef B300
510     { 300, B300 },
511 #endif
512 #ifdef B600
513     { 600, B600 },
514 #endif
515 #ifdef B1200
516     { 1200, B1200 },
517 #endif
518 #ifdef B1800
519     { 1800, B1800 },
520 #endif
521 #ifdef B2000
522     { 2000, B2000 },
523 #endif
524 #ifdef B2400
525     { 2400, B2400 },
526 #endif
527 #ifdef B3600
528     { 3600, B3600 },
529 #endif
530 #ifdef B4800
531     { 4800, B4800 },
532 #endif
533 #ifdef B7200
534     { 7200, B7200 },
535 #endif
536 #ifdef B9600
537     { 9600, B9600 },
538 #endif
539 #ifdef B19200
540     { 19200, B19200 },
541 #endif
542 #ifdef B38400
543     { 38400, B38400 },
544 #endif
545 #ifdef EXTA
546     { 19200, EXTA },
547 #endif
548 #ifdef EXTB
549     { 38400, EXTB },
550 #endif
551 #ifdef B57600
552     { 57600, B57600 },
553 #endif
554 #ifdef B115200
555     { 115200, B115200 },
556 #endif
557     { 0, 0 }
558 };
559
560 /*
561  * Translate from bits/second to a speed_t.
562  */
563 static int
564 translate_speed(bps)
565     int bps;
566 {
567     struct speed *speedp;
568
569     if (bps == 0)
570         return 0;
571     for (speedp = speeds; speedp->speed_int; speedp++)
572         if (bps == speedp->speed_int)
573             return speedp->speed_val;
574     warn("speed %d not supported", bps);
575     return 0;
576 }
577
578 /*
579  * Translate from a speed_t to bits/second.
580  */
581 static int
582 baud_rate_of(speed)
583     int speed;
584 {
585     struct speed *speedp;
586
587     if (speed == 0)
588         return 0;
589     for (speedp = speeds; speedp->speed_int; speedp++)
590         if (speed == speedp->speed_val)
591             return speedp->speed_int;
592     return 0;
593 }
594
595 /*
596  * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
597  * at the requested speed, etc.  If `local' is true, set CLOCAL
598  * regardless of whether the modem option was specified.
599  */
600 void
601 set_up_tty(fd, local)
602     int fd, local;
603 {
604     int speed;
605     struct termios tios;
606
607     if (tcgetattr(fd, &tios) < 0)
608         fatal("tcgetattr: %m");
609
610     if (!restore_term) {
611         inittermios = tios;
612         ioctl(fd, TIOCGWINSZ, &wsinfo);
613     }
614
615     tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
616     if (crtscts > 0)
617         tios.c_cflag |= CRTSCTS;
618     else if (crtscts < 0)
619         tios.c_cflag &= ~CRTSCTS;
620
621     tios.c_cflag |= CS8 | CREAD | HUPCL;
622     if (local || !modem)
623         tios.c_cflag |= CLOCAL;
624     tios.c_iflag = IGNBRK | IGNPAR;
625     tios.c_oflag = 0;
626     tios.c_lflag = 0;
627     tios.c_cc[VMIN] = 1;
628     tios.c_cc[VTIME] = 0;
629
630     if (crtscts == -2) {
631         tios.c_iflag |= IXON | IXOFF;
632         tios.c_cc[VSTOP] = 0x13;        /* DC3 = XOFF = ^S */
633         tios.c_cc[VSTART] = 0x11;       /* DC1 = XON  = ^Q */
634     }
635
636     speed = translate_speed(inspeed);
637     if (speed) {
638         cfsetospeed(&tios, speed);
639         cfsetispeed(&tios, speed);
640     } else {
641         speed = cfgetospeed(&tios);
642         /*
643          * We can't proceed if the serial port speed is 0,
644          * since that implies that the serial port is disabled.
645          */
646         if (speed == B0)
647             fatal("Baud rate for %s is 0; need explicit baud rate", devnam);
648     }
649
650     if (tcsetattr(fd, TCSAFLUSH, &tios) < 0)
651         fatal("tcsetattr: %m");
652
653     baud_rate = inspeed = baud_rate_of(speed);
654     restore_term = 1;
655 }
656
657 /*
658  * restore_tty - restore the terminal to the saved settings.
659  */
660 void
661 restore_tty(fd)
662     int fd;
663 {
664     if (restore_term) {
665         if (!default_device) {
666             /*
667              * Turn off echoing, because otherwise we can get into
668              * a loop with the tty and the modem echoing to each other.
669              * We presume we are the sole user of this tty device, so
670              * when we close it, it will revert to its defaults anyway.
671              */
672             inittermios.c_lflag &= ~(ECHO | ECHONL);
673         }
674         if (tcsetattr(fd, TCSAFLUSH, &inittermios) < 0)
675             if (!hungup && errno != ENXIO)
676                 warn("tcsetattr: %m");
677         ioctl(fd, TIOCSWINSZ, &wsinfo);
678         restore_term = 0;
679     }
680 }
681
682 /*
683  * setdtr - control the DTR line on the serial port.
684  * This is called from die(), so it shouldn't call die().
685  */
686 void
687 setdtr(fd, on)
688 int fd, on;
689 {
690     int modembits = TIOCM_DTR;
691
692     ioctl(fd, (on? TIOCMBIS: TIOCMBIC), &modembits);
693 }
694
695 /*
696  * open_loopback - open the device we use for getting packets
697  * in demand mode.  Under Digital Unix, we use our existing fd
698  * to the ppp driver.
699  */
700 int
701 open_ppp_loopback()
702 {
703     return pppfd;
704 }
705
706 /*
707  * output - Output PPP packet.
708  */
709 void
710 output(unit, p, len)
711     int unit;
712     u_char *p;
713     int len;
714 {
715     struct strbuf data;
716     int retries;
717     struct pollfd pfd;
718
719     if (debug)
720         dbglog("sent %P", p, len);
721
722     data.len = len;
723     data.buf = (caddr_t) p;
724     retries = 4;
725     while (putmsg(pppfd, NULL, &data, 0) < 0) {
726         if (--retries < 0 || (errno != EWOULDBLOCK && errno != EAGAIN)) {
727             if (errno != ENXIO)
728                 error("Couldn't send packet: %m");
729             break;
730         }
731         pfd.fd = pppfd;
732         pfd.events = POLLOUT;
733         poll(&pfd, 1, 250);     /* wait for up to 0.25 seconds */
734     }
735 }
736
737
738 /*
739  * wait_input - wait until there is data available on fd,
740  * for the length of time specified by *timo (indefinite
741  * if timo is NULL).
742  */
743 void
744 wait_input(timo)
745     struct timeval *timo;
746 {
747     int t;
748
749     t = timo == NULL? -1: timo->tv_sec * 1000 + timo->tv_usec / 1000;
750     if (poll(pollfds, n_pollfds, t) < 0 && errno != EINTR)
751         fatal("poll: %m");
752 }
753
754 /*
755  * add_fd - add an fd to the set that wait_input waits for.
756  */
757 void add_fd(fd)
758     int fd;
759 {
760     int n;
761
762     for (n = 0; n < n_pollfds; ++n)
763         if (pollfds[n].fd == fd)
764             return;
765     if (n_pollfds < MAX_POLLFDS) {
766         pollfds[n_pollfds].fd = fd;
767         pollfds[n_pollfds].events = POLLIN | POLLPRI | POLLHUP;
768         ++n_pollfds;
769     } else
770         error("Too many inputs!");
771 }
772
773 /*
774  * remove_fd - remove an fd from the set that wait_input waits for.
775  */
776 void remove_fd(fd)
777     int fd;
778 {
779     int n;
780
781     for (n = 0; n < n_pollfds; ++n) {
782         if (pollfds[n].fd == fd) {
783             while (++n < n_pollfds)
784                 pollfds[n-1] = pollfds[n];
785             --n_pollfds;
786             break;
787         }
788     }
789 }
790
791 #if 0
792 /*
793  * wait_loop_output - wait until there is data available on the
794  * loopback, for the length of time specified by *timo (indefinite
795  * if timo is NULL).
796  */
797 void
798 wait_loop_output(timo)
799     struct timeval *timo;
800 {
801     wait_input(timo);
802 }
803
804 /*
805  * wait_time - wait for a given length of time or until a
806  * signal is received.
807  */
808 void
809 wait_time(timo)
810     struct timeval *timo;
811 {
812     int n;
813
814     n = select(0, NULL, NULL, NULL, timo);
815     if (n < 0 && errno != EINTR)
816         fatal("select: %m");
817 }
818 #endif
819
820 /*
821  * read_packet - get a PPP packet from the serial device.
822  */
823 int
824 read_packet(buf)
825     u_char *buf;
826 {
827     struct strbuf ctrl, data;
828     int flags, len;
829     unsigned char ctrlbuf[64];
830
831     for (;;) {
832         data.maxlen = PPP_MRU + PPP_HDRLEN;
833         data.buf = (caddr_t) buf;
834         ctrl.maxlen = sizeof(ctrlbuf);
835         ctrl.buf = (caddr_t) ctrlbuf;
836         flags = 0;
837         len = getmsg(pppfd, &ctrl, &data, &flags);
838         if (len < 0) {
839             if (errno = EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
840                 return -1;
841             fatal("Error reading packet: %m");
842         }
843
844         if (ctrl.len <= 0)
845             return data.len;
846
847         /*
848          * Got a M_PROTO or M_PCPROTO message.  Huh?
849          */
850         if (debug)
851             dbglog("got ctrl msg len=%d", ctrl.len);
852
853     }
854 }
855
856 /*
857  * get_loop_output - get outgoing packets from the ppp device,
858  * and detect when we want to bring the real link up.
859  * Return value is 1 if we need to bring up the link, 0 otherwise.
860  */
861 int
862 get_loop_output()
863 {
864     int len;
865     int rv = 0;
866
867     while ((len = read_packet(inpacket_buf)) > 0) {
868         if (loop_frame(inpacket_buf, len))
869             rv = 1;
870     }
871     return rv;
872 }
873
874 /*
875  * ppp_send_config - configure the transmit characteristics of
876  * the ppp interface.
877  */
878 void
879 ppp_send_config(unit, mtu, asyncmap, pcomp, accomp)
880     int unit, mtu;
881     u_int32_t asyncmap;
882     int pcomp, accomp;
883 {
884     int cf[2];
885
886     link_mtu = mtu;
887     if (strioctl(pppfd, PPPIO_MTU, &mtu, sizeof(mtu), 0) < 0) {
888         if (hungup && errno == ENXIO)
889             return;
890         error("Couldn't set MTU: %m");
891     }
892     if (strioctl(pppfd, PPPIO_XACCM, &asyncmap, sizeof(asyncmap), 0) < 0) {
893         error("Couldn't set transmit ACCM: %m");
894     }
895     cf[0] = (pcomp? COMP_PROT: 0) + (accomp? COMP_AC: 0);
896     cf[1] = COMP_PROT | COMP_AC;
897     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
898         error("Couldn't set prot/AC compression: %m");
899     }
900 }
901
902 /*
903  * ppp_set_xaccm - set the extended transmit ACCM for the interface.
904  */
905 void
906 ppp_set_xaccm(unit, accm)
907     int unit;
908     ext_accm accm;
909 {
910     if (strioctl(pppfd, PPPIO_XACCM, accm, sizeof(ext_accm), 0) < 0) {
911         if (!hungup || errno != ENXIO)
912             warn("Couldn't set extended ACCM: %m");
913     }
914 }
915
916 /*
917  * ppp_recv_config - configure the receive-side characteristics of
918  * the ppp interface.
919  */
920 void
921 ppp_recv_config(unit, mru, asyncmap, pcomp, accomp)
922     int unit, mru;
923     u_int32_t asyncmap;
924     int pcomp, accomp;
925 {
926     int cf[2];
927
928     link_mru = mru;
929     if (strioctl(pppfd, PPPIO_MRU, &mru, sizeof(mru), 0) < 0) {
930         if (hungup && errno == ENXIO)
931             return;
932         error("Couldn't set MRU: %m");
933     }
934     if (strioctl(pppfd, PPPIO_RACCM, &asyncmap, sizeof(asyncmap), 0) < 0) {
935         error("Couldn't set receive ACCM: %m");
936     }
937     cf[0] = (pcomp? DECOMP_PROT: 0) + (accomp? DECOMP_AC: 0);
938     cf[1] = DECOMP_PROT | DECOMP_AC;
939     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
940         error("Couldn't set prot/AC decompression: %m");
941     }
942 }
943
944 /*
945  * ccp_test - ask kernel whether a given compression method
946  * is acceptable for use.
947  *
948  * In Digital UNIX the memory buckets for chunks >16K are not
949  * primed when the system comes up.  That means we're not
950  * likely to get the memory needed for the compressor on
951  * the first try.  The way we work around this is to have
952  * the driver spin off a thread to go get the memory for us
953  * (we can't block at that point in a streams context.)
954  *
955  * This code synchronizes with the thread when it has returned
956  * with the memory we need.  The driver will continue to return
957  * with EAGAIN until the thread comes back.  We give up here
958  * if after 10 attempts in one second we still don't have memory.
959  * It's up to the driver to not lose track of that memory if
960  * thread takes too long to return.
961  */
962 int
963 ccp_test(unit, opt_ptr, opt_len, for_transmit)
964     int unit, opt_len, for_transmit;
965     u_char *opt_ptr;
966 {
967     struct timeval tval;
968     int i;
969
970     tval.tv_sec = 0;
971     tval.tv_usec = 100000;
972     for (i = 0; i < 10; ++i) {
973         if (strioctl(pppfd, (for_transmit? PPPIO_XCOMP: PPPIO_RCOMP),
974             opt_ptr, opt_len, 0) >= 0) {
975             return 1;
976         }
977         if (errno != EAGAIN)
978             break;
979         wait_time(&tval);
980     }
981     if (errno != 0)
982         error("hard failure trying to get memory for a compressor: %m");
983     return (errno == ENOSR)? 0: -1;
984 }
985
986 /*
987  * ccp_flags_set - inform kernel about the current state of CCP.
988  */
989 void
990 ccp_flags_set(unit, isopen, isup)
991     int unit, isopen, isup;
992 {
993     int cf[2];
994
995     cf[0] = (isopen? CCP_ISOPEN: 0) + (isup? CCP_ISUP: 0);
996     cf[1] = CCP_ISOPEN | CCP_ISUP | CCP_ERROR | CCP_FATALERROR;
997     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
998         if (!hungup || errno != ENXIO)
999             error("Couldn't set kernel CCP state: %m");
1000     }
1001 }
1002
1003 /*
1004  * get_idle_time - return how long the link has been idle.
1005  */
1006 int
1007 get_idle_time(u, ip)
1008     int u;
1009     struct ppp_idle *ip;
1010 {
1011     return strioctl(pppfd, PPPIO_GIDLE, ip, 0, sizeof(struct ppp_idle)) >= 0;
1012 }
1013
1014 /*
1015  * get_ppp_stats - return statistics for the link.
1016  */
1017 int
1018 get_ppp_stats(u, stats)
1019     int u;
1020     struct pppd_stats *stats;
1021 {
1022     struct ppp_stats s;
1023
1024     if (strioctl(pppfd, PPPIO_GETSTAT, &s, 0, sizeof(s)) < 0) {
1025         error("Couldn't get link statistics: %m");
1026         return 0;
1027     }
1028     stats->bytes_in = s.p.ppp_ibytes;
1029     stats->bytes_out = s.p.ppp_obytes;
1030     return 1;
1031 }
1032
1033
1034 /*
1035  * ccp_fatal_error - returns 1 if decompression was disabled as a
1036  * result of an error detected after decompression of a packet,
1037  * 0 otherwise.  This is necessary because of patent nonsense.
1038  */
1039 int
1040 ccp_fatal_error(unit)
1041     int unit;
1042 {
1043     int cf[2];
1044
1045     cf[0] = cf[1] = 0;
1046     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
1047         if (errno != ENXIO && errno != EINVAL)
1048             error("Couldn't get compression flags: %m");
1049         return 0;
1050     }
1051     return cf[0] & CCP_FATALERROR;
1052 }
1053
1054 /*
1055  * sifvjcomp - config tcp header compression
1056  */
1057 int
1058 sifvjcomp(u, vjcomp, xcidcomp, xmaxcid)
1059     int u, vjcomp, xcidcomp, xmaxcid;
1060 {
1061     int cf[2];
1062     char maxcid[2];
1063
1064     if (vjcomp) {
1065         maxcid[0] = xcidcomp;
1066         maxcid[1] = 15;         /* XXX should be rmaxcid */
1067         if (strioctl(pppfd, PPPIO_VJINIT, maxcid, sizeof(maxcid), 0) < 0) {
1068             error("Couldn't initialize VJ compression: %m");
1069         }
1070     }
1071
1072     cf[0] = (vjcomp? COMP_VJC + DECOMP_VJC: 0)  /* XXX this is wrong */
1073         + (xcidcomp? COMP_VJCCID + DECOMP_VJCCID: 0);
1074     cf[1] = COMP_VJC + DECOMP_VJC + COMP_VJCCID + DECOMP_VJCCID;
1075     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
1076         if (vjcomp)
1077             error("Couldn't enable VJ compression: %m");
1078     }
1079
1080     return 1;
1081 }
1082
1083 /*
1084  * sifup - Config the interface up and enable IP packets to pass.
1085  */
1086 int
1087 sifup(u)
1088     int u;
1089 {
1090     struct ifreq ifr;
1091
1092     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
1093     if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
1094         error("Couldn't mark interface up (get): %m");
1095         return 0;
1096     }
1097     ifr.ifr_flags |= IFF_UP;
1098     if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
1099         error("Couldn't mark interface up (set): %m");
1100         return 0;
1101     }
1102     if_is_up = 1;
1103     return 1;
1104 }
1105
1106 /*
1107  * sifdown - Config the interface down and disable IP.
1108  */
1109 int
1110 sifdown(u)
1111     int u;
1112 {
1113     struct ifreq ifr;
1114
1115     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
1116     if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
1117         error("Couldn't mark interface down (get): %m");
1118         return 0;
1119     }
1120     if ((ifr.ifr_flags & IFF_UP) != 0) {
1121         ifr.ifr_flags &= ~IFF_UP;
1122         if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
1123             error("Couldn't mark interface down (set): %m");
1124             return 0;
1125         }
1126     }
1127     if_is_up = 0;
1128     return 1;
1129 }
1130
1131 /*
1132  * sifnpmode - Set the mode for handling packets for a given NP.
1133  */
1134 int
1135 sifnpmode(u, proto, mode)
1136     int u;
1137     int proto;
1138     enum NPmode mode;
1139 {
1140     int npi[2];
1141
1142     npi[0] = proto;
1143     npi[1] = (int) mode;
1144     if (strioctl(pppfd, PPPIO_NPMODE, npi, 2 * sizeof(int), 0) < 0) {
1145         error("ioctl(set NP %d mode to %d): %m", proto, mode);
1146         return 0;
1147     }
1148     return 1;
1149 }
1150
1151 #define INET_ADDR(x)    (((struct sockaddr_in *) &(x))->sin_addr.s_addr)
1152
1153 /*
1154  * SET_SA_FAMILY - initialize a struct sockaddr, setting the sa_family field.
1155  */
1156 #define SET_SA_FAMILY(addr, family)             \
1157     BZERO((char *) &(addr), sizeof(addr));      \
1158     addr.sa_family = (family);                  \
1159     addr.sa_len = sizeof ((addr))
1160
1161 /*
1162  * sifaddr - Config the interface IP addresses and netmask.
1163  */
1164 int
1165 sifaddr(u, o, h, m)
1166     int u;
1167     u_int32_t o, h, m;
1168 {
1169     struct ifreq ifr;
1170     struct ifaliasreq addreq;
1171     int ret;
1172
1173     ret = 1;
1174
1175     /* flush old address, if any
1176      */
1177     bzero(&ifr, sizeof (ifr));
1178     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
1179     SET_SA_FAMILY(ifr.ifr_addr, AF_INET);
1180     ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr.s_addr = o;
1181     if ((ioctl(sockfd, (int)SIOCDIFADDR, (caddr_t) &ifr) < 0)
1182         && errno != EADDRNOTAVAIL) {
1183         error("ioctl(SIOCDIFADDR): %m");
1184         ret = 0;
1185     }
1186
1187     bzero(&addreq, sizeof (addreq));
1188     strlcpy(addreq.ifra_name, ifname, sizeof (addreq.ifra_name));
1189     SET_SA_FAMILY(addreq.ifra_addr, AF_INET);
1190     SET_SA_FAMILY(addreq.ifra_broadaddr, AF_INET);
1191     ((struct sockaddr_in *)&addreq.ifra_addr)->sin_addr.s_addr = o;
1192     ((struct sockaddr_in *)&addreq.ifra_broadaddr)->sin_addr.s_addr = h;
1193
1194     if (m != 0) {
1195         ((struct sockaddr_in *)&addreq.ifra_mask)->sin_addr.s_addr = m;
1196         addreq.ifra_mask.sa_len = sizeof (struct sockaddr);
1197         info("Setting interface mask to %s\n", ip_ntoa(m));
1198     }
1199
1200     /* install new src/dst and (possibly) netmask
1201      */
1202     if (ioctl(sockfd, SIOCPIFADDR, &addreq) < 0) {
1203         error("ioctl(SIOCPIFADDR): %m");
1204         ret = 0;
1205     }
1206
1207     ifr.ifr_metric = link_mtu;
1208     if (ioctl(sockfd, SIOCSIPMTU, &ifr) < 0) {
1209         error("Couldn't set IP MTU: %m");
1210         ret = 0;
1211     }
1212
1213     ifaddrs[0] = o;
1214     ifaddrs[1] = h;
1215     return (ret);
1216 }
1217
1218
1219 /*
1220  * cifaddr - Clear the interface IP addresses, and delete routes
1221  * through the interface if possible.
1222  */
1223 int
1224 cifaddr(u, o, h)
1225     int u;
1226     u_int32_t o, h;
1227 {
1228     struct ifreq ifr;
1229
1230     ifaddrs[0] = 0;
1231     ifaddrs[1] = 0;
1232     bzero(&ifr, sizeof (ifr));
1233     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
1234     SET_SA_FAMILY(ifr.ifr_addr, AF_INET);
1235     ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr.s_addr = o;
1236     if (ioctl(sockfd, (int)SIOCDIFADDR, (caddr_t) &ifr) < 0) {
1237         error("ioctl(SIOCDIFADDR): %m");
1238         return 0;
1239     }
1240     return 1;
1241 }
1242
1243
1244 /*
1245  * sifdefaultroute - assign a default route through the address given.
1246  */
1247 int
1248 sifdefaultroute(u, l, g)
1249     int u;
1250     u_int32_t l, g;
1251 {
1252     struct ortentry rt;
1253
1254     BZERO(&rt, sizeof(rt));
1255     SET_SA_FAMILY(rt.rt_dst, AF_INET);
1256     SET_SA_FAMILY(rt.rt_gateway, AF_INET);
1257     ((struct sockaddr_in *) &rt.rt_gateway)->sin_addr.s_addr = g;
1258     rt.rt_flags = RTF_GATEWAY;
1259     if (ioctl(sockfd, (int)SIOCADDRT, &rt) < 0) {
1260         error("default route ioctl(SIOCADDRT): %m");
1261         return 0;
1262     }
1263     default_route_gateway = g;
1264     return 1;
1265 }
1266
1267
1268 /*
1269  * cifdefaultroute - delete a default route through the address given.
1270  */
1271 int
1272 cifdefaultroute(u, l, g)
1273     int u;
1274     u_int32_t l, g;
1275 {
1276     struct ortentry rt;
1277
1278     BZERO(&rt, sizeof(rt));
1279     SET_SA_FAMILY(rt.rt_dst, AF_INET);
1280     SET_SA_FAMILY(rt.rt_gateway, AF_INET);
1281     ((struct sockaddr_in *) &rt.rt_gateway)->sin_addr.s_addr = g;
1282     rt.rt_flags = RTF_GATEWAY;
1283     if (ioctl(sockfd, (int)SIOCDELRT, &rt) < 0) {
1284         error("default route ioctl(SIOCDELRT): %m");
1285         return 0;
1286     }
1287     default_route_gateway = 0;
1288     return 1;
1289 }
1290
1291 /*
1292  * sifproxyarp - Make a proxy ARP entry for the peer.
1293  */
1294 int
1295 sifproxyarp(unit, hisaddr)
1296     int unit;
1297     u_int32_t hisaddr;
1298 {
1299     struct arpreq arpreq;
1300
1301     BZERO(&arpreq, sizeof(arpreq));
1302
1303     /*
1304      * Get the hardware address of an interface on the same subnet
1305      * as our local address.
1306      */
1307     if (!get_ether_addr(hisaddr, &arpreq.arp_ha)) {
1308         warn("Cannot determine ethernet address for proxy ARP");
1309         return 0;
1310     }
1311
1312     SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
1313     ((struct sockaddr_in *) &arpreq.arp_pa)->sin_addr.s_addr = hisaddr;
1314     arpreq.arp_flags = ATF_PERM | ATF_PUBL;
1315     if (ioctl(sockfd, (int)SIOCSARP, (caddr_t)&arpreq) < 0) {
1316         error("ioctl(SIOCSARP): %m");
1317         return 0;
1318     }
1319
1320     proxy_arp_addr = hisaddr;
1321     return 1;
1322 }
1323
1324
1325 /*
1326  * cifproxyarp - Delete the proxy ARP entry for the peer.
1327  */
1328 int
1329 cifproxyarp(unit, hisaddr)
1330     int unit;
1331     u_int32_t hisaddr;
1332 {
1333     struct arpreq arpreq;
1334
1335     BZERO(&arpreq, sizeof(arpreq));
1336     SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
1337     ((struct sockaddr_in *) &arpreq.arp_pa)->sin_addr.s_addr = hisaddr;
1338     if (ioctl(sockfd, (int)SIOCDARP, (caddr_t)&arpreq) < 0) {
1339         error("ioctl(SIOCDARP): %m");
1340         return 0;
1341     }
1342     proxy_arp_addr = 0;
1343     return 1;
1344 }
1345
1346 /*
1347  * get_ether_addr - get the hardware address of an interface on the
1348  * the same subnet as ipaddr.
1349  */
1350 #define MAX_IFS         32
1351
1352 static int
1353 get_ether_addr(ipaddr, hwaddr)
1354     u_int32_t ipaddr;
1355     struct sockaddr *hwaddr;
1356 {
1357     struct ifreq *ifr, *ifend;
1358     u_int32_t ina, mask;
1359     struct ifreq ifreq;
1360     struct ifconf ifc;
1361     struct ifreq ifs[MAX_IFS];
1362     struct ifdevea ifdevreq;
1363
1364     ifc.ifc_len = sizeof(ifs);
1365     ifc.ifc_req = ifs;
1366     if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
1367         error("ioctl(SIOCGIFCONF): %m");
1368         return 0;
1369     }
1370
1371     /*
1372      * Scan through looking for an interface with an Internet
1373      * address on the same subnet as `ipaddr'.
1374      */
1375     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
1376     for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
1377         if (ifr->ifr_addr.sa_family == AF_INET) {
1378
1379             /*
1380              * Check that the interface is up, and not point-to-point
1381              * or loopback.
1382              */
1383             strlcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
1384             if (ioctl(sockfd, SIOCGIFFLAGS, &ifreq) < 0)
1385                 continue;
1386             if ((ifreq.ifr_flags &
1387                  (IFF_UP|IFF_BROADCAST|IFF_POINTOPOINT|IFF_LOOPBACK|IFF_NOARP))
1388                  != (IFF_UP|IFF_BROADCAST))
1389                 continue;
1390
1391             /*
1392              * Get its netmask and check that it's on the right subnet.
1393              */
1394             if (ioctl(sockfd, SIOCGIFNETMASK, &ifreq) < 0)
1395                 continue;
1396             ina = ((struct sockaddr_in *) &ifr->ifr_addr)->sin_addr.s_addr;
1397             mask = ((struct sockaddr_in *) &ifreq.ifr_addr)->sin_addr.s_addr;
1398             if ((ipaddr & mask) != (ina & mask))
1399                 continue;
1400
1401             break;
1402         } else {
1403             if (ifr->ifr_addr.sa_len > sizeof (ifr->ifr_addr))
1404                 ifr = (struct ifreq *)((caddr_t)ifr + (ifr->ifr_addr.sa_len - sizeof (ifr->ifr_addr)));
1405         }
1406     }
1407
1408     if (ifr >= ifend)
1409         return 0;
1410     info("found interface %s for proxy arp", ifr->ifr_name);
1411
1412     strlcpy(ifdevreq.ifr_name, ifr->ifr_name, sizeof(ifdevreq.ifr_name));
1413
1414     if (ioctl(sockfd, (int)SIOCRPHYSADDR, &ifdevreq) < 0) {
1415         perror("ioctl(SIOCRPHYSADDR)");
1416         return(0);
1417     }
1418
1419     hwaddr->sa_family = AF_UNSPEC;
1420     memcpy(hwaddr->sa_data, ifdevreq.current_pa, sizeof(ifdevreq.current_pa));
1421     return 1;
1422 }
1423
1424 #define WTMPFILE        "/usr/adm/wtmp"
1425
1426 void
1427 logwtmp(line, name, host)
1428     const char *line, *name, *host;
1429 {
1430     int fd;
1431     struct stat buf;
1432     struct utmp ut;
1433
1434     if ((fd = open(WTMPFILE, O_WRONLY|O_APPEND, 0)) < 0)
1435         return;
1436     if (!fstat(fd, &buf)) {
1437         strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1438         strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1439         strlcpy(ut.ut_host, host, sizeof(ut.ut_host));
1440         (void)time(&ut.ut_time);
1441         if (write(fd, (char *)&ut, sizeof(struct utmp)) != sizeof(struct utmp))
1442             (void)ftruncate(fd, buf.st_size);
1443     }
1444     close(fd);
1445 }
1446
1447 /*
1448  * Return user specified netmask, modified by any mask we might determine
1449  * for address `addr' (in network byte order).
1450  * Here we scan through the system's list of interfaces, looking for
1451  * any non-point-to-point interfaces which might appear to be on the same
1452  * network as `addr'.  If we find any, we OR in their netmask to the
1453  * user-specified netmask.
1454  */
1455 u_int32_t
1456 GetMask(addr)
1457     u_int32_t addr;
1458 {
1459     u_int32_t mask, nmask, ina;
1460     struct ifreq *ifr, *ifend, ifreq;
1461     struct ifconf ifc;
1462
1463     addr = ntohl(addr);
1464     if (IN_CLASSA(addr))        /* determine network mask for address class */
1465         nmask = IN_CLASSA_NET;
1466     else if (IN_CLASSB(addr))
1467         nmask = IN_CLASSB_NET;
1468     else
1469         nmask = IN_CLASSC_NET;
1470     /* class D nets are disallowed by bad_ip_adrs */
1471     mask = netmask | htonl(nmask);
1472
1473     /*
1474      * Scan through the system's network interfaces.
1475      */
1476     ifc.ifc_len = MAX_IFS * sizeof(struct ifreq);
1477     ifc.ifc_req = (struct ifreq *)alloca(ifc.ifc_len);
1478     if (ifc.ifc_req == 0)
1479         return mask;
1480     if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
1481         warn("Couldn't get system interface list: %m");
1482         return mask;
1483     }
1484     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
1485     for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
1486         /*
1487          * Check the interface's internet address.
1488          */
1489         if (ifr->ifr_addr.sa_family == AF_INET) {
1490             ina = INET_ADDR(ifr->ifr_addr);
1491             if ((ntohl(ina) & nmask) != (addr & nmask))
1492                 continue;
1493             /*
1494              * Check that the interface is up, and not point-to-point or loopback.
1495              */
1496             strlcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
1497             if (ioctl(sockfd, SIOCGIFFLAGS, &ifreq) < 0)
1498                 continue;
1499             if ((ifreq.ifr_flags & (IFF_UP|IFF_POINTOPOINT|IFF_LOOPBACK))
1500                 != IFF_UP)
1501                 continue;
1502             /*
1503              * Get its netmask and OR it into our mask.
1504              */
1505             if (ioctl(sockfd, SIOCGIFNETMASK, &ifreq) < 0)
1506                 continue;
1507             mask |= INET_ADDR(ifreq.ifr_addr);
1508             break;
1509         } else {
1510             if (ifr->ifr_addr.sa_len > sizeof (ifr->ifr_addr))
1511                 ifr = (struct ifreq *)((caddr_t)ifr + (ifr->ifr_addr.sa_len - sizeof (ifr->ifr_addr)));
1512         }
1513     }
1514
1515     return mask;
1516 }
1517
1518 /*
1519  * have_route_to - determine if the system has any route to
1520  * a given IP address.  `addr' is in network byte order.
1521  * For demand mode to work properly, we have to ignore routes
1522  * through our own interface.
1523  */
1524 int have_route_to(u_int32_t addr)
1525 {
1526         char buf[sizeof(struct rt_msghdr) + (sizeof(struct sockaddr_in))];
1527         int status;
1528         int s, n;
1529         struct rt_msghdr *rtm;
1530         struct sockaddr_in *sin;
1531         int msglen = sizeof(*rtm) + (sizeof(*sin));
1532         char *cp;
1533         char msg[2048];
1534
1535         rtm = (struct rt_msghdr *)buf;
1536         memset(rtm, 0, msglen);
1537         rtm->rtm_msglen = msglen;
1538         rtm->rtm_version = RTM_VERSION;
1539         rtm->rtm_type = RTM_GET;
1540         rtm->rtm_addrs = RTA_DST;
1541         /* rtm->rtm_addrs, rtm_flags  should be set on output */
1542
1543         sin = (struct sockaddr_in *)((u_char *)rtm + sizeof(*rtm));
1544         sin->sin_len = sizeof(*sin);
1545         sin->sin_family = AF_INET;
1546         sin->sin_addr.s_addr = addr;
1547
1548         status = 0;
1549
1550         if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0)
1551                 return -1;
1552         if (write(s, (char *)rtm, msglen) != msglen) {
1553                 close(s);
1554                 return status == ESRCH? 0: -1;
1555         }
1556
1557         n = read(s, msg, 2048);
1558         close(s);
1559         if (n <= 0)
1560                 return -1;
1561
1562         rtm = (struct rt_msghdr *) msg;
1563         if (rtm->rtm_version != RTM_VERSION)
1564                 return -1;
1565
1566         /* here we try to work out if the route is through our own interface */
1567         cp = (char *)(rtm + 1);
1568         if (rtm->rtm_addrs & RTA_DST) {
1569                 struct sockaddr *sa = (struct sockaddr *) cp;
1570                 cp = (char *)(((unsigned long)cp + sa->sa_len
1571                                + sizeof(long) - 1) & ~(sizeof(long) - 1));
1572         }
1573         if (rtm->rtm_addrs & RTA_GATEWAY) {
1574                 sin = (struct sockaddr_in *) cp;
1575                 if (sin->sin_addr.s_addr == ifaddrs[0]
1576                     || sin->sin_addr.s_addr == ifaddrs[1])
1577                         return 0;       /* route is through our interface */
1578         }
1579
1580         return 1;
1581 }
1582
1583 static int
1584 strioctl(fd, cmd, ptr, ilen, olen)
1585     int fd, cmd, ilen, olen;
1586     void *ptr;
1587 {
1588     struct strioctl str;
1589
1590     str.ic_cmd = cmd;
1591     str.ic_timout = 0;
1592     str.ic_len = ilen;
1593     str.ic_dp = ptr;
1594     if (ioctl(fd, I_STR, &str) == -1)
1595         return -1;
1596     if (str.ic_len != olen)
1597         dbglog("strioctl: expected %d bytes, got %d for cmd %x\n",
1598                olen, str.ic_len, cmd);
1599     return 0;
1600 }
1601
1602 /*
1603  * Use the hostid as part of the random number seed.
1604  */
1605 int
1606 get_host_seed()
1607 {
1608     return gethostid();
1609 }
1610
1611 /*
1612  * Code for locking/unlocking the serial device.
1613  * This code is derived from chat.c.
1614  */
1615
1616 #if !defined(HDB) && !defined(SUNOS3)
1617 #define HDB     1               /* ascii lock files are the default */
1618 #endif
1619
1620 #ifndef LOCK_DIR
1621 # if HDB
1622 #  define       PIDSTRING
1623 #  define       LOCK_PREFIX     "/usr/spool/locks/LCK.."
1624 # else /* HDB */
1625 #  define       LOCK_PREFIX     "/usr/spool/uucp/LCK.."
1626 # endif /* HDB */
1627 #endif /* LOCK_DIR */
1628
1629 static char *lock_file;         /* name of lock file created */
1630
1631 /*
1632  * lock - create a lock file for the named device.
1633  */
1634 int
1635 lock(dev)
1636     char *dev;
1637 {
1638     char hdb_lock_buffer[12];
1639     int fd, pid, n;
1640     char *p;
1641     size_t l;
1642
1643     if ((p = strrchr(dev, '/')) != NULL)
1644         dev = p + 1;
1645     l = strlen(LOCK_PREFIX) + strlen(dev) + 1;
1646     lock_file = malloc(l);
1647     if (lock_file == NULL)
1648         novm("lock file name");
1649     slprintf(lock_file, l, "%s%s", LOCK_PREFIX, dev);
1650
1651     while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
1652         if (errno == EEXIST
1653             && (fd = open(lock_file, O_RDONLY, 0)) >= 0) {
1654             /* Read the lock file to find out who has the device locked */
1655 #ifdef PIDSTRING
1656             n = read(fd, hdb_lock_buffer, 11);
1657             if (n > 0) {
1658                 hdb_lock_buffer[n] = 0;
1659                 pid = atoi(hdb_lock_buffer);
1660             }
1661 #else
1662             n = read(fd, &pid, sizeof(pid));
1663 #endif
1664             if (n <= 0) {
1665                 error("Can't read pid from lock file %s", lock_file);
1666                 close(fd);
1667             } else {
1668                 if (kill(pid, 0) == -1 && errno == ESRCH) {
1669                     /* pid no longer exists - remove the lock file */
1670                     if (unlink(lock_file) == 0) {
1671                         close(fd);
1672                         notice("Removed stale lock on %s (pid %d)",
1673                                dev, pid);
1674                         continue;
1675                     } else
1676                         warn("Couldn't remove stale lock on %s",
1677                                dev);
1678                 } else
1679                     notice("Device %s is locked by pid %d",
1680                            dev, pid);
1681             }
1682             close(fd);
1683         } else
1684             error("Can't create lock file %s: %m", lock_file);
1685         free(lock_file);
1686         lock_file = NULL;
1687         return -1;
1688     }
1689
1690 #ifdef PIDSTRING
1691     slprintf(hdb_lock_buffer, sizeof(hdb_lock_buffer), "%10d\n", getpid());
1692     write(fd, hdb_lock_buffer, 11);
1693 #else
1694     pid = getpid();
1695     write(fd, &pid, sizeof pid);
1696 #endif
1697
1698     close(fd);
1699     return 0;
1700 }
1701
1702 /*
1703  * unlock - remove our lockfile
1704  */
1705 void
1706 unlock()
1707 {
1708     if (lock_file) {
1709         unlink(lock_file);
1710         free(lock_file);
1711         lock_file = NULL;
1712     }
1713 }
1714
1715 int
1716 set_filters(pass, active)
1717     struct bpf_program *pass, *active;
1718 {
1719     return 1;
1720 }
1721
1722 int
1723 bpf_compile(program, buf, optimize)
1724     struct bpf_program *program;
1725     char *buf;
1726     int optimize;
1727 {
1728     return 0;
1729 }
1730
1731 char *
1732 bpf_geterr()
1733 {
1734     return 0;
1735 }
1736
1737 u_int
1738 bpf_filter(pc, p, wirelen, buflen)
1739     struct bpf_insn *pc;
1740     u_char *p;
1741     u_int wirelen;
1742     u_int buflen;
1743 {
1744     return 0;
1745 }