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