]> git.ozlabs.org Git - ppp.git/blob - pppd/sys-bsd.c
changed order of args to strlcpy/strlcat.
[ppp.git] / pppd / sys-bsd.c
1 /*
2  * sys-bsd.c - System-dependent procedures for setting up
3  * PPP interfaces on bsd-4.4-ish systems (including 386BSD, NetBSD, etc.)
4  *
5  * Copyright (c) 1989 Carnegie Mellon University.
6  * Copyright (c) 1995 The Australian National University.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms are permitted
10  * provided that the above copyright notice and this paragraph are
11  * duplicated in all such forms and that any documentation,
12  * advertising materials, and other materials related to such
13  * distribution and use acknowledge that the software was developed
14  * by Carnegie Mellon University and The Australian National University.
15  * The names of the Universities may not be used to endorse or promote
16  * products derived from this software without specific prior written
17  * permission.
18  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
20  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21  */
22
23 #ifndef lint
24 static char rcsid[] = "$Id: sys-bsd.c,v 1.39 1999/03/19 01:29:44 paulus Exp $";
25 /*      $NetBSD: sys-bsd.c,v 1.1.1.3 1997/09/26 18:53:04 christos Exp $ */
26 #endif
27
28 /*
29  * TODO:
30  */
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <termios.h>
39 #include <signal.h>
40 #include <sys/ioctl.h>
41 #include <sys/types.h>
42 #include <sys/socket.h>
43 #include <sys/time.h>
44 #include <sys/stat.h>
45 #include <sys/param.h>
46 #ifdef NetBSD1_2
47 #include <util.h>
48 #endif
49 #ifdef PPP_FILTER
50 #include <net/bpf.h>
51 #endif
52
53 #include <net/if.h>
54 #include <net/ppp_defs.h>
55 #include <net/if_ppp.h>
56 #include <net/route.h>
57 #include <net/if_dl.h>
58 #include <netinet/in.h>
59
60 #if RTM_VERSION >= 3
61 #include <sys/param.h>
62 #if defined(NetBSD) && (NetBSD >= 199703)
63 #include <netinet/if_inarp.h>
64 #else   /* NetBSD 1.2D or later */
65 #ifdef __FreeBSD__
66 #include <netinet/if_ether.h>
67 #else
68 #include <net/if_ether.h>
69 #endif
70 #endif
71 #endif
72
73 #include "pppd.h"
74 #include "fsm.h"
75 #include "ipcp.h"
76
77 static int initdisc = -1;       /* Initial TTY discipline for ppp_fd */
78 static int initfdflags = -1;    /* Initial file descriptor flags for ppp_fd */
79 static int ppp_fd = -1;         /* fd which is set to PPP discipline */
80 static int rtm_seq;
81
82 static int restore_term;        /* 1 => we've munged the terminal */
83 static struct termios inittermios; /* Initial TTY termios */
84 static struct winsize wsinfo;   /* Initial window size info */
85
86 static char *lock_file;         /* name of lock file created */
87
88 static int loop_slave = -1;
89 static int loop_master;
90 static char loop_name[20];
91
92 static unsigned char inbuf[512]; /* buffer for chars read from loopback */
93
94 static int sockfd;              /* socket for doing interface ioctls */
95
96 static fd_set in_fds;           /* set of fds that wait_input waits for */
97 static int max_in_fd;           /* highest fd set in in_fds */
98
99 static int if_is_up;            /* the interface is currently up */
100 static u_int32_t ifaddrs[2];    /* local and remote addresses we set */
101 static u_int32_t default_route_gateway; /* gateway addr for default route */
102 static u_int32_t proxy_arp_addr;        /* remote addr for proxy arp */
103
104 /* Prototypes for procedures local to this file. */
105 static int dodefaultroute __P((u_int32_t, int));
106 static int get_ether_addr __P((u_int32_t, struct sockaddr_dl *));
107
108
109 /*
110  * sys_init - System-dependent initialization.
111  */
112 void
113 sys_init()
114 {
115     /* Get an internet socket for doing socket ioctl's on. */
116     if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
117         fatal("Couldn't create IP socket: %m");
118
119     FD_ZERO(&in_fds);
120     max_in_fd = 0;
121 }
122
123 /*
124  * sys_cleanup - restore any system state we modified before exiting:
125  * mark the interface down, delete default route and/or proxy arp entry.
126  * This should call die() because it's called from die().
127  */
128 void
129 sys_cleanup()
130 {
131     struct ifreq ifr;
132
133     if (if_is_up) {
134         strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
135         if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) >= 0
136             && ((ifr.ifr_flags & IFF_UP) != 0)) {
137             ifr.ifr_flags &= ~IFF_UP;
138             ioctl(sockfd, SIOCSIFFLAGS, &ifr);
139         }
140     }
141     if (ifaddrs[0] != 0)
142         cifaddr(0, ifaddrs[0], ifaddrs[1]);
143     if (default_route_gateway)
144         cifdefaultroute(0, 0, default_route_gateway);
145     if (proxy_arp_addr)
146         cifproxyarp(0, proxy_arp_addr);
147 }
148
149 /*
150  * sys_close - Clean up in a child process before execing.
151  */
152 void
153 sys_close()
154 {
155     close(sockfd);
156     if (loop_slave >= 0) {
157         close(loop_slave);
158         close(loop_master);
159     }
160 }
161
162 /*
163  * sys_check_options - check the options that the user specified
164  */
165 int
166 sys_check_options()
167 {
168 #ifndef CDTRCTS
169     if (crtscts == 2) {
170         warn("DTR/CTS flow control is not supported on this system");
171         return 0;
172     }
173 #endif
174     return 1;
175 }
176
177 /*
178  * ppp_available - check whether the system has any ppp interfaces
179  * (in fact we check whether we can do an ioctl on ppp0).
180  */
181 int
182 ppp_available()
183 {
184     int s, ok;
185     struct ifreq ifr;
186     extern char *no_ppp_msg;
187
188     if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
189         return 1;               /* can't tell */
190
191     strlcpy(ifr.ifr_name, "ppp0", sizeof (ifr.ifr_name));
192     ok = ioctl(s, SIOCGIFFLAGS, (caddr_t) &ifr) >= 0;
193     close(s);
194
195     no_ppp_msg = "\
196 This system lacks kernel support for PPP.  To include PPP support\n\
197 in the kernel, please follow the steps detailed in the README.bsd\n\
198 file in the ppp-2.2 distribution.\n";
199     return ok;
200 }
201
202 /*
203  * establish_ppp - Turn the serial port into a ppp interface.
204  */
205 int
206 establish_ppp(fd)
207     int fd;
208 {
209     int pppdisc = PPPDISC;
210     int x;
211
212     if (demand) {
213         /*
214          * Demand mode - prime the old ppp device to relinquish the unit.
215          */
216         if (ioctl(ppp_fd, PPPIOCXFERUNIT, 0) < 0)
217             fatal("ioctl(transfer ppp unit): %m");
218     }
219
220     /*
221      * Save the old line discipline of fd, and set it to PPP.
222      */
223     if (ioctl(fd, TIOCGETD, &initdisc) < 0)
224         fatal("ioctl(TIOCGETD): %m");
225     if (ioctl(fd, TIOCSETD, &pppdisc) < 0)
226         fatal("ioctl(TIOCSETD): %m");
227
228     if (!demand) {
229         /*
230          * Find out which interface we were given.
231          */
232         if (ioctl(fd, PPPIOCGUNIT, &ifunit) < 0) {    
233             fatal("ioctl(PPPIOCGUNIT): %m");
234     } else {
235         /*
236          * Check that we got the same unit again.
237          */
238         if (ioctl(fd, PPPIOCGUNIT, &x) < 0) { 
239             fatal("ioctl(PPPIOCGUNIT): %m");
240         if (x != ifunit)
241             fatal("transfer_ppp failed: wanted unit %d, got %d", ifunit, x);
242         x = TTYDISC;
243         ioctl(loop_slave, TIOCSETD, &x);
244     }
245
246     ppp_fd = fd;
247
248     /*
249      * Enable debug in the driver if requested.
250      */
251     if (kdebugflag) {
252         if (ioctl(fd, PPPIOCGFLAGS, (caddr_t) &x) < 0) {
253             warn("ioctl (PPPIOCGFLAGS): %m");
254         } else {
255             x |= (kdebugflag & 0xFF) * SC_DEBUG;
256             if (ioctl(fd, PPPIOCSFLAGS, (caddr_t) &x) < 0)
257                 warn("ioctl(PPPIOCSFLAGS): %m");
258         }
259     }
260
261     /*
262      * Set device for non-blocking reads.
263      */
264     if ((initfdflags = fcntl(fd, F_GETFL)) == -1
265         || fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
266         warn("Couldn't set device to non-blocking mode: %m");
267     }
268
269     return fd;
270 }
271
272 /*
273  * restore_loop - reattach the ppp unit to the loopback.
274  */
275 void
276 restore_loop()
277 {
278     int x;
279
280     /*
281      * Transfer the ppp interface back to the loopback.
282      */
283     if (ioctl(ppp_fd, PPPIOCXFERUNIT, 0) < 0)
284         fatal("ioctl(transfer ppp unit): %m");
285     x = PPPDISC;
286     if (ioctl(loop_slave, TIOCSETD, &x) < 0)
287         fatal("ioctl(TIOCSETD): %m");
288
289     /*
290      * Check that we got the same unit again.
291      */
292     if (ioctl(loop_slave, PPPIOCGUNIT, &x) < 0)
293         fatal("ioctl(PPPIOCGUNIT): %m");
294     if (x != ifunit)
295         fatal("transfer_ppp failed: wanted unit %d, got %d", ifunit, x);
296     ppp_fd = loop_slave;
297 }
298
299
300 /*
301  * disestablish_ppp - Restore the serial port to normal operation.
302  * This shouldn't call die() because it's called from die().
303  */
304 void
305 disestablish_ppp(fd)
306     int fd;
307 {
308     /* Reset non-blocking mode on fd. */
309     if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
310         warn("Couldn't restore device fd flags: %m");
311     initfdflags = -1;
312
313     /* Restore old line discipline. */
314     if (initdisc >= 0 && ioctl(fd, TIOCSETD, &initdisc) < 0)
315         error("ioctl(TIOCSETD): %m");
316     initdisc = -1;
317
318     if (fd == ppp_fd)
319         ppp_fd = -1;
320 }
321
322 /*
323  * Check whether the link seems not to be 8-bit clean.
324  */
325 void
326 clean_check()
327 {
328     int x;
329     char *s;
330
331     if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &x) == 0) {
332         s = NULL;
333         switch (~x & (SC_RCV_B7_0|SC_RCV_B7_1|SC_RCV_EVNP|SC_RCV_ODDP)) {
334         case SC_RCV_B7_0:
335             s = "bit 7 set to 1";
336             break;
337         case SC_RCV_B7_1:
338             s = "bit 7 set to 0";
339             break;
340         case SC_RCV_EVNP:
341             s = "odd parity";
342             break;
343         case SC_RCV_ODDP:
344             s = "even parity";
345             break;
346         }
347         if (s != NULL) {
348             warn("Serial link is not 8-bit clean:");
349             warn("All received characters had %s", s);
350         }
351     }
352 }
353
354 /*
355  * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
356  * at the requested speed, etc.  If `local' is true, set CLOCAL
357  * regardless of whether the modem option was specified.
358  *
359  * For *BSD, we assume that speed_t values numerically equal bits/second.
360  */
361 void
362 set_up_tty(fd, local)
363     int fd, local;
364 {
365     struct termios tios;
366
367     if (tcgetattr(fd, &tios) < 0)
368         fatal("tcgetattr: %m");
369
370     if (!restore_term) {
371         inittermios = tios;
372         ioctl(fd, TIOCGWINSZ, &wsinfo);
373     }
374
375     tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
376     if (crtscts > 0 && !local) {
377         if (crtscts == 2) {
378 #ifdef CDTRCTS
379             tios.c_cflag |= CDTRCTS;
380 #endif
381         } else
382             tios.c_cflag |= CRTSCTS;
383     } else if (crtscts < 0) {
384         tios.c_cflag &= ~CRTSCTS;
385 #ifdef CDTRCTS
386         tios.c_cflag &= ~CDTRCTS;
387 #endif
388     }
389
390     tios.c_cflag |= CS8 | CREAD | HUPCL;
391     if (local || !modem)
392         tios.c_cflag |= CLOCAL;
393     tios.c_iflag = IGNBRK | IGNPAR;
394     tios.c_oflag = 0;
395     tios.c_lflag = 0;
396     tios.c_cc[VMIN] = 1;
397     tios.c_cc[VTIME] = 0;
398
399     if (crtscts == -2) {
400         tios.c_iflag |= IXON | IXOFF;
401         tios.c_cc[VSTOP] = 0x13;        /* DC3 = XOFF = ^S */
402         tios.c_cc[VSTART] = 0x11;       /* DC1 = XON  = ^Q */
403     }
404
405     if (inspeed) {
406         cfsetospeed(&tios, inspeed);
407         cfsetispeed(&tios, inspeed);
408     } else {
409         inspeed = cfgetospeed(&tios);
410         /*
411          * We can't proceed if the serial port speed is 0,
412          * since that implies that the serial port is disabled.
413          */
414         if (inspeed == 0)
415             fatal("Baud rate for %s is 0; need explicit baud rate", devnam);
416     }
417     baud_rate = inspeed;
418
419     if (tcsetattr(fd, TCSAFLUSH, &tios) < 0)
420         fatal("tcsetattr: %m");
421
422     restore_term = 1;
423 }
424
425 /*
426  * restore_tty - restore the terminal to the saved settings.
427  */
428 void
429 restore_tty(fd)
430     int fd;
431 {
432     if (restore_term) {
433         if (!default_device) {
434             /*
435              * Turn off echoing, because otherwise we can get into
436              * a loop with the tty and the modem echoing to each other.
437              * We presume we are the sole user of this tty device, so
438              * when we close it, it will revert to its defaults anyway.
439              */
440             inittermios.c_lflag &= ~(ECHO | ECHONL);
441         }
442         if (tcsetattr(fd, TCSAFLUSH, &inittermios) < 0)
443             if (errno != ENXIO)
444                 warn("tcsetattr: %m");
445         ioctl(fd, TIOCSWINSZ, &wsinfo);
446         restore_term = 0;
447     }
448 }
449
450 /*
451  * setdtr - control the DTR line on the serial port.
452  * This is called from die(), so it shouldn't call die().
453  */
454 void
455 setdtr(fd, on)
456 int fd, on;
457 {
458     int modembits = TIOCM_DTR;
459
460     ioctl(fd, (on? TIOCMBIS: TIOCMBIC), &modembits);
461 }
462
463
464 /*
465  * open_ppp_loopback - open the device we use for getting
466  * packets in demand mode, and connect it to a ppp interface.
467  * Here we use a pty.
468  */
469 int
470 open_ppp_loopback()
471 {
472     int flags;
473     struct termios tios;
474     int pppdisc = PPPDISC;
475
476     if (openpty(&loop_master, &loop_slave, loop_name, NULL, NULL) < 0)
477         fatal("No free pty for loopback");
478     SYSDEBUG(("using %s for loopback", loop_name));
479
480     if (tcgetattr(loop_slave, &tios) == 0) {
481         tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB);
482         tios.c_cflag |= CS8 | CREAD;
483         tios.c_iflag = IGNPAR;
484         tios.c_oflag = 0;
485         tios.c_lflag = 0;
486         if (tcsetattr(loop_slave, TCSAFLUSH, &tios) < 0)
487             warn("couldn't set attributes on loopback: %m");
488     }
489
490     if ((flags = fcntl(loop_master, F_GETFL)) != -1) 
491         if (fcntl(loop_master, F_SETFL, flags | O_NONBLOCK) == -1)
492             warn("couldn't set loopback to nonblock: %m");
493
494     ppp_fd = loop_slave;
495     if (ioctl(ppp_fd, TIOCSETD, &pppdisc) < 0)
496         fatal("ioctl(TIOCSETD): %m");
497
498     /*
499      * Find out which interface we were given.
500      */
501     if (ioctl(ppp_fd, PPPIOCGUNIT, &ifunit) < 0)
502         fatal("ioctl(PPPIOCGUNIT): %m");
503
504     /*
505      * Enable debug in the driver if requested.
506      */
507     if (kdebugflag) {
508         if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &flags) < 0) {
509             warn("ioctl (PPPIOCGFLAGS): %m");
510         } else {
511             flags |= (kdebugflag & 0xFF) * SC_DEBUG;
512             if (ioctl(ppp_fd, PPPIOCSFLAGS, (caddr_t) &flags) < 0)
513                 warn("ioctl(PPPIOCSFLAGS): %m");
514         }
515     }
516
517     return loop_master;
518 }
519
520
521 /*
522  * output - Output PPP packet.
523  */
524 void
525 output(unit, p, len)
526     int unit;
527     u_char *p;
528     int len;
529 {
530     if (debug)
531         dbglog("sent %P", p, len);
532
533     if (write(ttyfd, p, len) < 0) {
534         if (errno != EIO)
535             error("write: %m");
536     }
537 }
538
539
540 /*
541  * wait_input - wait until there is data available,
542  * for the length of time specified by *timo (indefinite
543  * if timo is NULL).
544  */
545 void
546 wait_input(timo)
547     struct timeval *timo;
548 {
549     fd_set ready;
550     int n;
551
552     ready = in_fds;
553     n = select(max_in_fd + 1, &ready, NULL, &ready, timo);
554     if (n < 0 && errno != EINTR)
555         fatal("select: %m");
556 }
557
558
559 /*
560  * add_fd - add an fd to the set that wait_input waits for.
561  */
562 void add_fd(int fd)
563 {
564     FD_SET(fd, &in_fds);
565     if (fd > max_in_fd)
566         max_in_fd = fd;
567 }
568
569 /*
570  * remove_fd - remove an fd from the set that wait_input waits for.
571  */
572 void remove_fd(int fd)
573 {
574     FD_CLR(fd, &in_fds);
575 }
576
577 #if 0
578 /*
579  * wait_loop_output - wait until there is data available on the
580  * loopback, for the length of time specified by *timo (indefinite
581  * if timo is NULL).
582  */
583 void
584 wait_loop_output(timo)
585     struct timeval *timo;
586 {
587     fd_set ready;
588     int n;
589
590     FD_ZERO(&ready);
591     FD_SET(loop_master, &ready);
592     n = select(loop_master + 1, &ready, NULL, &ready, timo);
593     if (n < 0 && errno != EINTR)
594         fatal("select: %m");
595 }
596
597
598 /*
599  * wait_time - wait for a given length of time or until a
600  * signal is received.
601  */
602 void
603 wait_time(timo)
604     struct timeval *timo;
605 {
606     int n;
607
608     n = select(0, NULL, NULL, NULL, timo);
609     if (n < 0 && errno != EINTR)
610         fatal("select: %m");
611 }
612 #endif
613
614
615 /*
616  * read_packet - get a PPP packet from the serial device.
617  */
618 int
619 read_packet(buf)
620     u_char *buf;
621 {
622     int len;
623
624     if ((len = read(ttyfd, buf, PPP_MTU + PPP_HDRLEN)) < 0) {
625         if (errno == EWOULDBLOCK || errno == EINTR)
626             return -1;
627         fatal("read: %m");
628     }
629     return len;
630 }
631
632
633 /*
634  * get_loop_output - read characters from the loopback, form them
635  * into frames, and detect when we want to bring the real link up.
636  * Return value is 1 if we need to bring up the link, 0 otherwise.
637  */
638 int
639 get_loop_output()
640 {
641     int rv = 0;
642     int n;
643
644     while ((n = read(loop_master, inbuf, sizeof(inbuf))) >= 0) {
645         if (loop_chars(inbuf, n))
646             rv = 1;
647     }
648
649     if (n == 0)
650         fatal("eof on loopback");
651     if (errno != EWOULDBLOCK)
652         fatal("read from loopback: %m");
653
654     return rv;
655 }
656
657
658 /*
659  * ppp_send_config - configure the transmit characteristics of
660  * the ppp interface.
661  */
662 void
663 ppp_send_config(unit, mtu, asyncmap, pcomp, accomp)
664     int unit, mtu;
665     u_int32_t asyncmap;
666     int pcomp, accomp;
667 {
668     u_int x;
669     struct ifreq ifr;
670
671     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
672     ifr.ifr_mtu = mtu;
673     if (ioctl(sockfd, SIOCSIFMTU, (caddr_t) &ifr) < 0)
674         fatal("ioctl(SIOCSIFMTU): %m");
675
676     if (ioctl(ppp_fd, PPPIOCSASYNCMAP, (caddr_t) &asyncmap) < 0)
677         fatal("ioctl(PPPIOCSASYNCMAP): %m");
678
679     if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &x) < 0)
680         fatal("ioctl (PPPIOCGFLAGS): %m");
681     x = pcomp? x | SC_COMP_PROT: x &~ SC_COMP_PROT;
682     x = accomp? x | SC_COMP_AC: x &~ SC_COMP_AC;
683     if (ioctl(ppp_fd, PPPIOCSFLAGS, (caddr_t) &x) < 0)
684         fatal("ioctl(PPPIOCSFLAGS): %m");
685 }
686
687
688 /*
689  * ppp_set_xaccm - set the extended transmit ACCM for the interface.
690  */
691 void
692 ppp_set_xaccm(unit, accm)
693     int unit;
694     ext_accm accm;
695 {
696     if (ioctl(ppp_fd, PPPIOCSXASYNCMAP, accm) < 0 && errno != ENOTTY)
697         warn("ioctl(set extended ACCM): %m");
698 }
699
700
701 /*
702  * ppp_recv_config - configure the receive-side characteristics of
703  * the ppp interface.
704  */
705 void
706 ppp_recv_config(unit, mru, asyncmap, pcomp, accomp)
707     int unit, mru;
708     u_int32_t asyncmap;
709     int pcomp, accomp;
710 {
711     int x;
712
713     if (ioctl(ppp_fd, PPPIOCSMRU, (caddr_t) &mru) < 0)
714         fatal("ioctl(PPPIOCSMRU): %m");
715     if (ioctl(ppp_fd, PPPIOCSRASYNCMAP, (caddr_t) &asyncmap) < 0)
716         fatal("ioctl(PPPIOCSRASYNCMAP): %m");
717     if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &x) < 0)
718         fatal("ioctl (PPPIOCGFLAGS): %m");
719     x = !accomp? x | SC_REJ_COMP_AC: x &~ SC_REJ_COMP_AC;
720     if (ioctl(ppp_fd, PPPIOCSFLAGS, (caddr_t) &x) < 0)
721         fatal("ioctl(PPPIOCSFLAGS): %m");
722 }
723
724 /*
725  * ccp_test - ask kernel whether a given compression method
726  * is acceptable for use.  Returns 1 if the method and parameters
727  * are OK, 0 if the method is known but the parameters are not OK
728  * (e.g. code size should be reduced), or -1 if the method is unknown.
729  */
730 int
731 ccp_test(unit, opt_ptr, opt_len, for_transmit)
732     int unit, opt_len, for_transmit;
733     u_char *opt_ptr;
734 {
735     struct ppp_option_data data;
736
737     data.ptr = opt_ptr;
738     data.length = opt_len;
739     data.transmit = for_transmit;
740     if (ioctl(ttyfd, PPPIOCSCOMPRESS, (caddr_t) &data) >= 0)
741         return 1;
742     return (errno == ENOBUFS)? 0: -1;
743 }
744
745 /*
746  * ccp_flags_set - inform kernel about the current state of CCP.
747  */
748 void
749 ccp_flags_set(unit, isopen, isup)
750     int unit, isopen, isup;
751 {
752     int x;
753
754     if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &x) < 0) {
755         error("ioctl (PPPIOCGFLAGS): %m");
756         return;
757     }
758     x = isopen? x | SC_CCP_OPEN: x &~ SC_CCP_OPEN;
759     x = isup? x | SC_CCP_UP: x &~ SC_CCP_UP;
760     if (ioctl(ppp_fd, PPPIOCSFLAGS, (caddr_t) &x) < 0)
761         error("ioctl(PPPIOCSFLAGS): %m");
762 }
763
764 /*
765  * ccp_fatal_error - returns 1 if decompression was disabled as a
766  * result of an error detected after decompression of a packet,
767  * 0 otherwise.  This is necessary because of patent nonsense.
768  */
769 int
770 ccp_fatal_error(unit)
771     int unit;
772 {
773     int x;
774
775     if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &x) < 0) {
776         error("ioctl(PPPIOCGFLAGS): %m");
777         return 0;
778     }
779     return x & SC_DC_FERROR;
780 }
781
782 /*
783  * get_idle_time - return how long the link has been idle.
784  */
785 int
786 get_idle_time(u, ip)
787     int u;
788     struct ppp_idle *ip;
789 {
790     return ioctl(ppp_fd, PPPIOCGIDLE, ip) >= 0;
791 }
792
793
794 #ifdef PPP_FILTER
795 /*
796  * set_filters - transfer the pass and active filters to the kernel.
797  */
798 int
799 set_filters(pass, active)
800     struct bpf_program *pass, *active;
801 {
802     int ret = 1;
803
804     if (pass->bf_len > 0) {
805         if (ioctl(ppp_fd, PPPIOCSPASS, pass) < 0) {
806             error("Couldn't set pass-filter in kernel: %m");
807             ret = 0;
808         }
809     }
810     if (active->bf_len > 0) {
811         if (ioctl(ppp_fd, PPPIOCSACTIVE, active) < 0) {
812             error("Couldn't set active-filter in kernel: %m");
813             ret = 0;
814         }
815     }
816     return ret;
817 }
818 #endif
819
820 /*
821  * sifvjcomp - config tcp header compression
822  */
823 int
824 sifvjcomp(u, vjcomp, cidcomp, maxcid)
825     int u, vjcomp, cidcomp, maxcid;
826 {
827     u_int x;
828
829     if (ioctl(ppp_fd, PPPIOCGFLAGS, (caddr_t) &x) < 0) {
830         error("ioctl (PPPIOCGFLAGS): %m");
831         return 0;
832     }
833     x = vjcomp ? x | SC_COMP_TCP: x &~ SC_COMP_TCP;
834     x = cidcomp? x & ~SC_NO_TCP_CCID: x | SC_NO_TCP_CCID;
835     if (ioctl(ppp_fd, PPPIOCSFLAGS, (caddr_t) &x) < 0) {
836         error("ioctl(PPPIOCSFLAGS): %m");
837         return 0;
838     }
839     if (vjcomp && ioctl(ppp_fd, PPPIOCSMAXCID, (caddr_t) &maxcid) < 0) {
840         error("ioctl(PPPIOCSFLAGS): %m");
841         return 0;
842     }
843     return 1;
844 }
845
846 /*
847  * sifup - Config the interface up and enable IP packets to pass.
848  */
849 int
850 sifup(u)
851     int u;
852 {
853     struct ifreq ifr;
854
855     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
856     if (ioctl(sockfd, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
857         error("ioctl (SIOCGIFFLAGS): %m");
858         return 0;
859     }
860     ifr.ifr_flags |= IFF_UP;
861     if (ioctl(sockfd, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) {
862         error("ioctl(SIOCSIFFLAGS): %m");
863         return 0;
864     }
865     if_is_up = 1;
866     return 1;
867 }
868
869 /*
870  * sifnpmode - Set the mode for handling packets for a given NP.
871  */
872 int
873 sifnpmode(u, proto, mode)
874     int u;
875     int proto;
876     enum NPmode mode;
877 {
878     struct npioctl npi;
879
880     npi.protocol = proto;
881     npi.mode = mode;
882     if (ioctl(ppp_fd, PPPIOCSNPMODE, &npi) < 0) {
883         error("ioctl(set NP %d mode to %d): %m", proto, mode);
884         return 0;
885     }
886     return 1;
887 }
888
889 /*
890  * sifdown - Config the interface down and disable IP.
891  */
892 int
893 sifdown(u)
894     int u;
895 {
896     struct ifreq ifr;
897     int rv;
898     struct npioctl npi;
899
900     rv = 1;
901     npi.protocol = PPP_IP;
902     npi.mode = NPMODE_ERROR;
903     ioctl(ppp_fd, PPPIOCSNPMODE, (caddr_t) &npi);
904     /* ignore errors, because ppp_fd might have been closed by now. */
905
906     strlcpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
907     if (ioctl(sockfd, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
908         error("ioctl (SIOCGIFFLAGS): %m");
909         rv = 0;
910     } else {
911         ifr.ifr_flags &= ~IFF_UP;
912         if (ioctl(sockfd, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) {
913             error("ioctl(SIOCSIFFLAGS): %m");
914             rv = 0;
915         } else
916             if_is_up = 0;
917     }
918     return rv;
919 }
920
921 /*
922  * SET_SA_FAMILY - set the sa_family field of a struct sockaddr,
923  * if it exists.
924  */
925 #define SET_SA_FAMILY(addr, family)             \
926     BZERO((char *) &(addr), sizeof(addr));      \
927     addr.sa_family = (family);                  \
928     addr.sa_len = sizeof(addr);
929
930 /*
931  * sifaddr - Config the interface IP addresses and netmask.
932  */
933 int
934 sifaddr(u, o, h, m)
935     int u;
936     u_int32_t o, h, m;
937 {
938     struct ifaliasreq ifra;
939     struct ifreq ifr;
940
941     strlcpy(ifra.ifra_name, ifname, sizeof(ifra.ifra_name));
942     SET_SA_FAMILY(ifra.ifra_addr, AF_INET);
943     ((struct sockaddr_in *) &ifra.ifra_addr)->sin_addr.s_addr = o;
944     SET_SA_FAMILY(ifra.ifra_broadaddr, AF_INET);
945     ((struct sockaddr_in *) &ifra.ifra_broadaddr)->sin_addr.s_addr = h;
946     if (m != 0) {
947         SET_SA_FAMILY(ifra.ifra_mask, AF_INET);
948         ((struct sockaddr_in *) &ifra.ifra_mask)->sin_addr.s_addr = m;
949     } else
950         BZERO(&ifra.ifra_mask, sizeof(ifra.ifra_mask));
951     BZERO(&ifr, sizeof(ifr));
952     strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
953     if (ioctl(sockfd, SIOCDIFADDR, (caddr_t) &ifr) < 0) {
954         if (errno != EADDRNOTAVAIL)
955             warn("Couldn't remove interface address: %m");
956     }
957     if (ioctl(sockfd, SIOCAIFADDR, (caddr_t) &ifra) < 0) {
958         if (errno != EEXIST) {
959             error("Couldn't set interface address: %m");
960             return 0;
961         }
962         warn("Couldn't set interface address: Address %I already exists", o);
963     }
964     ifaddrs[0] = o;
965     ifaddrs[1] = h;
966     return 1;
967 }
968
969 /*
970  * cifaddr - Clear the interface IP addresses, and delete routes
971  * through the interface if possible.
972  */
973 int
974 cifaddr(u, o, h)
975     int u;
976     u_int32_t o, h;
977 {
978     struct ifaliasreq ifra;
979
980     ifaddrs[0] = 0;
981     strlcpy(ifra.ifra_name, ifname, sizeof(ifra.ifra_name));
982     SET_SA_FAMILY(ifra.ifra_addr, AF_INET);
983     ((struct sockaddr_in *) &ifra.ifra_addr)->sin_addr.s_addr = o;
984     SET_SA_FAMILY(ifra.ifra_broadaddr, AF_INET);
985     ((struct sockaddr_in *) &ifra.ifra_broadaddr)->sin_addr.s_addr = h;
986     BZERO(&ifra.ifra_mask, sizeof(ifra.ifra_mask));
987     if (ioctl(sockfd, SIOCDIFADDR, (caddr_t) &ifra) < 0) {
988         if (errno != EADDRNOTAVAIL)
989             warn("Couldn't delete interface address: %m");
990         return 0;
991     }
992     return 1;
993 }
994
995 /*
996  * sifdefaultroute - assign a default route through the address given.
997  */
998 int
999 sifdefaultroute(u, l, g)
1000     int u;
1001     u_int32_t l, g;
1002 {
1003     return dodefaultroute(g, 's');
1004 }
1005
1006 /*
1007  * cifdefaultroute - delete a default route through the address given.
1008  */
1009 int
1010 cifdefaultroute(u, l, g)
1011     int u;
1012     u_int32_t l, g;
1013 {
1014     return dodefaultroute(g, 'c');
1015 }
1016
1017 /*
1018  * dodefaultroute - talk to a routing socket to add/delete a default route.
1019  */
1020 static int
1021 dodefaultroute(g, cmd)
1022     u_int32_t g;
1023     int cmd;
1024 {
1025     int routes;
1026     struct {
1027         struct rt_msghdr        hdr;
1028         struct sockaddr_in      dst;
1029         struct sockaddr_in      gway;
1030         struct sockaddr_in      mask;
1031     } rtmsg;
1032
1033     if ((routes = socket(PF_ROUTE, SOCK_RAW, AF_INET)) < 0) {
1034         error("Couldn't %s default route: socket: %m",
1035                cmd=='s'? "add": "delete");
1036         return 0;
1037     }
1038
1039     memset(&rtmsg, 0, sizeof(rtmsg));
1040     rtmsg.hdr.rtm_type = cmd == 's'? RTM_ADD: RTM_DELETE;
1041     rtmsg.hdr.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
1042     rtmsg.hdr.rtm_version = RTM_VERSION;
1043     rtmsg.hdr.rtm_seq = ++rtm_seq;
1044     rtmsg.hdr.rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
1045     rtmsg.dst.sin_len = sizeof(rtmsg.dst);
1046     rtmsg.dst.sin_family = AF_INET;
1047     rtmsg.gway.sin_len = sizeof(rtmsg.gway);
1048     rtmsg.gway.sin_family = AF_INET;
1049     rtmsg.gway.sin_addr.s_addr = g;
1050     rtmsg.mask.sin_len = sizeof(rtmsg.dst);
1051     rtmsg.mask.sin_family = AF_INET;
1052
1053     rtmsg.hdr.rtm_msglen = sizeof(rtmsg);
1054     if (write(routes, &rtmsg, sizeof(rtmsg)) < 0) {
1055         error("Couldn't %s default route: %m",
1056                cmd=='s'? "add": "delete");
1057         close(routes);
1058         return 0;
1059     }
1060
1061     close(routes);
1062     default_route_gateway = (cmd == 's')? g: 0;
1063     return 1;
1064 }
1065
1066 #if RTM_VERSION >= 3
1067
1068 /*
1069  * sifproxyarp - Make a proxy ARP entry for the peer.
1070  */
1071 static struct {
1072     struct rt_msghdr            hdr;
1073     struct sockaddr_inarp       dst;
1074     struct sockaddr_dl          hwa;
1075     char                        extra[128];
1076 } arpmsg;
1077
1078 static int arpmsg_valid;
1079
1080 int
1081 sifproxyarp(unit, hisaddr)
1082     int unit;
1083     u_int32_t hisaddr;
1084 {
1085     int routes;
1086
1087     /*
1088      * Get the hardware address of an interface on the same subnet
1089      * as our local address.
1090      */
1091     memset(&arpmsg, 0, sizeof(arpmsg));
1092     if (!get_ether_addr(hisaddr, &arpmsg.hwa)) {
1093         error("Cannot determine ethernet address for proxy ARP");
1094         return 0;
1095     }
1096
1097     if ((routes = socket(PF_ROUTE, SOCK_RAW, AF_INET)) < 0) {
1098         error("Couldn't add proxy arp entry: socket: %m");
1099         return 0;
1100     }
1101
1102     arpmsg.hdr.rtm_type = RTM_ADD;
1103     arpmsg.hdr.rtm_flags = RTF_ANNOUNCE | RTF_HOST | RTF_STATIC;
1104     arpmsg.hdr.rtm_version = RTM_VERSION;
1105     arpmsg.hdr.rtm_seq = ++rtm_seq;
1106     arpmsg.hdr.rtm_addrs = RTA_DST | RTA_GATEWAY;
1107     arpmsg.hdr.rtm_inits = RTV_EXPIRE;
1108     arpmsg.dst.sin_len = sizeof(struct sockaddr_inarp);
1109     arpmsg.dst.sin_family = AF_INET;
1110     arpmsg.dst.sin_addr.s_addr = hisaddr;
1111     arpmsg.dst.sin_other = SIN_PROXY;
1112
1113     arpmsg.hdr.rtm_msglen = (char *) &arpmsg.hwa - (char *) &arpmsg
1114         + arpmsg.hwa.sdl_len;
1115     if (write(routes, &arpmsg, arpmsg.hdr.rtm_msglen) < 0) {
1116         error("Couldn't add proxy arp entry: %m");
1117         close(routes);
1118         return 0;
1119     }
1120
1121     close(routes);
1122     arpmsg_valid = 1;
1123     proxy_arp_addr = hisaddr;
1124     return 1;
1125 }
1126
1127 /*
1128  * cifproxyarp - Delete the proxy ARP entry for the peer.
1129  */
1130 int
1131 cifproxyarp(unit, hisaddr)
1132     int unit;
1133     u_int32_t hisaddr;
1134 {
1135     int routes;
1136
1137     if (!arpmsg_valid)
1138         return 0;
1139     arpmsg_valid = 0;
1140
1141     arpmsg.hdr.rtm_type = RTM_DELETE;
1142     arpmsg.hdr.rtm_seq = ++rtm_seq;
1143
1144     if ((routes = socket(PF_ROUTE, SOCK_RAW, AF_INET)) < 0) {
1145         error("Couldn't delete proxy arp entry: socket: %m");
1146         return 0;
1147     }
1148
1149     if (write(routes, &arpmsg, arpmsg.hdr.rtm_msglen) < 0) {
1150         error("Couldn't delete proxy arp entry: %m");
1151         close(routes);
1152         return 0;
1153     }
1154
1155     close(routes);
1156     proxy_arp_addr = 0;
1157     return 1;
1158 }
1159
1160 #else   /* RTM_VERSION */
1161
1162 /*
1163  * sifproxyarp - Make a proxy ARP entry for the peer.
1164  */
1165 int
1166 sifproxyarp(unit, hisaddr)
1167     int unit;
1168     u_int32_t hisaddr;
1169 {
1170     struct arpreq arpreq;
1171     struct {
1172         struct sockaddr_dl      sdl;
1173         char                    space[128];
1174     } dls;
1175
1176     BZERO(&arpreq, sizeof(arpreq));
1177
1178     /*
1179      * Get the hardware address of an interface on the same subnet
1180      * as our local address.
1181      */
1182     if (!get_ether_addr(hisaddr, &dls.sdl)) {
1183         error("Cannot determine ethernet address for proxy ARP");
1184         return 0;
1185     }
1186
1187     arpreq.arp_ha.sa_len = sizeof(struct sockaddr);
1188     arpreq.arp_ha.sa_family = AF_UNSPEC;
1189     BCOPY(LLADDR(&dls.sdl), arpreq.arp_ha.sa_data, dls.sdl.sdl_alen);
1190     SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
1191     ((struct sockaddr_in *) &arpreq.arp_pa)->sin_addr.s_addr = hisaddr;
1192     arpreq.arp_flags = ATF_PERM | ATF_PUBL;
1193     if (ioctl(sockfd, SIOCSARP, (caddr_t)&arpreq) < 0) {
1194         error("Couldn't add proxy arp entry: %m");
1195         return 0;
1196     }
1197
1198     proxy_arp_addr = hisaddr;
1199     return 1;
1200 }
1201
1202 /*
1203  * cifproxyarp - Delete the proxy ARP entry for the peer.
1204  */
1205 int
1206 cifproxyarp(unit, hisaddr)
1207     int unit;
1208     u_int32_t hisaddr;
1209 {
1210     struct arpreq arpreq;
1211
1212     BZERO(&arpreq, sizeof(arpreq));
1213     SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
1214     ((struct sockaddr_in *) &arpreq.arp_pa)->sin_addr.s_addr = hisaddr;
1215     if (ioctl(sockfd, SIOCDARP, (caddr_t)&arpreq) < 0) {
1216         warn("Couldn't delete proxy arp entry: %m");
1217         return 0;
1218     }
1219     proxy_arp_addr = 0;
1220     return 1;
1221 }
1222 #endif  /* RTM_VERSION */
1223
1224
1225 /*
1226  * get_ether_addr - get the hardware address of an interface on the
1227  * the same subnet as ipaddr.
1228  */
1229 #define MAX_IFS         32
1230
1231 static int
1232 get_ether_addr(ipaddr, hwaddr)
1233     u_int32_t ipaddr;
1234     struct sockaddr_dl *hwaddr;
1235 {
1236     struct ifreq *ifr, *ifend, *ifp;
1237     u_int32_t ina, mask;
1238     struct sockaddr_dl *dla;
1239     struct ifreq ifreq;
1240     struct ifconf ifc;
1241     struct ifreq ifs[MAX_IFS];
1242
1243     ifc.ifc_len = sizeof(ifs);
1244     ifc.ifc_req = ifs;
1245     if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
1246         error("ioctl(SIOCGIFCONF): %m");
1247         return 0;
1248     }
1249
1250     /*
1251      * Scan through looking for an interface with an Internet
1252      * address on the same subnet as `ipaddr'.
1253      */
1254     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
1255     for (ifr = ifc.ifc_req; ifr < ifend; ifr = (struct ifreq *)
1256                 ((char *)&ifr->ifr_addr + ifr->ifr_addr.sa_len)) {
1257         if (ifr->ifr_addr.sa_family == AF_INET) {
1258             ina = ((struct sockaddr_in *) &ifr->ifr_addr)->sin_addr.s_addr;
1259             strlcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
1260             /*
1261              * Check that the interface is up, and not point-to-point
1262              * or loopback.
1263              */
1264             if (ioctl(sockfd, SIOCGIFFLAGS, &ifreq) < 0)
1265                 continue;
1266             if ((ifreq.ifr_flags &
1267                  (IFF_UP|IFF_BROADCAST|IFF_POINTOPOINT|IFF_LOOPBACK|IFF_NOARP))
1268                  != (IFF_UP|IFF_BROADCAST))
1269                 continue;
1270             /*
1271              * Get its netmask and check that it's on the right subnet.
1272              */
1273             if (ioctl(sockfd, SIOCGIFNETMASK, &ifreq) < 0)
1274                 continue;
1275             mask = ((struct sockaddr_in *) &ifreq.ifr_addr)->sin_addr.s_addr;
1276             if ((ipaddr & mask) != (ina & mask))
1277                 continue;
1278
1279             break;
1280         }
1281     }
1282
1283     if (ifr >= ifend)
1284         return 0;
1285     info("found interface %s for proxy arp", ifr->ifr_name);
1286
1287     /*
1288      * Now scan through again looking for a link-level address
1289      * for this interface.
1290      */
1291     ifp = ifr;
1292     for (ifr = ifc.ifc_req; ifr < ifend; ) {
1293         if (strcmp(ifp->ifr_name, ifr->ifr_name) == 0
1294             && ifr->ifr_addr.sa_family == AF_LINK) {
1295             /*
1296              * Found the link-level address - copy it out
1297              */
1298             dla = (struct sockaddr_dl *) &ifr->ifr_addr;
1299             BCOPY(dla, hwaddr, dla->sdl_len);
1300             return 1;
1301         }
1302         ifr = (struct ifreq *) ((char *)&ifr->ifr_addr + ifr->ifr_addr.sa_len);
1303     }
1304
1305     return 0;
1306 }
1307
1308 /*
1309  * Return user specified netmask, modified by any mask we might determine
1310  * for address `addr' (in network byte order).
1311  * Here we scan through the system's list of interfaces, looking for
1312  * any non-point-to-point interfaces which might appear to be on the same
1313  * network as `addr'.  If we find any, we OR in their netmask to the
1314  * user-specified netmask.
1315  */
1316 u_int32_t
1317 GetMask(addr)
1318     u_int32_t addr;
1319 {
1320     u_int32_t mask, nmask, ina;
1321     struct ifreq *ifr, *ifend, ifreq;
1322     struct ifconf ifc;
1323     struct ifreq ifs[MAX_IFS];
1324
1325     addr = ntohl(addr);
1326     if (IN_CLASSA(addr))        /* determine network mask for address class */
1327         nmask = IN_CLASSA_NET;
1328     else if (IN_CLASSB(addr))
1329         nmask = IN_CLASSB_NET;
1330     else
1331         nmask = IN_CLASSC_NET;
1332     /* class D nets are disallowed by bad_ip_adrs */
1333     mask = netmask | htonl(nmask);
1334
1335     /*
1336      * Scan through the system's network interfaces.
1337      */
1338     ifc.ifc_len = sizeof(ifs);
1339     ifc.ifc_req = ifs;
1340     if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
1341         warn("ioctl(SIOCGIFCONF): %m");
1342         return mask;
1343     }
1344     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
1345     for (ifr = ifc.ifc_req; ifr < ifend; ifr = (struct ifreq *)
1346                 ((char *)&ifr->ifr_addr + ifr->ifr_addr.sa_len)) {
1347         /*
1348          * Check the interface's internet address.
1349          */
1350         if (ifr->ifr_addr.sa_family != AF_INET)
1351             continue;
1352         ina = ((struct sockaddr_in *) &ifr->ifr_addr)->sin_addr.s_addr;
1353         if ((ntohl(ina) & nmask) != (addr & nmask))
1354             continue;
1355         /*
1356          * Check that the interface is up, and not point-to-point or loopback.
1357          */
1358         strlcpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
1359         if (ioctl(sockfd, SIOCGIFFLAGS, &ifreq) < 0)
1360             continue;
1361         if ((ifreq.ifr_flags & (IFF_UP|IFF_POINTOPOINT|IFF_LOOPBACK))
1362             != IFF_UP)
1363             continue;
1364         /*
1365          * Get its netmask and OR it into our mask.
1366          */
1367         if (ioctl(sockfd, SIOCGIFNETMASK, &ifreq) < 0)
1368             continue;
1369         mask |= ((struct sockaddr_in *)&ifreq.ifr_addr)->sin_addr.s_addr;
1370     }
1371
1372     return mask;
1373 }
1374
1375 /*
1376  * have_route_to - determine if the system has any route to
1377  * a given IP address.
1378  * For demand mode to work properly, we have to ignore routes
1379  * through our own interface.
1380  */
1381 int have_route_to(u_int32_t addr)
1382 {
1383     return -1;
1384 }
1385
1386 /*
1387  * Use the hostid as part of the random number seed.
1388  */
1389 int
1390 get_host_seed()
1391 {
1392     return gethostid();
1393 }
1394
1395 /*
1396  * lock - create a lock file for the named lock device
1397  */
1398 #define LOCK_PREFIX     "/var/spool/lock/LCK.."
1399
1400 int
1401 lock(dev)
1402     char *dev;
1403 {
1404     char hdb_lock_buffer[12];
1405     int fd, pid, n;
1406     char *p;
1407     size_t l;
1408
1409     if ((p = strrchr(dev, '/')) != NULL)
1410         dev = p + 1;
1411     l = strlen(LOCK_PREFIX) + strlen(dev) + 1;
1412     lock_file = malloc(l);
1413     if (lock_file == NULL)
1414         novm("lock file name");
1415     slprintf(lock_file, l, "%s%s", LOCK_PREFIX, dev);
1416
1417     while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
1418         if (errno == EEXIST
1419             && (fd = open(lock_file, O_RDONLY, 0)) >= 0) {
1420             /* Read the lock file to find out who has the device locked */
1421             n = read(fd, hdb_lock_buffer, 11);
1422             if (n <= 0) {
1423                 error("Can't read pid from lock file %s", lock_file);
1424                 close(fd);
1425             } else {
1426                 hdb_lock_buffer[n] = 0;
1427                 pid = atoi(hdb_lock_buffer);
1428                 if (kill(pid, 0) == -1 && errno == ESRCH) {
1429                     /* pid no longer exists - remove the lock file */
1430                     if (unlink(lock_file) == 0) {
1431                         close(fd);
1432                         notice("Removed stale lock on %s (pid %d)",
1433                                dev, pid);
1434                         continue;
1435                     } else
1436                         warn("Couldn't remove stale lock on %s",
1437                                dev);
1438                 } else
1439                     notice("Device %s is locked by pid %d",
1440                            dev, pid);
1441             }
1442             close(fd);
1443         } else
1444             error("Can't create lock file %s: %m", lock_file);
1445         free(lock_file);
1446         lock_file = NULL;
1447         return -1;
1448     }
1449
1450     slprintf(hdb_lock_buffer, sizeof(hdb_lock_buffer), "%10d\n", getpid());
1451     write(fd, hdb_lock_buffer, 11);
1452
1453     close(fd);
1454     return 0;
1455 }
1456
1457 /*
1458  * unlock - remove our lockfile
1459  */
1460 void
1461 unlock()
1462 {
1463     if (lock_file) {
1464         unlink(lock_file);
1465         free(lock_file);
1466         lock_file = NULL;
1467     }
1468 }