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