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