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