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