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