]> git.ozlabs.org Git - ppp.git/blob - pppd/sys-sunos4.c
make establish_ppp and open_ppp_loopback return the correct fd
[ppp.git] / pppd / sys-sunos4.c
1 /*
2  * System-dependent procedures for pppd under SunOS 4.
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-sunos4.c,v 1.15 1999/03/16 22:53:48 paulus Exp $";
30 #endif
31
32 #include <stdio.h>
33 #include <stddef.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <unistd.h>
40 #include <termios.h>
41 #include <signal.h>
42 #include <malloc.h>
43 #include <utmp.h>
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/socket.h>
47 #include <sys/sockio.h>
48 #include <sys/stream.h>
49 #include <sys/stropts.h>
50 #include <sys/stat.h>
51 #include <sys/time.h>
52 #include <sys/poll.h>
53 #include <net/if.h>
54 #include <net/if_arp.h>
55 #include <net/nit_if.h>
56 #include <net/route.h>
57 #include <net/ppp_defs.h>
58 #include <net/pppio.h>
59 #include <netinet/in.h>
60
61 #include "pppd.h"
62
63 #if defined(sun) && defined(sparc)
64 #include <alloca.h>
65 #ifndef __GNUC__
66 extern void *alloca();
67 #endif
68 #endif /*sparc*/
69
70 static int      pppfd;
71 static int      fdmuxid = -1;
72 static int      iffd;
73 static int      sockfd;
74
75 static int      restore_term;
76 static struct termios inittermios;
77 static struct winsize wsinfo;   /* Initial window size info */
78 static pid_t    parent_pid;     /* PID of our parent */
79
80 extern u_char   inpacket_buf[]; /* borrowed from main.c */
81
82 #define MAX_POLLFDS     32
83 static struct pollfd pollfds[MAX_POLLFDS];
84 static int n_pollfds;
85
86 static int      link_mtu, link_mru;
87
88 #define NMODULES        32
89 static int      tty_nmodules;
90 static char     tty_modules[NMODULES][FMNAMESZ+1];
91
92 static int      if_is_up;       /* Interface has been marked up */
93 static u_int32_t ifaddrs[2];    /* local and remote addresses */
94 static u_int32_t default_route_gateway; /* Gateway for default route added */
95 static u_int32_t proxy_arp_addr;        /* Addr for proxy arp entry added */
96
97 /* Prototypes for procedures local to this file. */
98 static int translate_speed __P((int));
99 static int baud_rate_of __P((int));
100 static int get_ether_addr __P((u_int32_t, struct sockaddr *));
101 static int strioctl __P((int, int, void *, int, int));
102
103
104 /*
105  * sys_init - System-dependent initialization.
106  */
107 void
108 sys_init()
109 {
110     int x;
111
112     /* Get an internet socket for doing socket ioctl's on. */
113     if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
114         fatal("Couldn't create IP socket: %m");
115
116     /*
117      * We may want to send a SIGHUP to the session leader associated
118      * with our controlling terminal later.  Because SunOS doesn't
119      * have getsid(), we make do with sending the signal to our
120      * parent process.
121      */
122     parent_pid = getppid();
123
124     /*
125      * Open the ppp device.
126      */
127     pppfd = open("/dev/ppp", O_RDWR | O_NONBLOCK, 0);
128     if (pppfd < 0)
129         fatal("Can't open /dev/ppp: %m");
130     if (kdebugflag) {
131         x = PPPDBG_LOG + PPPDBG_DRIVER;
132         strioctl(pppfd, PPPIO_DEBUG, &x, sizeof(int), 0);
133     }
134
135     /* Assign a new PPA and get its unit number. */
136     if (strioctl(pppfd, PPPIO_NEWPPA, &ifunit, 0, sizeof(int)) < 0)
137         fatal("Can't create new PPP interface: %m");
138
139     /*
140      * Open the ppp device again and push the if_ppp module on it.
141      */
142     iffd = open("/dev/ppp", O_RDWR, 0);
143     if (iffd < 0)
144         fatal("Can't open /dev/ppp (2): %m");
145     if (kdebugflag) {
146         x = PPPDBG_LOG + PPPDBG_DRIVER;
147         strioctl(iffd, PPPIO_DEBUG, &x, sizeof(int), 0);
148     }
149     if (strioctl(iffd, PPPIO_ATTACH, &ifunit, sizeof(int), 0) < 0)
150         fatal("Couldn't attach ppp interface to device: %m");
151     if (ioctl(iffd, I_PUSH, "if_ppp") < 0)
152         fatal("Can't push ppp interface module: %m");
153     if (kdebugflag) {
154         x = PPPDBG_LOG + PPPDBG_IF;
155         strioctl(iffd, PPPIO_DEBUG, &x, sizeof(int), 0);
156     }
157     if (strioctl(iffd, PPPIO_NEWPPA, &ifunit, sizeof(int), 0) < 0)
158         fatal("Couldn't create ppp interface unit: %m");
159     x = PPP_IP;
160     if (strioctl(iffd, PPPIO_BIND, &x, sizeof(int), 0) < 0)
161         fatal("Couldn't bind ppp interface to IP SAP: %m");
162
163     n_pollfds = 0;
164 }
165
166 /*
167  * sys_cleanup - restore any system state we modified before exiting:
168  * mark the interface down, delete default route and/or proxy arp entry.
169  * This shouldn't call die() because it's called from die().
170  */
171 void
172 sys_cleanup()
173 {
174     if (if_is_up)
175         sifdown(0);
176     if (ifaddrs[0])
177         cifaddr(0, ifaddrs[0], ifaddrs[1]);
178     if (default_route_gateway)
179         cifdefaultroute(0, 0, default_route_gateway);
180     if (proxy_arp_addr)
181         cifproxyarp(0, proxy_arp_addr);
182 }
183
184 /*
185  * sys_close - Clean up in a child process before execing.
186  */
187 void
188 sys_close()
189 {
190     close(iffd);
191     close(pppfd);
192     close(sockfd);
193 }
194
195 /*
196  * sys_check_options - check the options that the user specified
197  */
198 int
199 sys_check_options()
200 {
201     return 1;
202 }
203
204
205 /*
206  * daemon - Detach us from controlling terminal session.
207  */
208 int
209 daemon(nochdir, noclose)
210     int nochdir, noclose;
211 {
212     int pid;
213
214     if ((pid = fork()) < 0)
215         return -1;
216     if (pid != 0)
217         exit(0);                /* parent dies */
218     setsid();
219     if (!nochdir)
220         chdir("/");
221     if (!noclose) {
222         fclose(stdin);          /* don't need stdin, stdout, stderr */
223         fclose(stdout);
224         fclose(stderr);
225     }
226     return 0;
227 }
228
229 /*
230  * ppp_available - check whether the system has any ppp interfaces
231  */
232 int
233 ppp_available()
234 {
235     struct stat buf;
236
237     return stat("/dev/ppp", &buf) >= 0;
238 }
239
240 /*
241  * establish_ppp - Turn the serial port into a ppp interface.
242  */
243 int
244 establish_ppp(fd)
245     int fd;
246 {
247     int i;
248
249     /* Pop any existing modules off the tty stream. */
250     for (i = 0;; ++i)
251         if (ioctl(fd, I_LOOK, tty_modules[i]) < 0
252             || ioctl(fd, I_POP, 0) < 0)
253             break;
254     tty_nmodules = i;
255
256     /* Push the async hdlc module and the compressor module. */
257     if (ioctl(fd, I_PUSH, "ppp_ahdl") < 0)
258         fatal("Couldn't push PPP Async HDLC module: %m");
259     if (ioctl(fd, I_PUSH, "ppp_comp") < 0)
260         error("Couldn't push PPP compression module: %m");
261
262     /* Link the serial port under the PPP multiplexor. */
263     if ((fdmuxid = ioctl(pppfd, I_LINK, fd)) < 0)
264         fatal("Can't link tty to PPP mux: %m");
265
266     return pppfd;
267 }
268
269 /*
270  * restore_loop - reattach the ppp unit to the loopback.
271  * This doesn't need to do anything because disestablish_ppp does it.
272  */
273 void
274 restore_loop()
275 {
276 }
277
278 /*
279  * disestablish_ppp - Restore the serial port to normal operation.
280  * It attempts to reconstruct the stream with the previously popped
281  * modules.  This shouldn't call die() because it's called from die().
282  */
283 void
284 disestablish_ppp(fd)
285     int fd;
286 {
287     int i;
288
289     if (fdmuxid >= 0) {
290         if (ioctl(pppfd, I_UNLINK, fdmuxid) < 0) {
291             if (!hungup)
292                 error("Can't unlink tty from PPP mux: %m");
293         }
294         fdmuxid = -1;
295
296         if (!hungup) {
297             while (ioctl(fd, I_POP, 0) >= 0)
298                 ;
299             for (i = tty_nmodules - 1; i >= 0; --i)
300                 if (ioctl(fd, I_PUSH, tty_modules[i]) < 0)
301                     error("Couldn't restore tty module %s: %m",
302                            tty_modules[i]);
303         }
304         if (hungup && default_device && parent_pid > 0) {
305             /*
306              * If we have received a hangup, we need to send a SIGHUP
307              * to the terminal's controlling process.  The reason is
308              * that the original stream head for the terminal hasn't
309              * seen the M_HANGUP message (it went up through the ppp
310              * driver to the stream head for our fd to /dev/ppp).
311              * Actually we send the signal to the process that invoked
312              * pppd, since SunOS doesn't have getsid().
313              */
314             kill(parent_pid, SIGHUP);
315         }
316     }
317 }
318
319 /*
320  * Check whether the link seems not to be 8-bit clean.
321  */
322 void
323 clean_check()
324 {
325     int x;
326     char *s;
327
328     if (strioctl(pppfd, PPPIO_GCLEAN, &x, 0, sizeof(x)) < 0)
329         return;
330     s = NULL;
331     switch (~x) {
332     case RCV_B7_0:
333         s = "bit 7 set to 1";
334         break;
335     case RCV_B7_1:
336         s = "bit 7 set to 0";
337         break;
338     case RCV_EVNP:
339         s = "odd parity";
340         break;
341     case RCV_ODDP:
342         s = "even parity";
343         break;
344     }
345     if (s != NULL) {
346         warn("Serial link is not 8-bit clean:");
347         warn("All received characters had %s", s);
348     }
349 }
350
351 /*
352  * List of valid speeds.
353  */
354 struct speed {
355     int speed_int, speed_val;
356 } speeds[] = {
357 #ifdef B50
358     { 50, B50 },
359 #endif
360 #ifdef B75
361     { 75, B75 },
362 #endif
363 #ifdef B110
364     { 110, B110 },
365 #endif
366 #ifdef B134
367     { 134, B134 },
368 #endif
369 #ifdef B150
370     { 150, B150 },
371 #endif
372 #ifdef B200
373     { 200, B200 },
374 #endif
375 #ifdef B300
376     { 300, B300 },
377 #endif
378 #ifdef B600
379     { 600, B600 },
380 #endif
381 #ifdef B1200
382     { 1200, B1200 },
383 #endif
384 #ifdef B1800
385     { 1800, B1800 },
386 #endif
387 #ifdef B2000
388     { 2000, B2000 },
389 #endif
390 #ifdef B2400
391     { 2400, B2400 },
392 #endif
393 #ifdef B3600
394     { 3600, B3600 },
395 #endif
396 #ifdef B4800
397     { 4800, B4800 },
398 #endif
399 #ifdef B7200
400     { 7200, B7200 },
401 #endif
402 #ifdef B9600
403     { 9600, B9600 },
404 #endif
405 #ifdef B19200
406     { 19200, B19200 },
407 #endif
408 #ifdef B38400
409     { 38400, B38400 },
410 #endif
411 #ifdef EXTA
412     { 19200, EXTA },
413 #endif
414 #ifdef EXTB
415     { 38400, EXTB },
416 #endif
417 #ifdef B57600
418     { 57600, B57600 },
419 #endif
420 #ifdef B115200
421     { 115200, B115200 },
422 #endif
423     { 0, 0 }
424 };
425
426 /*
427  * Translate from bits/second to a speed_t.
428  */
429 static int
430 translate_speed(bps)
431     int bps;
432 {
433     struct speed *speedp;
434
435     if (bps == 0)
436         return 0;
437     for (speedp = speeds; speedp->speed_int; speedp++)
438         if (bps == speedp->speed_int)
439             return speedp->speed_val;
440     warn("speed %d not supported", bps);
441     return 0;
442 }
443
444 /*
445  * Translate from a speed_t to bits/second.
446  */
447 static int
448 baud_rate_of(speed)
449     int speed;
450 {
451     struct speed *speedp;
452
453     if (speed == 0)
454         return 0;
455     for (speedp = speeds; speedp->speed_int; speedp++)
456         if (speed == speedp->speed_val)
457             return speedp->speed_int;
458     return 0;
459 }
460
461 /*
462  * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
463  * at the requested speed, etc.  If `local' is true, set CLOCAL
464  * regardless of whether the modem option was specified.
465  */
466 void
467 set_up_tty(fd, local)
468     int fd, local;
469 {
470     int speed;
471     struct termios tios;
472
473     if (tcgetattr(fd, &tios) < 0)
474         fatal("tcgetattr: %m");
475
476     if (!restore_term) {
477         inittermios = tios;
478         ioctl(fd, TIOCGWINSZ, &wsinfo);
479     }
480
481     tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
482     if (crtscts > 0)
483         tios.c_cflag |= CRTSCTS;
484     else if (crtscts < 0)
485         tios.c_cflag &= ~CRTSCTS;
486
487     tios.c_cflag |= CS8 | CREAD | HUPCL;
488     if (local || !modem)
489         tios.c_cflag |= CLOCAL;
490     tios.c_iflag = IGNBRK | IGNPAR;
491     tios.c_oflag = 0;
492     tios.c_lflag = 0;
493     tios.c_cc[VMIN] = 1;
494     tios.c_cc[VTIME] = 0;
495
496     if (crtscts == -2) {
497         tios.c_iflag |= IXON | IXOFF;
498         tios.c_cc[VSTOP] = 0x13;        /* DC3 = XOFF = ^S */
499         tios.c_cc[VSTART] = 0x11;       /* DC1 = XON  = ^Q */
500     }
501
502     speed = translate_speed(inspeed);
503     if (speed) {
504         cfsetospeed(&tios, speed);
505         cfsetispeed(&tios, speed);
506     } else {
507         speed = cfgetospeed(&tios);
508         /*
509          * We can't proceed if the serial port speed is 0,
510          * since that implies that the serial port is disabled.
511          */
512         if (speed == B0)
513             fatal("Baud rate for %s is 0; need explicit baud rate", devnam);
514     }
515
516     if (tcsetattr(fd, TCSAFLUSH, &tios) < 0)
517         fatal("tcsetattr: %m");
518
519     baud_rate = inspeed = baud_rate_of(speed);
520     restore_term = 1;
521 }
522
523 /*
524  * restore_tty - restore the terminal to the saved settings.
525  */
526 void
527 restore_tty(fd)
528     int fd;
529 {
530     if (restore_term) {
531         if (!default_device) {
532             /*
533              * Turn off echoing, because otherwise we can get into
534              * a loop with the tty and the modem echoing to each other.
535              * We presume we are the sole user of this tty device, so
536              * when we close it, it will revert to its defaults anyway.
537              */
538             inittermios.c_lflag &= ~(ECHO | ECHONL);
539         }
540         if (tcsetattr(fd, TCSAFLUSH, &inittermios) < 0)
541             if (!hungup && errno != ENXIO)
542                 warn("tcsetattr: %m");
543         ioctl(fd, TIOCSWINSZ, &wsinfo);
544         restore_term = 0;
545     }
546 }
547
548 /*
549  * setdtr - control the DTR line on the serial port.
550  * This is called from die(), so it shouldn't call die().
551  */
552 void
553 setdtr(fd, on)
554 int fd, on;
555 {
556     int modembits = TIOCM_DTR;
557
558     ioctl(fd, (on? TIOCMBIS: TIOCMBIC), &modembits);
559 }
560
561 /*
562  * open_loopback - open the device we use for getting packets
563  * in demand mode.  Under SunOS, we use our existing fd
564  * to the ppp driver.
565  */
566 int
567 open_ppp_loopback()
568 {
569     return pppfd;
570 }
571
572 /*
573  * output - Output PPP packet.
574  */
575 void
576 output(unit, p, len)
577     int unit;
578     u_char *p;
579     int len;
580 {
581     struct strbuf data;
582     int retries;
583     struct pollfd pfd;
584
585     if (debug)
586         dbglog("sent %P", p, len);
587
588     data.len = len;
589     data.buf = (caddr_t) p;
590     retries = 4;
591     while (putmsg(pppfd, NULL, &data, 0) < 0) {
592         if (--retries < 0 || (errno != EWOULDBLOCK && errno != EAGAIN)) {
593             if (errno != ENXIO)
594                 error("Couldn't send packet: %m");
595             break;
596         }
597         pfd.fd = pppfd;
598         pfd.events = POLLOUT;
599         poll(&pfd, 1, 250);     /* wait for up to 0.25 seconds */
600     }
601 }
602
603
604 /*
605  * wait_input - wait until there is data available,
606  * for the length of time specified by *timo (indefinite
607  * if timo is NULL).
608  */
609 void
610 wait_input(timo)
611     struct timeval *timo;
612 {
613     int t;
614
615     t = timo == NULL? -1: timo->tv_sec * 1000 + timo->tv_usec / 1000;
616     if (poll(pollfds, n_pollfds, t) < 0 && errno != EINTR)
617         fatal("poll: %m");
618 }
619
620 /*
621  * wait_loop_output - wait until there is data available on the
622  * loopback, for the length of time specified by *timo (indefinite
623  * if timo is NULL).
624  */
625 void
626 wait_loop_output(timo)
627     struct timeval *timo;
628 {
629     wait_input(timo);
630 }
631
632 /*
633  * wait_time - wait for a given length of time or until a
634  * signal is received.
635  */
636 void
637 wait_time(timo)
638     struct timeval *timo;
639 {
640     int n;
641
642     n = select(0, NULL, NULL, NULL, timo);
643     if (n < 0 && errno != EINTR)
644         fatal("select: %m");
645 }
646
647
648 /*
649  * read_packet - get a PPP packet from the serial device.
650  */
651 int
652 read_packet(buf)
653     u_char *buf;
654 {
655     struct strbuf ctrl, data;
656     int flags, len;
657     unsigned char ctrlbuf[64];
658
659     for (;;) {
660         data.maxlen = PPP_MRU + PPP_HDRLEN;
661         data.buf = (caddr_t) buf;
662         ctrl.maxlen = sizeof(ctrlbuf);
663         ctrl.buf = (caddr_t) ctrlbuf;
664         flags = 0;
665         len = getmsg(pppfd, &ctrl, &data, &flags);
666         if (len < 0) {
667             if (errno = EAGAIN || errno == EINTR)
668                 return -1;
669             fatal("Error reading packet: %m");
670         }
671
672         if (ctrl.len <= 0)
673             return data.len;
674
675         /*
676          * Got a M_PROTO or M_PCPROTO message.  Huh?
677          */
678         if (debug)
679             dbglog("got ctrl msg len=%d", ctrl.len);
680
681     }
682 }
683
684 /*
685  * get_loop_output - get outgoing packets from the ppp device,
686  * and detect when we want to bring the real link up.
687  * Return value is 1 if we need to bring up the link, 0 otherwise.
688  */
689 int
690 get_loop_output()
691 {
692     int len;
693     int rv = 0;
694
695     while ((len = read_packet(inpacket_buf)) > 0) {
696         if (loop_frame(inpacket_buf, len))
697             rv = 1;
698     }
699     return rv;
700 }
701
702 /*
703  * ppp_send_config - configure the transmit characteristics of
704  * the ppp interface.
705  */
706 void
707 ppp_send_config(unit, mtu, asyncmap, pcomp, accomp)
708     int unit, mtu;
709     u_int32_t asyncmap;
710     int pcomp, accomp;
711 {
712     int cf[2];
713     struct ifreq ifr;
714
715     link_mtu = mtu;
716     if (strioctl(pppfd, PPPIO_MTU, &mtu, sizeof(mtu), 0) < 0) {
717         if (hungup && errno == ENXIO)
718             return;
719         error("Couldn't set MTU: %m");
720     }
721     if (strioctl(pppfd, PPPIO_XACCM, &asyncmap, sizeof(asyncmap), 0) < 0) {
722         error("Couldn't set transmit ACCM: %m");
723     }
724     cf[0] = (pcomp? COMP_PROT: 0) + (accomp? COMP_AC: 0);
725     cf[1] = COMP_PROT | COMP_AC;
726     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
727         error("Couldn't set prot/AC compression: %m");
728     }
729
730     /* set mtu for ip as well */
731     memset(&ifr, 0, sizeof(ifr));
732     strlcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);
733     ifr.ifr_metric = link_mtu;
734     if (ioctl(sockfd, SIOCSIFMTU, &ifr) < 0) {
735         error("Couldn't set IP MTU: %m");
736     }
737 }
738
739 /*
740  * ppp_set_xaccm - set the extended transmit ACCM for the interface.
741  */
742 void
743 ppp_set_xaccm(unit, accm)
744     int unit;
745     ext_accm accm;
746 {
747     if (strioctl(pppfd, PPPIO_XACCM, accm, sizeof(ext_accm), 0) < 0) {
748         if (!hungup || errno != ENXIO)
749             warn("Couldn't set extended ACCM: %m");
750     }
751 }
752
753 /*
754  * ppp_recv_config - configure the receive-side characteristics of
755  * the ppp interface.
756  */
757 void
758 ppp_recv_config(unit, mru, asyncmap, pcomp, accomp)
759     int unit, mru;
760     u_int32_t asyncmap;
761     int pcomp, accomp;
762 {
763     int cf[2];
764
765     link_mru = mru;
766     if (strioctl(pppfd, PPPIO_MRU, &mru, sizeof(mru), 0) < 0) {
767         if (hungup && errno == ENXIO)
768             return;
769         error("Couldn't set MRU: %m");
770     }
771     if (strioctl(pppfd, PPPIO_RACCM, &asyncmap, sizeof(asyncmap), 0) < 0) {
772         error("Couldn't set receive ACCM: %m");
773     }
774     cf[0] = (pcomp? DECOMP_PROT: 0) + (accomp? DECOMP_AC: 0);
775     cf[1] = DECOMP_PROT | DECOMP_AC;
776     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
777         error("Couldn't set prot/AC decompression: %m");
778     }
779 }
780
781 /*
782  * ccp_test - ask kernel whether a given compression method
783  * is acceptable for use.
784  */
785 int
786 ccp_test(unit, opt_ptr, opt_len, for_transmit)
787     int unit, opt_len, for_transmit;
788     u_char *opt_ptr;
789 {
790     if (strioctl(pppfd, (for_transmit? PPPIO_XCOMP: PPPIO_RCOMP),
791                  opt_ptr, opt_len, 0) >= 0)
792         return 1;
793     return (errno == ENOSR)? 0: -1;
794 }
795
796 /*
797  * ccp_flags_set - inform kernel about the current state of CCP.
798  */
799 void
800 ccp_flags_set(unit, isopen, isup)
801     int unit, isopen, isup;
802 {
803     int cf[2];
804
805     cf[0] = (isopen? CCP_ISOPEN: 0) + (isup? CCP_ISUP: 0);
806     cf[1] = CCP_ISOPEN | CCP_ISUP | CCP_ERROR | CCP_FATALERROR;
807     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
808         if (!hungup || errno != ENXIO)
809             error("Couldn't set kernel CCP state: %m");
810     }
811 }
812
813 /*
814  * get_idle_time - return how long the link has been idle.
815  */
816 int
817 get_idle_time(u, ip)
818     int u;
819     struct ppp_idle *ip;
820 {
821     return strioctl(pppfd, PPPIO_GIDLE, ip, 0, sizeof(struct ppp_idle)) >= 0;
822 }
823
824
825 /*
826  * ccp_fatal_error - returns 1 if decompression was disabled as a
827  * result of an error detected after decompression of a packet,
828  * 0 otherwise.  This is necessary because of patent nonsense.
829  */
830 int
831 ccp_fatal_error(unit)
832     int unit;
833 {
834     int cf[2];
835
836     cf[0] = cf[1] = 0;
837     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
838         if (errno != ENXIO && errno != EINVAL)
839             error("Couldn't get compression flags: %m");
840         return 0;
841     }
842     return cf[0] & CCP_FATALERROR;
843 }
844
845 /*
846  * sifvjcomp - config tcp header compression
847  */
848 int
849 sifvjcomp(u, vjcomp, xcidcomp, xmaxcid)
850     int u, vjcomp, xcidcomp, xmaxcid;
851 {
852     int cf[2];
853     char maxcid[2];
854
855     if (vjcomp) {
856         maxcid[0] = xcidcomp;
857         maxcid[1] = 15;         /* XXX should be rmaxcid */
858         if (strioctl(pppfd, PPPIO_VJINIT, maxcid, sizeof(maxcid), 0) < 0) {
859             error("Couldn't initialize VJ compression: %m");
860         }
861     }
862
863     cf[0] = (vjcomp? COMP_VJC + DECOMP_VJC: 0)  /* XXX this is wrong */
864         + (xcidcomp? COMP_VJCCID + DECOMP_VJCCID: 0);
865     cf[1] = COMP_VJC + DECOMP_VJC + COMP_VJCCID + DECOMP_VJCCID;
866     if (strioctl(pppfd, PPPIO_CFLAGS, cf, sizeof(cf), sizeof(int)) < 0) {
867         if (vjcomp)
868             error("Couldn't enable VJ compression: %m");
869     }
870
871     return 1;
872 }
873
874 /*
875  * sifup - Config the interface up and enable IP packets to pass.
876  */
877 int
878 sifup(u)
879     int u;
880 {
881     struct ifreq ifr;
882
883     strlcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);
884     if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
885         error("Couldn't mark interface up (get): %m");
886         return 0;
887     }
888     ifr.ifr_flags |= IFF_UP;
889     if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
890         error("Couldn't mark interface up (set): %m");
891         return 0;
892     }
893     if_is_up = 1;
894     return 1;
895 }
896
897 /*
898  * sifdown - Config the interface down and disable IP.
899  */
900 int
901 sifdown(u)
902     int u;
903 {
904     struct ifreq ifr;
905
906     strlcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);
907     if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
908         error("Couldn't mark interface down (get): %m");
909         return 0;
910     }
911     if ((ifr.ifr_flags & IFF_UP) != 0) {
912         ifr.ifr_flags &= ~IFF_UP;
913         if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0) {
914             error("Couldn't mark interface down (set): %m");
915             return 0;
916         }
917     }
918     if_is_up = 0;
919     return 1;
920 }
921
922 /*
923  * sifnpmode - Set the mode for handling packets for a given NP.
924  */
925 int
926 sifnpmode(u, proto, mode)
927     int u;
928     int proto;
929     enum NPmode mode;
930 {
931     int npi[2];
932
933     npi[0] = proto;
934     npi[1] = (int) mode;
935     if (strioctl(pppfd, PPPIO_NPMODE, npi, 2 * sizeof(int), 0) < 0) {
936         error("ioctl(set NP %d mode to %d): %m", proto, mode);
937         return 0;
938     }
939     return 1;
940 }
941
942 #define INET_ADDR(x)    (((struct sockaddr_in *) &(x))->sin_addr.s_addr)
943
944 /*
945  * sifaddr - Config the interface IP addresses and netmask.
946  */
947 int
948 sifaddr(u, o, h, m)
949     int u;
950     u_int32_t o, h, m;
951 {
952     struct ifreq ifr;
953
954     memset(&ifr, 0, sizeof(ifr));
955     strlcpy(ifr.ifr_name, sizeof(ifr.ifr_name), ifname);
956     ifr.ifr_addr.sa_family = AF_INET;
957     INET_ADDR(ifr.ifr_addr) = m;
958     if (ioctl(sockfd, SIOCSIFNETMASK, &ifr) < 0) {
959         error("Couldn't set IP netmask: %m");
960     }
961     ifr.ifr_addr.sa_family = AF_INET;
962     INET_ADDR(ifr.ifr_addr) = o;
963     if (ioctl(sockfd, SIOCSIFADDR, &ifr) < 0) {
964         error("Couldn't set local IP address: %m");
965     }
966     ifr.ifr_dstaddr.sa_family = AF_INET;
967     INET_ADDR(ifr.ifr_dstaddr) = h;
968     if (ioctl(sockfd, SIOCSIFDSTADDR, &ifr) < 0) {
969         error("Couldn't set remote IP address: %m");
970     }
971 #if 0   /* now done in ppp_send_config */
972     ifr.ifr_metric = link_mtu;
973     if (ioctl(sockfd, SIOCSIFMTU, &ifr) < 0) {
974         error("Couldn't set IP MTU: %m");
975     }
976 #endif
977     ifaddrs[0] = o;
978     ifaddrs[1] = h;
979
980     return 1;
981 }
982
983 /*
984  * cifaddr - Clear the interface IP addresses, and delete routes
985  * through the interface if possible.
986  */
987 int
988 cifaddr(u, o, h)
989     int u;
990     u_int32_t o, h;
991 {
992     struct rtentry rt;
993
994     bzero(&rt, sizeof(rt));
995     rt.rt_dst.sa_family = AF_INET;
996     INET_ADDR(rt.rt_dst) = h;
997     rt.rt_gateway.sa_family = AF_INET;
998     INET_ADDR(rt.rt_gateway) = o;
999     rt.rt_flags = RTF_HOST;
1000     if (ioctl(sockfd, SIOCDELRT, &rt) < 0)
1001         error("Couldn't delete route through interface: %m");
1002     ifaddrs[0] = 0;
1003     return 1;
1004 }
1005
1006 /*
1007  * sifdefaultroute - assign a default route through the address given.
1008  */
1009 int
1010 sifdefaultroute(u, l, g)
1011     int u;
1012     u_int32_t l, g;
1013 {
1014     struct rtentry rt;
1015
1016     bzero(&rt, sizeof(rt));
1017     rt.rt_dst.sa_family = AF_INET;
1018     INET_ADDR(rt.rt_dst) = 0;
1019     rt.rt_gateway.sa_family = AF_INET;
1020     INET_ADDR(rt.rt_gateway) = g;
1021     rt.rt_flags = RTF_GATEWAY;
1022
1023     if (ioctl(sockfd, SIOCADDRT, &rt) < 0) {
1024         error("Can't add default route: %m");
1025         return 0;
1026     }
1027
1028     default_route_gateway = g;
1029     return 1;
1030 }
1031
1032 /*
1033  * cifdefaultroute - delete a default route through the address given.
1034  */
1035 int
1036 cifdefaultroute(u, l, g)
1037     int u;
1038     u_int32_t l, g;
1039 {
1040     struct rtentry rt;
1041
1042     bzero(&rt, sizeof(rt));
1043     rt.rt_dst.sa_family = AF_INET;
1044     INET_ADDR(rt.rt_dst) = 0;
1045     rt.rt_gateway.sa_family = AF_INET;
1046     INET_ADDR(rt.rt_gateway) = g;
1047     rt.rt_flags = RTF_GATEWAY;
1048
1049     if (ioctl(sockfd, SIOCDELRT, &rt) < 0) {
1050         error("Can't delete default route: %m");
1051         return 0;
1052     }
1053
1054     default_route_gateway = 0;
1055     return 1;
1056 }
1057
1058 /*
1059  * sifproxyarp - Make a proxy ARP entry for the peer.
1060  */
1061 int
1062 sifproxyarp(unit, hisaddr)
1063     int unit;
1064     u_int32_t hisaddr;
1065 {
1066     struct arpreq arpreq;
1067
1068     bzero(&arpreq, sizeof(arpreq));
1069     if (!get_ether_addr(hisaddr, &arpreq.arp_ha))
1070         return 0;
1071
1072     arpreq.arp_pa.sa_family = AF_INET;
1073     INET_ADDR(arpreq.arp_pa) = hisaddr;
1074     arpreq.arp_flags = ATF_PERM | ATF_PUBL;
1075     if (ioctl(sockfd, SIOCSARP, (caddr_t) &arpreq) < 0) {
1076         error("Couldn't set proxy ARP entry: %m");
1077         return 0;
1078     }
1079
1080     proxy_arp_addr = hisaddr;
1081     return 1;
1082 }
1083
1084 /*
1085  * cifproxyarp - Delete the proxy ARP entry for the peer.
1086  */
1087 int
1088 cifproxyarp(unit, hisaddr)
1089     int unit;
1090     u_int32_t hisaddr;
1091 {
1092     struct arpreq arpreq;
1093
1094     bzero(&arpreq, sizeof(arpreq));
1095     arpreq.arp_pa.sa_family = AF_INET;
1096     INET_ADDR(arpreq.arp_pa) = hisaddr;
1097     if (ioctl(sockfd, SIOCDARP, (caddr_t)&arpreq) < 0) {
1098         error("Couldn't delete proxy ARP entry: %m");
1099         return 0;
1100     }
1101
1102     proxy_arp_addr = 0;
1103     return 1;
1104 }
1105
1106 /*
1107  * get_ether_addr - get the hardware address of an interface on the
1108  * the same subnet as ipaddr.
1109  */
1110 #define MAX_IFS         32
1111
1112 static int
1113 get_ether_addr(ipaddr, hwaddr)
1114     u_int32_t ipaddr;
1115     struct sockaddr *hwaddr;
1116 {
1117     struct ifreq *ifr, *ifend;
1118     u_int32_t ina, mask;
1119     struct ifreq ifreq;
1120     struct ifconf ifc;
1121     struct ifreq ifs[MAX_IFS];
1122     int nit_fd;
1123
1124     ifc.ifc_len = sizeof(ifs);
1125     ifc.ifc_req = ifs;
1126     if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
1127         error("ioctl(SIOCGIFCONF): %m");
1128         return 0;
1129     }
1130
1131     /*
1132      * Scan through looking for an interface with an Internet
1133      * address on the same subnet as `ipaddr'.
1134      */
1135     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
1136     for (ifr = ifc.ifc_req; ifr < ifend; ifr = (struct ifreq *)
1137             ((char *)&ifr->ifr_addr + sizeof(struct sockaddr))) {
1138         if (ifr->ifr_addr.sa_family == AF_INET) {
1139
1140             /*
1141              * Check that the interface is up, and not point-to-point
1142              * or loopback.
1143              */
1144             strlcpy(ifreq.ifr_name, sizeof(ifreq.ifr_name), ifr->ifr_name);
1145             if (ioctl(sockfd, SIOCGIFFLAGS, &ifreq) < 0)
1146                 continue;
1147             if ((ifreq.ifr_flags &
1148                  (IFF_UP|IFF_BROADCAST|IFF_POINTOPOINT|IFF_LOOPBACK|IFF_NOARP))
1149                  != (IFF_UP|IFF_BROADCAST))
1150                 continue;
1151
1152             /*
1153              * Get its netmask and check that it's on the right subnet.
1154              */
1155             if (ioctl(sockfd, SIOCGIFNETMASK, &ifreq) < 0)
1156                 continue;
1157             ina = ((struct sockaddr_in *) &ifr->ifr_addr)->sin_addr.s_addr;
1158             mask = ((struct sockaddr_in *) &ifreq.ifr_addr)->sin_addr.s_addr;
1159             if ((ipaddr & mask) != (ina & mask))
1160                 continue;
1161
1162             break;
1163         }
1164     }
1165
1166     if (ifr >= ifend)
1167         return 0;
1168     info("found interface %s for proxy arp", ifr->ifr_name);
1169
1170     /*
1171      * Grab the physical address for this interface.
1172      */
1173     if ((nit_fd = open("/dev/nit", O_RDONLY)) < 0) {
1174         error("Couldn't open /dev/nit: %m");
1175         return 0;
1176     }
1177     strlcpy(ifreq.ifr_name, sizeof(ifreq.ifr_name), ifr->ifr_name);
1178     if (ioctl(nit_fd, NIOCBIND, &ifreq) < 0
1179         || ioctl(nit_fd, SIOCGIFADDR, &ifreq) < 0) {
1180         error("Couldn't get hardware address for %s: %m",
1181                ifreq.ifr_name);
1182         close(nit_fd);
1183         return 0;
1184     }
1185
1186     hwaddr->sa_family = AF_UNSPEC;
1187     memcpy(hwaddr->sa_data, ifreq.ifr_addr.sa_data, 6);
1188     close(nit_fd);
1189     return 1;
1190 }
1191
1192 /*
1193  * have_route_to - determine if the system has any route to
1194  * a given IP address.
1195  * For demand mode to work properly, we have to ignore routes
1196  * through our own interface.
1197  */
1198 int have_route_to(addr)
1199     u_int32_t addr;
1200 {
1201     return -1;
1202 }
1203
1204 #define WTMPFILE        "/usr/adm/wtmp"
1205
1206 void
1207 logwtmp(line, name, host)
1208     const char *line, *name, *host;
1209 {
1210     int fd;
1211     struct stat buf;
1212     struct utmp ut;
1213
1214     if ((fd = open(WTMPFILE, O_WRONLY|O_APPEND, 0)) < 0)
1215         return;
1216     if (!fstat(fd, &buf)) {
1217         strlcpy(ut.ut_line, sizeof(ut.ut_line), line);
1218         strlcpy(ut.ut_name, sizeof(ut.ut_name), name);
1219         strlcpy(ut.ut_host, sizeof(ut.ut_host), host);
1220         (void)time(&ut.ut_time);
1221         if (write(fd, (char *)&ut, sizeof(struct utmp)) != sizeof(struct utmp))
1222             (void)ftruncate(fd, buf.st_size);
1223     }
1224     close(fd);
1225 }
1226
1227 /*
1228  * Return user specified netmask, modified by any mask we might determine
1229  * for address `addr' (in network byte order).
1230  * Here we scan through the system's list of interfaces, looking for
1231  * any non-point-to-point interfaces which might appear to be on the same
1232  * network as `addr'.  If we find any, we OR in their netmask to the
1233  * user-specified netmask.
1234  */
1235 u_int32_t
1236 GetMask(addr)
1237     u_int32_t addr;
1238 {
1239     u_int32_t mask, nmask, ina;
1240     struct ifreq *ifr, *ifend, ifreq;
1241     struct ifconf ifc;
1242
1243     addr = ntohl(addr);
1244     if (IN_CLASSA(addr))        /* determine network mask for address class */
1245         nmask = IN_CLASSA_NET;
1246     else if (IN_CLASSB(addr))
1247         nmask = IN_CLASSB_NET;
1248     else
1249         nmask = IN_CLASSC_NET;
1250     /* class D nets are disallowed by bad_ip_adrs */
1251     mask = netmask | htonl(nmask);
1252
1253     /*
1254      * Scan through the system's network interfaces.
1255      */
1256     ifc.ifc_len = MAX_IFS * sizeof(struct ifreq);
1257     ifc.ifc_req = alloca(ifc.ifc_len);
1258     if (ifc.ifc_req == 0)
1259         return mask;
1260     if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
1261         warn("Couldn't get system interface list: %m");
1262         return mask;
1263     }
1264     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
1265     for (ifr = ifc.ifc_req; ifr < ifend; ++ifr) {
1266         /*
1267          * Check the interface's internet address.
1268          */
1269         if (ifr->ifr_addr.sa_family != AF_INET)
1270             continue;
1271         ina = INET_ADDR(ifr->ifr_addr);
1272         if ((ntohl(ina) & nmask) != (addr & nmask))
1273             continue;
1274         /*
1275          * Check that the interface is up, and not point-to-point or loopback.
1276          */
1277         strlcpy(ifreq.ifr_name, sizeof(ifreq.ifr_name), ifr->ifr_name);
1278         if (ioctl(sockfd, SIOCGIFFLAGS, &ifreq) < 0)
1279             continue;
1280         if ((ifreq.ifr_flags & (IFF_UP|IFF_POINTOPOINT|IFF_LOOPBACK))
1281             != IFF_UP)
1282             continue;
1283         /*
1284          * Get its netmask and OR it into our mask.
1285          */
1286         if (ioctl(sockfd, SIOCGIFNETMASK, &ifreq) < 0)
1287             continue;
1288         mask |= INET_ADDR(ifreq.ifr_addr);
1289     }
1290
1291     return mask;
1292 }
1293
1294 static int
1295 strioctl(fd, cmd, ptr, ilen, olen)
1296     int fd, cmd, ilen, olen;
1297     void *ptr;
1298 {
1299     struct strioctl str;
1300
1301     str.ic_cmd = cmd;
1302     str.ic_timout = 0;
1303     str.ic_len = ilen;
1304     str.ic_dp = ptr;
1305     if (ioctl(fd, I_STR, &str) == -1)
1306         return -1;
1307     if (str.ic_len != olen)
1308         dbglog("strioctl: expected %d bytes, got %d for cmd %x\n",
1309                olen, str.ic_len, cmd);
1310     return 0;
1311 }
1312
1313 /*
1314  * Use the hostid as part of the random number seed.
1315  */
1316 int
1317 get_host_seed()
1318 {
1319     return gethostid();
1320 }
1321
1322 /*
1323  * Code for locking/unlocking the serial device.
1324  * This code is derived from chat.c.
1325  */
1326
1327 #if !defined(HDB) && !defined(SUNOS3)
1328 #define HDB     1               /* ascii lock files are the default */
1329 #endif
1330
1331 #ifndef LOCK_DIR
1332 # if HDB
1333 #  define       PIDSTRING
1334 #  define       LOCK_PREFIX     "/usr/spool/locks/LCK.."
1335 # else /* HDB */
1336 #  define       LOCK_PREFIX     "/usr/spool/uucp/LCK.."
1337 # endif /* HDB */
1338 #endif /* LOCK_DIR */
1339
1340 static char *lock_file;         /* name of lock file created */
1341
1342 /*
1343  * lock - create a lock file for the named device.
1344  */
1345 int
1346 lock(dev)
1347     char *dev;
1348 {
1349     char hdb_lock_buffer[12];
1350     int fd, pid, n;
1351     char *p;
1352     size_t l;
1353
1354     if ((p = strrchr(dev, '/')) != NULL)
1355         dev = p + 1;
1356     l = strlen(LOCK_PREFIX) + strlen(dev) + 1;
1357     lock_file = malloc(l);
1358     if (lock_file == NULL)
1359         novm("lock file name");
1360     slprintf(lock_file, l, "%s%s", LOCK_PREFIX, dev);
1361
1362     while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
1363         if (errno == EEXIST
1364             && (fd = open(lock_file, O_RDONLY, 0)) >= 0) {
1365             /* Read the lock file to find out who has the device locked */
1366 #ifdef PIDSTRING
1367             n = read(fd, hdb_lock_buffer, 11);
1368             if (n > 0) {
1369                 hdb_lock_buffer[n] = 0;
1370                 pid = atoi(hdb_lock_buffer);
1371             }
1372 #else
1373             n = read(fd, &pid, sizeof(pid));
1374 #endif
1375             if (n <= 0) {
1376                 error("Can't read pid from lock file %s", lock_file);
1377                 close(fd);
1378             } else {
1379                 if (kill(pid, 0) == -1 && errno == ESRCH) {
1380                     /* pid no longer exists - remove the lock file */
1381                     if (unlink(lock_file) == 0) {
1382                         close(fd);
1383                         notice("Removed stale lock on %s (pid %d)",
1384                                dev, pid);
1385                         continue;
1386                     } else
1387                         warn("Couldn't remove stale lock on %s",
1388                                dev);
1389                 } else
1390                     notice("Device %s is locked by pid %d",
1391                            dev, pid);
1392             }
1393             close(fd);
1394         } else
1395             error("Can't create lock file %s: %m", lock_file);
1396         free(lock_file);
1397         lock_file = NULL;
1398         return -1;
1399     }
1400
1401 #ifdef PIDSTRING
1402     slprintf(hdb_lock_buffer, sizeof(hdb_lock_buffer), "%10d\n", getpid());
1403     write(fd, hdb_lock_buffer, 11);
1404 #else
1405     pid = getpid();
1406     write(fd, &pid, sizeof pid);
1407 #endif
1408
1409     close(fd);
1410     return 0;
1411 }
1412
1413 /*
1414  * unlock - remove our lockfile
1415  */
1416 void
1417 unlock()
1418 {
1419     if (lock_file) {
1420         unlink(lock_file);
1421         free(lock_file);
1422         lock_file = NULL;
1423     }
1424 }
1425
1426 /*
1427  * SunOS doesn't have strtoul :-(
1428  */
1429 unsigned long
1430 strtoul(str, ptr, base)
1431     char *str, **ptr;
1432     int base;
1433 {
1434     return (unsigned long) strtol(str, ptr, base);
1435 }
1436
1437 /*
1438  * Or strerror :-(
1439  */
1440 extern char *sys_errlist[];
1441 extern int sys_nerr;
1442
1443 char *
1444 strerror(n)
1445     int n;
1446 {
1447     static char unknown[32];
1448
1449     if (n > 0 && n < sys_nerr)
1450         return sys_errlist[n];
1451     slprintf(unknown, sizeof(unknown), "Error %d", n);
1452     return unknown;
1453 }