]> git.ozlabs.org Git - ppp.git/blob - pppd/sys-str.c
support defaultroute and proxyarp; sundry fixes
[ppp.git] / pppd / sys-str.c
1 /*
2  * sys-str.c - System-dependent procedures for setting up
3  * PPP interfaces on systems which use the STREAMS ppp interface.
4  *
5  * Copyright (c) 1989 Carnegie Mellon University.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms are permitted
9  * provided that the above copyright notice and this paragraph are
10  * duplicated in all such forms and that any documentation,
11  * advertising materials, and other materials related to such
12  * distribution and use acknowledge that the software was developed
13  * by Carnegie Mellon University.  The name of the
14  * University may not be used to endorse or promote products derived
15  * from this software without specific prior written permission.
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19  */
20
21 #ifndef lint
22 static char rcsid[] = "$Id: sys-str.c,v 1.20 1995/05/01 00:26:22 paulus Exp $";
23 #endif
24
25 /*
26  * TODO:
27  */
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <syslog.h>
33 #include <termios.h>
34 #include <fcntl.h>
35 #include <string.h>
36 #include <time.h>
37 #include <utmp.h>
38 #include <poll.h>
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <sys/sockio.h>
42 #include <sys/time.h>
43 #include <sys/stream.h>
44 #include <sys/stropts.h>
45
46 #include <arpa/inet.h>
47 #include <net/if.h>
48 #include <net/ppp_defs.h>
49 #include <net/ppp_str.h>
50 #include <net/route.h>
51 #include <net/if_arp.h>
52 #include <netinet/in.h>
53
54 #include "pppd.h"
55
56 #ifndef ifr_mtu
57 #define ifr_mtu         ifr_metric
58 #endif
59
60 #define MAXMODULES      10      /* max number of module names to save */
61 static struct   modlist {
62     char        modname[FMNAMESZ+1];
63 } str_modules[MAXMODULES];
64 static int      str_module_count = 0;
65 static int      pushed_ppp;
66 static int      closed_stdio;
67
68 static int      restore_term;   /* 1 => we've munged the terminal */
69 static struct termios inittermios; /* Initial TTY termios */
70
71 int sockfd;                     /* socket for doing interface ioctls */
72 static char *lock_file;         /* lock file created for serial port */
73
74 /*
75  * sys_init - System-dependent initialization.
76  */
77 void
78 sys_init()
79 {
80     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
81     setlogmask(LOG_UPTO(LOG_INFO));
82     if (debug)
83         setlogmask(LOG_UPTO(LOG_DEBUG));
84
85     /* Get an internet socket for doing socket ioctl's on. */
86     if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
87         syslog(LOG_ERR, "Couldn't create IP socket: %m");
88         die(1);
89     }
90 }
91
92 /*
93  * note_debug_level - note a change in the debug level.
94  */
95 void
96 note_debug_level()
97 {
98     if (debug) {
99         syslog(LOG_INFO, "Debug turned ON, Level %d", debug);
100         setlogmask(LOG_UPTO(LOG_DEBUG));
101     } else {
102         setlogmask(LOG_UPTO(LOG_WARNING));
103     }
104 }
105
106 /*
107  * daemon - Detach us from the terminal session.
108  */
109 int
110 daemon(nochdir, noclose)
111     int nochdir, noclose;
112 {
113     int pid;
114
115     if ((pid = fork()) < 0)
116         return -1;
117     if (pid != 0)
118         exit(0);                /* parent dies */
119     setsid();
120     if (!nochdir)
121         chdir("/");
122     if (!noclose) {
123         fclose(stdin);          /* don't need stdin, stdout, stderr */
124         fclose(stdout);
125         fclose(stderr);
126     }
127     return 0;
128 }
129
130
131 /*
132  * ppp_available - check if this kernel supports PPP.
133  */
134 int
135 ppp_available()
136 {
137     int fd, ret;
138
139     fd = open("/dev/tty", O_RDONLY, 0);
140     if (fd < 0)
141         return 1;               /* can't find out - assume we have ppp */
142     ret = ioctl(fd, I_FIND, "pppasync") >= 0;
143     close(fd);
144     return ret;
145 }
146
147
148 /*
149  * establish_ppp - Turn the serial port into a ppp interface.
150  */
151 void
152 establish_ppp()
153 {
154     /* go through and save the name of all the modules, then pop em */
155     for (;;) { 
156         if (ioctl(fd, I_LOOK, str_modules[str_module_count].modname) < 0 ||
157             ioctl(fd, I_POP, 0) < 0)
158             break;
159         MAINDEBUG((LOG_DEBUG, "popped stream module : %s",
160                    str_modules[str_module_count].modname));
161         str_module_count++;
162     }
163
164     /* now push the async/fcs module */
165     if (ioctl(fd, I_PUSH, "pppasync") < 0) {
166         syslog(LOG_ERR, "ioctl(I_PUSH, ppp_async): %m");
167         die(1);
168     }
169     /* push the compress module */
170     if (ioctl(fd, I_PUSH, "pppcomp") < 0) {
171         syslog(LOG_WARNING, "ioctl(I_PUSH, ppp_comp): %m");
172     }
173     /* finally, push the ppp_if module that actually handles the */
174     /* network interface */ 
175     if (ioctl(fd, I_PUSH, "pppif") < 0) {
176         syslog(LOG_ERR, "ioctl(I_PUSH, ppp_if): %m");
177         die(1);
178     }
179     pushed_ppp = 1;
180     /* read mode, message non-discard mode */
181     if (ioctl(fd, I_SRDOPT, RMSGN) < 0) {
182         syslog(LOG_ERR, "ioctl(I_SRDOPT, RMSGN): %m");
183         die(1);
184     }
185     /*
186      * Find out which interface we were given.
187      * (ppp_if handles this ioctl)
188      */
189     if (ioctl(fd, SIOCGETU, &ifunit) < 0) {
190         syslog(LOG_ERR, "ioctl(SIOCGETU): %m");
191         die(1);
192     }
193
194     /* Set debug flags in driver */
195     if (ioctl(fd, SIOCSIFDEBUG, &kdebugflag) < 0) {
196         syslog(LOG_ERR, "ioctl(SIOCSIFDEBUG): %m");
197     }
198
199     /* close stdin, stdout, stderr if they might refer to the device */
200     if (default_device && !closed_stdio) {
201         int i;
202
203         for (i = 0; i <= 2; ++i)
204             if (i != fd && i != sockfd)
205                 close(i);
206         closed_stdio = 1;
207     }
208 }
209
210 /*
211  * disestablish_ppp - Restore the serial port to normal operation.
212  * It attempts to reconstruct the stream with the previously popped
213  * modules.  This shouldn't call die() because it's called from die().
214  */
215 void
216 disestablish_ppp()
217 {
218     int flags;
219     char *s;
220
221     if (hungup) {
222         /* we can't push or pop modules after the stream has hung up */
223         str_module_count = 0;
224         restore_term = 0;       /* nor can we fix up terminal settings */
225         return;
226     }
227
228     if (pushed_ppp) {
229         /*
230          * Check whether the link seems not to be 8-bit clean.
231          */
232         if (ioctl(fd, SIOCGIFDEBUG, (caddr_t) &flags) == 0) {
233             s = NULL;
234             switch (~flags & PAI_FLAGS_HIBITS) {
235             case PAI_FLAGS_B7_0:
236                 s = "bit 7 set to 1";
237                 break;
238             case PAI_FLAGS_B7_1:
239                 s = "bit 7 set to 0";
240                 break;
241             case PAI_FLAGS_PAR_EVEN:
242                 s = "odd parity";
243                 break;
244             case PAI_FLAGS_PAR_ODD:
245                 s = "even parity";
246                 break;
247             }
248             if (s != NULL) {
249                 syslog(LOG_WARNING, "Serial link is not 8-bit clean:");
250                 syslog(LOG_WARNING, "All received characters had %s", s);
251             }
252         }
253
254         while (ioctl(fd, I_POP, 0) == 0)        /* pop any we pushed */
255             ;
256   
257         for (; str_module_count > 0; str_module_count--) {
258             if (ioctl(fd, I_PUSH, str_modules[str_module_count-1].modname)) {
259                 if (errno != ENXIO)
260                     syslog(LOG_WARNING, "Couldn't restore module %s: %m",
261                            str_modules[str_module_count-1].modname);
262             } else {
263                 MAINDEBUG((LOG_INFO, "str_restore: pushed module %s",
264                            str_modules[str_module_count-1].modname));
265             }
266         }
267         pushed_ppp = 0;
268     }
269 }
270
271
272 /*
273  * List of valid speeds.
274  */
275 struct speed {
276     int speed_int, speed_val;
277 } speeds[] = {
278 #ifdef B50
279     { 50, B50 },
280 #endif
281 #ifdef B75
282     { 75, B75 },
283 #endif
284 #ifdef B110
285     { 110, B110 },
286 #endif
287 #ifdef B134
288     { 134, B134 },
289 #endif
290 #ifdef B150
291     { 150, B150 },
292 #endif
293 #ifdef B200
294     { 200, B200 },
295 #endif
296 #ifdef B300
297     { 300, B300 },
298 #endif
299 #ifdef B600
300     { 600, B600 },
301 #endif
302 #ifdef B1200
303     { 1200, B1200 },
304 #endif
305 #ifdef B1800
306     { 1800, B1800 },
307 #endif
308 #ifdef B2000
309     { 2000, B2000 },
310 #endif
311 #ifdef B2400
312     { 2400, B2400 },
313 #endif
314 #ifdef B3600
315     { 3600, B3600 },
316 #endif
317 #ifdef B4800
318     { 4800, B4800 },
319 #endif
320 #ifdef B7200
321     { 7200, B7200 },
322 #endif
323 #ifdef B9600
324     { 9600, B9600 },
325 #endif
326 #ifdef B19200
327     { 19200, B19200 },
328 #endif
329 #ifdef B38400
330     { 38400, B38400 },
331 #endif
332 #ifdef EXTA
333     { 19200, EXTA },
334 #endif
335 #ifdef EXTB
336     { 38400, EXTB },
337 #endif
338 #ifdef B57600
339     { 57600, B57600 },
340 #endif
341 #ifdef B115200
342     { 115200, B115200 },
343 #endif
344     { 0, 0 }
345 };
346
347 /*
348  * Translate from bits/second to a speed_t.
349  */
350 int
351 translate_speed(bps)
352     int bps;
353 {
354     struct speed *speedp;
355
356     if (bps == 0)
357         return 0;
358     for (speedp = speeds; speedp->speed_int; speedp++)
359         if (bps == speedp->speed_int)
360             return speedp->speed_val;
361     syslog(LOG_WARNING, "speed %d not supported", bps);
362     return 0;
363 }
364
365 /*
366  * Translate from a speed_t to bits/second.
367  */
368 int
369 baud_rate_of(speed)
370     int speed;
371 {
372     struct speed *speedp;
373
374     if (speed == 0)
375         return 0;
376     for (speedp = speeds; speedp->speed_int; speedp++)
377         if (speed == speedp->speed_val)
378             return speedp->speed_int;
379     return 0;
380 }
381
382 /*
383  * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
384  * at the requested speed, etc.  If `local' is true, set CLOCAL
385  * regardless of whether the modem option was specified.
386  */
387 set_up_tty(fd, local)
388     int fd, local;
389 {
390     int speed;
391     struct termios tios;
392
393     if (tcgetattr(fd, &tios) < 0) {
394         syslog(LOG_ERR, "tcgetattr: %m");
395         die(1);
396     }
397
398     if (!restore_term)
399         inittermios = tios;
400
401     tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
402     if (crtscts > 0)
403         tios.c_cflag |= CRTSCTS;
404     else if (crtscts < 0)
405         tios.c_cflag &= ~CRTSCTS;
406
407     tios.c_cflag |= CS8 | CREAD | HUPCL;
408     if (local || !modem)
409         tios.c_cflag |= CLOCAL;
410     tios.c_iflag = IGNBRK | IGNPAR;
411     tios.c_oflag = 0;
412     tios.c_lflag = 0;
413     tios.c_cc[VMIN] = 1;
414     tios.c_cc[VTIME] = 0;
415
416     if (crtscts == 2) {
417         tios.c_iflag |= IXOFF;
418         tios.c_cc[VSTOP] = 0x13;        /* DC3 = XOFF = ^S */
419         tios.c_cc[VSTART] = 0x11;       /* DC1 = XON  = ^Q */
420     }
421
422     speed = translate_speed(inspeed);
423     if (speed) {
424         cfsetospeed(&tios, speed);
425         cfsetispeed(&tios, speed);
426     } else {
427         speed = cfgetospeed(&tios);
428         /*
429          * We can't proceed if the serial port speed is B0,
430          * since that implies that the serial port is disabled.
431          */
432         if (speed == B0) {
433             syslog(LOG_ERR, "Baud rate for %s is 0; need explicit baud rate",
434                    devnam);
435             die(1);
436         }
437     }
438
439     if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {
440         syslog(LOG_ERR, "tcsetattr: %m");
441         die(1);
442     }
443
444     baud_rate = inspeed = baud_rate_of(speed);
445     restore_term = 1;
446 }
447
448 /*
449  * restore_tty - restore the terminal to the saved settings.
450  */
451 void
452 restore_tty()
453 {
454     if (restore_term) {
455         if (!default_device) {
456             /*
457              * Turn off echoing, because otherwise we can get into
458              * a loop with the tty and the modem echoing to each other.
459              * We presume we are the sole user of this tty device, so
460              * when we close it, it will revert to its defaults anyway.
461              */
462             inittermios.c_lflag &= ~(ECHO | ECHONL);
463         }
464         if (tcsetattr(fd, TCSAFLUSH, &inittermios) < 0)
465             if (errno != ENXIO)
466                 syslog(LOG_WARNING, "tcsetattr: %m");
467         restore_term = 0;
468     }
469 }
470
471 /*
472  * setdtr - control the DTR line on the serial port.
473  * This is called from die(), so it shouldn't call die().
474  */
475 setdtr(fd, on)
476 int fd, on;
477 {
478     int modembits = TIOCM_DTR;
479
480     ioctl(fd, (on? TIOCMBIS: TIOCMBIC), &modembits);
481 }
482
483
484 /*
485  * output - Output PPP packet.
486  */
487 void
488 output(unit, p, len)
489     int unit;
490     u_char *p;
491     int len;
492 {
493     struct strbuf       str;
494
495     if (unit != 0)
496         MAINDEBUG((LOG_WARNING, "output: unit != 0!"));
497     if (debug)
498         log_packet(p, len, "sent ");
499
500     str.len = len;
501     str.buf = (caddr_t) p;
502     if (putmsg(fd, NULL, &str, 0) < 0) {
503         if (errno != ENXIO) {
504             syslog(LOG_ERR, "putmsg: %m");
505             die(1);
506         }
507     }
508 }
509
510 /*
511  * wait_input - wait for input, for a length of time specified in *timo.
512  */
513 wait_input(timo)
514     struct timeval *timo;
515 {
516     int t;
517     struct pollfd pfd;
518
519     t = timo == NULL? -1: timo->tv_sec * 1000 + timo->tv_usec / 1000;
520     pfd.fd = fd;
521     pfd.events = POLLIN | POLLPRI | POLLHUP;
522     if (poll(&pfd, 1, t) < 0 && errno != EINTR) {
523         syslog(LOG_ERR, "poll: %m");
524         die(1);
525     }
526 }
527
528 /*
529  * read_packet - get a PPP packet from the serial device.
530  */
531 int
532 read_packet(buf)
533     u_char *buf;
534 {
535     struct strbuf str, ctl;
536     int len, i;
537     unsigned char ctlbuf[16];
538
539     str.maxlen = PPP_MTU + PPP_HDRLEN;
540     str.buf = (caddr_t) buf;
541     ctl.maxlen = sizeof(ctlbuf);
542     ctl.buf = (caddr_t) ctlbuf;
543     i = 0;
544     len = getmsg(fd, &ctl, &str, &i);
545     if (len < 0) {
546         if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
547             return -1;
548         }
549         syslog(LOG_ERR, "getmsg(fd) %m");
550         die(1);
551     }
552     if (len) 
553         MAINDEBUG((LOG_DEBUG, "getmsg returned 0x%x",len));
554     if (ctl.len > 0)
555         syslog(LOG_NOTICE, "got ctrl msg len %d %x %x\n", ctl.len,
556                ctlbuf[0], ctlbuf[1]);
557
558     if (str.len < 0) {
559         MAINDEBUG((LOG_DEBUG, "getmsg short return length %d", str.len));
560         return -1;
561     }
562
563     return str.len;
564 }
565
566
567 /*
568  * ppp_send_config - configure the transmit characteristics of
569  * the ppp interface.
570  */
571 void
572 ppp_send_config(unit, mtu, asyncmap, pcomp, accomp)
573     int unit, mtu;
574     u_int32_t asyncmap;
575     int pcomp, accomp;
576 {
577     char c;
578     struct ifreq ifr;
579
580     strncpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
581     ifr.ifr_mtu = mtu;
582     if (ioctl(sockfd, SIOCSIFMTU, (caddr_t) &ifr) < 0) {
583         syslog(LOG_ERR, "ioctl(SIOCSIFMTU): %m");
584         quit();
585     }
586
587     if(ioctl(fd, SIOCSIFASYNCMAP, (caddr_t) &asyncmap) < 0) {
588         syslog(LOG_ERR, "ioctl(SIOCSIFASYNCMAP): %m");
589         quit();
590     }
591
592     c = (pcomp? 1: 0);
593     if(ioctl(fd, SIOCSIFCOMPPROT, &c) < 0) {
594         syslog(LOG_ERR, "ioctl(SIOCSIFCOMPPROT): %m");
595         quit();
596     }
597
598     c = (accomp? 1: 0);
599     if(ioctl(fd, SIOCSIFCOMPAC, &c) < 0) {
600         syslog(LOG_ERR, "ioctl(SIOCSIFCOMPAC): %m");
601         quit();
602     }
603 }
604
605
606 /*
607  * ppp_set_xaccm - set the extended transmit ACCM for the interface.
608  */
609 void
610 ppp_set_xaccm(unit, accm)
611     int unit;
612     ext_accm accm;
613 {
614     if (ioctl(fd, SIOCSIFXASYNCMAP, accm) < 0 && errno != ENOTTY)
615         syslog(LOG_WARNING, "ioctl(set extended ACCM): %m");
616 }
617
618
619 /*
620  * ppp_recv_config - configure the receive-side characteristics of
621  * the ppp interface.
622  */
623 void
624 ppp_recv_config(unit, mru, asyncmap, pcomp, accomp)
625     int unit, mru;
626     u_int32_t asyncmap;
627     int pcomp, accomp;
628 {
629     char c;
630
631     if (ioctl(fd, SIOCSIFMRU, &mru) < 0) {
632         syslog(LOG_ERR, "ioctl(SIOCSIFMRU): %m");
633     }
634
635     if (ioctl(fd, SIOCSIFRASYNCMAP, (caddr_t) &asyncmap) < 0) {
636         syslog(LOG_ERR, "ioctl(SIOCSIFRASYNCMAP): %m");
637     }
638
639     c = 2 + (pcomp? 1: 0);
640     if(ioctl(fd, SIOCSIFCOMPPROT, &c) < 0) {
641         syslog(LOG_ERR, "ioctl(SIOCSIFCOMPPROT): %m");
642     }
643
644     c = 2 + (accomp? 1: 0);
645     if (ioctl(fd, SIOCSIFCOMPAC, &c) < 0) {
646         syslog(LOG_ERR, "ioctl(SIOCSIFCOMPAC): %m");
647     }
648 }
649
650 /*
651  * ccp_test - ask kernel whether a given compression method
652  * is acceptable for use.
653  */
654 ccp_test(unit, opt_ptr, opt_len, for_transmit)
655     int unit, opt_len, for_transmit;
656     u_char *opt_ptr;
657 {
658     struct ppp_option_data data;
659
660     if ((unsigned) opt_len > MAX_PPP_OPTION)
661         opt_len = MAX_PPP_OPTION;
662     data.length = opt_len;
663     data.transmit = for_transmit;
664     BCOPY(opt_ptr, data.opt_data, opt_len);
665     return ioctl(fd, SIOCSCOMPRESS, (caddr_t) &data) >= 0;
666 }
667
668 /*
669  * ccp_flags_set - inform kernel about the current state of CCP.
670  */
671 void
672 ccp_flags_set(unit, isopen, isup)
673     int unit, isopen, isup;
674 {
675     int x;
676
677     x = (isopen? 1: 0) + (isup? 2: 0);
678     if (ioctl(fd, SIOCSIFCOMP, (caddr_t) &x) < 0 && errno != ENOTTY)
679         syslog(LOG_ERR, "ioctl (SIOCSIFCOMP): %m");
680 }
681
682 /*
683  * ccp_fatal_error - returns 1 if decompression was disabled as a
684  * result of an error detected after decompression of a packet,
685  * 0 otherwise.  This is necessary because of patent nonsense.
686  */
687 int
688 ccp_fatal_error(unit)
689     int unit;
690 {
691     int x;
692
693     if (ioctl(fd, SIOCGIFCOMP, (caddr_t) &x) < 0) {
694         syslog(LOG_ERR, "ioctl(SIOCGIFCOMP): %m");
695         return 0;
696     }
697     return x & CCP_FATALERROR;
698 }
699
700 /*
701  * sifvjcomp - config tcp header compression
702  */
703 int
704 sifvjcomp(u, vjcomp, cidcomp, maxcid)
705     int u, vjcomp, cidcomp, maxcid;
706 {
707     char x;
708
709     x = (vjcomp? 1: 0) + (cidcomp? 0: 2) + (maxcid << 4);
710     if (ioctl(fd, SIOCSIFVJCOMP, (caddr_t) &x) < 0) {
711         syslog(LOG_ERR, "ioctl(SIOCSIFVJCOMP): %m");
712         return 0;
713     }
714     return 1;
715 }
716
717 /*
718  * sifup - Config the interface up and enable IP packets to pass.
719  */
720 int
721 sifup(u)
722     int u;
723 {
724     struct ifreq ifr;
725     struct npioctl npi;
726
727     strncpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
728     if (ioctl(sockfd, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
729         syslog(LOG_ERR, "ioctl (SIOCGIFFLAGS): %m");
730         return 0;
731     }
732     ifr.ifr_flags |= IFF_UP;
733     if (ioctl(sockfd, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) {
734         syslog(LOG_ERR, "ioctl(SIOCSIFFLAGS): %m");
735         return 0;
736     }
737     npi.protocol = PPP_IP;
738     npi.mode = NPMODE_PASS;
739     if (ioctl(fd, SIOCSETNPMODE, &npi) < 0) {
740         if (errno != ENOTTY) {
741             syslog(LOG_ERR, "ioctl(SIOCSETNPMODE): %m");
742             return 0;
743         }
744     }
745     return 1;
746 }
747
748 /*
749  * sifdown - Config the interface down.
750  */
751 int
752 sifdown(u)
753     int u;
754 {
755     struct ifreq ifr;
756     int rv;
757     struct npioctl npi;
758
759     rv = 1;
760     npi.protocol = PPP_IP;
761     npi.mode = NPMODE_ERROR;
762     if (ioctl(fd, SIOCSETNPMODE, (caddr_t) &npi) < 0) {
763         if (errno != ENOTTY) {
764             syslog(LOG_ERR, "ioctl(SIOCSETNPMODE): %m");
765             rv = 0;
766         }
767     }
768
769     strncpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
770     if (ioctl(sockfd, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
771         syslog(LOG_ERR, "ioctl (SIOCGIFFLAGS): %m");
772         rv = 0;
773     } else {
774         ifr.ifr_flags &= ~IFF_UP;
775         if (ioctl(sockfd, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) {
776             syslog(LOG_ERR, "ioctl(SIOCSIFFLAGS): %m");
777             rv = 0;
778         }
779     }
780     return rv;
781 }
782
783 /*
784  * SET_SA_FAMILY - initialize a struct sockaddr, setting the sa_family field.
785  */
786 #define SET_SA_FAMILY(addr, family)             \
787     BZERO((char *) &(addr), sizeof(addr));      \
788     addr.sa_family = (family);
789
790 /*
791  * sifaddr - Config the interface IP addresses and netmask.
792  */
793 int
794 sifaddr(u, o, h, m)
795     int u;
796     u_int32_t o, h, m;
797 {
798     int ret;
799     struct ifreq ifr;
800
801     ret = 1;
802     strncpy(ifr.ifr_name, ifname, sizeof (ifr.ifr_name));
803     SET_SA_FAMILY(ifr.ifr_addr, AF_INET);
804     ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr.s_addr = o;
805     if (ioctl(sockfd, SIOCSIFADDR, (caddr_t) &ifr) < 0) {
806         syslog(LOG_ERR, "ioctl(SIOCSIFADDR): %m");
807         ret = 0;
808     }
809     ((struct sockaddr_in *) &ifr.ifr_dstaddr)->sin_addr.s_addr = h;
810     if (ioctl(sockfd, SIOCSIFDSTADDR, (caddr_t) &ifr) < 0) {
811         syslog(LOG_ERR, "ioctl(SIOCSIFDSTADDR): %m");
812         ret = 0;
813     }
814     if (m != 0) {
815         ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr.s_addr = m;
816         syslog(LOG_INFO, "Setting interface mask to %s\n", ip_ntoa(m));
817         if (ioctl(sockfd, SIOCSIFNETMASK, (caddr_t) &ifr) < 0) {
818             syslog(LOG_ERR, "ioctl(SIOCSIFNETMASK): %m");
819             ret = 0;
820         }
821     }
822     return ret;
823 }
824
825 /*
826  * cifaddr - Clear the interface IP addresses, and delete routes
827  * through the interface if possible.
828  */
829 int
830 cifaddr(u, o, h)
831     int u;
832     u_int32_t o, h;
833 {
834     struct rtentry rt;
835
836     SET_SA_FAMILY(rt.rt_dst, AF_INET);
837     ((struct sockaddr_in *) &rt.rt_dst)->sin_addr.s_addr = h;
838     SET_SA_FAMILY(rt.rt_gateway, AF_INET);
839     ((struct sockaddr_in *) &rt.rt_gateway)->sin_addr.s_addr = o;
840     rt.rt_flags = RTF_HOST;
841     if (ioctl(sockfd, SIOCDELRT, (caddr_t) &rt) < 0) {
842         syslog(LOG_ERR, "ioctl(SIOCDELRT): %m");
843         return 0;
844     }
845     return 1;
846 }
847
848 /*
849  * sifdefaultroute - assign a default route through the address given.
850  */
851 int
852 sifdefaultroute(u, g)
853     int u;
854     u_int32_t g;
855 {
856     struct rtentry rt;
857
858     SET_SA_FAMILY(rt.rt_dst, AF_INET);
859     SET_SA_FAMILY(rt.rt_gateway, AF_INET);
860     ((struct sockaddr_in *) &rt.rt_gateway)->sin_addr.s_addr = g;
861     rt.rt_flags = RTF_GATEWAY;
862     if (ioctl(sockfd, SIOCADDRT, &rt) < 0) {
863         syslog(LOG_ERR, "default route ioctl(SIOCADDRT): %m");
864         return 0;
865     }
866     return 1;
867 }
868
869 /*
870  * cifdefaultroute - delete a default route through the address given.
871  */
872 int
873 cifdefaultroute(u, g)
874     int u;
875     u_int32_t g;
876 {
877     struct rtentry rt;
878
879     SET_SA_FAMILY(rt.rt_dst, AF_INET);
880     SET_SA_FAMILY(rt.rt_gateway, AF_INET);
881     ((struct sockaddr_in *) &rt.rt_gateway)->sin_addr.s_addr = g;
882     rt.rt_flags = RTF_GATEWAY;
883     if (ioctl(sockfd, SIOCDELRT, &rt) < 0) {
884         syslog(LOG_ERR, "default route ioctl(SIOCDELRT): %m");
885         return 0;
886     }
887     return 1;
888 }
889
890 /*
891  * sifproxyarp - Make a proxy ARP entry for the peer.
892  */
893 int
894 sifproxyarp(unit, hisaddr)
895     int unit;
896     u_int32_t hisaddr;
897 {
898     struct arpreq arpreq;
899
900     BZERO(&arpreq, sizeof(arpreq));
901
902     /*
903      * Get the hardware address of an interface on the same subnet
904      * as our local address.
905      */
906     if (!get_ether_addr(hisaddr, &arpreq.arp_ha)) {
907         syslog(LOG_WARNING, "Cannot determine ethernet address for proxy ARP");
908         return 0;
909     }
910
911     SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
912     ((struct sockaddr_in *) &arpreq.arp_pa)->sin_addr.s_addr = hisaddr;
913     arpreq.arp_flags = ATF_PERM | ATF_PUBL;
914     if (ioctl(sockfd, SIOCSARP, (caddr_t)&arpreq) < 0) {
915         syslog(LOG_ERR, "ioctl(SIOCSARP): %m");
916         return 0;
917     }
918
919     return 1;
920 }
921
922 /*
923  * cifproxyarp - Delete the proxy ARP entry for the peer.
924  */
925 int
926 cifproxyarp(unit, hisaddr)
927     int unit;
928     u_int32_t hisaddr;
929 {
930     struct arpreq arpreq;
931
932     BZERO(&arpreq, sizeof(arpreq));
933     SET_SA_FAMILY(arpreq.arp_pa, AF_INET);
934     ((struct sockaddr_in *) &arpreq.arp_pa)->sin_addr.s_addr = hisaddr;
935     if (ioctl(sockfd, SIOCDARP, (caddr_t)&arpreq) < 0) {
936         syslog(LOG_ERR, "ioctl(SIOCDARP): %m");
937         return 0;
938     }
939     return 1;
940 }
941
942 /*
943  * get_ether_addr - get the hardware address of an interface on the
944  * the same subnet as ipaddr.  Code borrowed from myetheraddr.c
945  * in the cslip-2.6 distribution, which is subject to the following
946  * copyright notice (which also applies to logwtmp below):
947  *
948  * Copyright (c) 1990, 1992 The Regents of the University of California.
949  * All rights reserved.
950  *
951  * Redistribution and use in source and binary forms, with or without
952  * modification, are permitted provided that: (1) source code distributions
953  * retain the above copyright notice and this paragraph in its entirety, (2)
954  * distributions including binary code include the above copyright notice and
955  * this paragraph in its entirety in the documentation or other materials
956  * provided with the distribution, and (3) all advertising materials mentioning
957  * features or use of this software display the following acknowledgement:
958  * ``This product includes software developed by the University of California,
959  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
960  * the University nor the names of its contributors may be used to endorse
961  * or promote products derived from this software without specific prior
962  * written permission.
963  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
964  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
965  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
966  */
967
968 #include <fcntl.h>
969 #include <nlist.h>
970 #include <kvm.h>
971
972 /* XXX SunOS 4.1 defines this and 3.5 doesn't... */
973 #ifdef _nlist_h
974 #define SUNOS4
975 #endif
976
977 #ifdef SUNOS4
978 #include <netinet/in_var.h>
979 #endif
980 #include <netinet/if_ether.h>
981
982 /* Cast a struct sockaddr to a structaddr_in */
983 #define SATOSIN(sa) ((struct sockaddr_in *)(sa))
984
985 /* Determine if "bits" is set in "flag" */
986 #define ALLSET(flag, bits) (((flag) & (bits)) == (bits))
987
988 static struct nlist nl[] = {
989 #define N_IFNET 0
990         { "_ifnet" },
991         { 0 }
992 };
993
994 static void kread();
995
996 int
997 get_ether_addr(ipaddr, hwaddr)
998     u_int32_t ipaddr;
999     struct sockaddr *hwaddr;
1000 {
1001     register kvm_t *kd;
1002     register struct ifnet *ifp;
1003     register struct arpcom *ac;
1004     struct arpcom arpcom;
1005     struct in_addr *inp;
1006 #ifdef SUNOS4
1007     register struct ifaddr *ifa;
1008     register struct in_ifaddr *in;
1009     union {
1010         struct ifaddr ifa;
1011         struct in_ifaddr in;
1012     } ifaddr;
1013 #endif
1014     u_int32_t addr, mask;
1015
1016     /* Open kernel memory for reading */
1017     kd = kvm_open(0, 0, 0, O_RDONLY, NULL);
1018     if (kd == 0) {
1019         syslog(LOG_ERR, "kvm_open: %m");
1020         return 0;
1021     }
1022
1023     /* Fetch namelist */
1024     if (kvm_nlist(kd, nl) != 0) {
1025         syslog(LOG_ERR, "kvm_nlist failed");
1026         return 0;
1027     }
1028
1029     ac = &arpcom;
1030     ifp = &arpcom.ac_if;
1031 #ifdef SUNOS4
1032     ifa = &ifaddr.ifa;
1033     in = &ifaddr.in;
1034 #endif
1035
1036     if (kvm_read(kd, nl[N_IFNET].n_value, (char *)&addr, sizeof(addr))
1037         != sizeof(addr)) {
1038         syslog(LOG_ERR, "error reading ifnet addr");
1039         return 0;
1040     }
1041     for ( ; addr; addr = (u_int32_t)ifp->if_next) {
1042         if (kvm_read(kd, addr, (char *)ac, sizeof(*ac)) != sizeof(*ac)) {
1043             syslog(LOG_ERR, "error reading ifnet");
1044             return 0;
1045         }
1046
1047         /* Only look at configured, broadcast interfaces */
1048         if (!ALLSET(ifp->if_flags, IFF_UP | IFF_BROADCAST))
1049             continue;
1050 #ifdef SUNOS4
1051         /* This probably can't happen... */
1052         if (ifp->if_addrlist == 0)
1053             continue;
1054 #endif
1055
1056         /* Get interface ip address */
1057 #ifdef SUNOS4
1058         if (kvm_read(kd, (u_int32_t)ifp->if_addrlist, (char *)&ifaddr,
1059                      sizeof(ifaddr)) != sizeof(ifaddr)) {
1060             syslog(LOG_ERR, "error reading ifaddr");
1061             return 0;
1062         }
1063         inp = &SATOSIN(&ifa->ifa_addr)->sin_addr;
1064 #else
1065         inp = &SATOSIN(&ifp->if_addr)->sin_addr;
1066 #endif
1067
1068         /* Check if this interface on the right subnet */
1069 #ifdef SUNOS4
1070         mask = in->ia_subnetmask;
1071 #else
1072         mask = ifp->if_subnetmask;
1073 #endif
1074         if ((ipaddr & mask) != (inp->s_addr & mask))
1075             continue;
1076
1077         /* Copy out the local ethernet address */
1078         hwaddr->sa_family = AF_UNSPEC;
1079         BCOPY((caddr_t) &arpcom.ac_enaddr, hwaddr->sa_data,
1080               sizeof(arpcom.ac_enaddr));
1081         return 1;               /* success! */
1082     }
1083
1084     /* couldn't find one */
1085     return 0;
1086 }
1087
1088 #define WTMPFILE        "/usr/adm/wtmp"
1089
1090 int
1091 logwtmp(line, name, host)
1092     char *line, *name, *host;
1093 {
1094     int fd;
1095     struct stat buf;
1096     struct utmp ut;
1097
1098     if ((fd = open(WTMPFILE, O_WRONLY|O_APPEND, 0)) < 0)
1099         return;
1100     if (!fstat(fd, &buf)) {
1101         (void)strncpy(ut.ut_line, line, sizeof(ut.ut_line));
1102         (void)strncpy(ut.ut_name, name, sizeof(ut.ut_name));
1103         (void)strncpy(ut.ut_host, host, sizeof(ut.ut_host));
1104         (void)time(&ut.ut_time);
1105         if (write(fd, (char *)&ut, sizeof(struct utmp)) != sizeof(struct utmp))
1106             (void)ftruncate(fd, buf.st_size);
1107     }
1108     close(fd);
1109 }
1110
1111 /*
1112  * Return user specified netmask, modified by any mask we might determine
1113  * for address `addr' (in network byte order).
1114  * Here we scan through the system's list of interfaces, looking for
1115  * any non-point-to-point interfaces which might appear to be on the same
1116  * network as `addr'.  If we find any, we OR in their netmask to the
1117  * user-specified netmask.
1118  */
1119 #define MAX_IFS         32
1120
1121 u_int32_t
1122 GetMask(addr)
1123     u_int32_t addr;
1124 {
1125     u_int32_t mask, nmask, ina;
1126     struct ifreq *ifr, *ifend, ifreq;
1127     struct ifconf ifc;
1128     struct ifreq ifs[MAX_IFS];
1129
1130     addr = ntohl(addr);
1131     if (IN_CLASSA(addr))        /* determine network mask for address class */
1132         nmask = IN_CLASSA_NET;
1133     else if (IN_CLASSB(addr))
1134         nmask = IN_CLASSB_NET;
1135     else
1136         nmask = IN_CLASSC_NET;
1137     /* class D nets are disallowed by bad_ip_adrs */
1138     mask = netmask | htonl(nmask);
1139
1140     /*
1141      * Scan through the system's network interfaces.
1142      */
1143     ifc.ifc_len = sizeof(ifs);
1144     ifc.ifc_req = ifs;
1145     if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
1146         syslog(LOG_WARNING, "ioctl(SIOCGIFCONF): %m");
1147         return mask;
1148     }
1149     ifend = (struct ifreq *) (ifc.ifc_buf + ifc.ifc_len);
1150     for (ifr = ifc.ifc_req; ifr < ifend; ++ifr) {
1151         /*
1152          * Check the interface's internet address.
1153          */
1154         if (ifr->ifr_addr.sa_family != AF_INET)
1155             continue;
1156         ina = ((struct sockaddr_in *) &ifr->ifr_addr)->sin_addr.s_addr;
1157         if ((ntohl(ina) & nmask) != (addr & nmask))
1158             continue;
1159         /*
1160          * Check that the interface is up, and not point-to-point or loopback.
1161          */
1162         strncpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
1163         if (ioctl(sockfd, SIOCGIFFLAGS, &ifreq) < 0)
1164             continue;
1165         if ((ifreq.ifr_flags & (IFF_UP|IFF_POINTOPOINT|IFF_LOOPBACK))
1166             != IFF_UP)
1167             continue;
1168         /*
1169          * Get its netmask and OR it into our mask.
1170          */
1171         if (ioctl(sockfd, SIOCGIFNETMASK, &ifreq) < 0)
1172             continue;
1173         mask |= ((struct sockaddr_in *)&ifreq.ifr_addr)->sin_addr.s_addr;
1174     }
1175
1176     return mask;
1177 }
1178
1179 /*
1180  * Code for locking/unlocking the serial device.
1181  * This code is derived from chat.c.
1182  */
1183
1184 #if defined(SUNOS) && SUNOS >= 41 && !defined(HDB)
1185 #define HDB     1
1186 #endif
1187
1188 #ifndef LOCK_DIR
1189 # ifdef HDB
1190 #  define       PIDSTRING
1191 #  define       LOCK_PREFIX     "/usr/spool/locks/LCK.."
1192 # else /* HDB */
1193 #  define       LOCK_PREFIX     "/usr/spool/uucp/LCK.."
1194 # endif /* HDB */
1195 #endif /* LOCK_DIR */
1196
1197 /*
1198  * lock - create a lock file for the named device.
1199  */
1200 int
1201 lock(dev)
1202     char *dev;
1203 {
1204     char hdb_lock_buffer[12];
1205     int fd, pid, n;
1206     char *p;
1207
1208     if ((p = strrchr(dev, '/')) != NULL)
1209         dev = p + 1;
1210     lock_file = malloc(strlen(LOCK_PREFIX) + strlen(dev) + 1);
1211     if (lock_file == NULL)
1212         novm("lock file name");
1213     strcat(strcpy(lock_file, LOCK_PREFIX), dev);
1214
1215     while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
1216         if (errno == EEXIST
1217             && (fd = open(lock_file, O_RDONLY, 0)) >= 0) {
1218             /* Read the lock file to find out who has the device locked */
1219 #ifdef PIDSTRING
1220             n = read(fd, hdb_lock_buffer, 11);
1221             if (n > 0) {
1222                 hdb_lock_buffer[n] = 0;
1223                 pid = atoi(hdb_lock_buffer);
1224             }
1225 #else
1226             n = read(fd, &pid, sizeof(pid));
1227 #endif
1228             if (n <= 0) {
1229                 syslog(LOG_ERR, "Can't read pid from lock file %s", lock_file);
1230                 close(fd);
1231             } else {
1232                 if (kill(pid, 0) == -1 && errno == ESRCH) {
1233                     /* pid no longer exists - remove the lock file */
1234                     if (unlink(lock_file) == 0) {
1235                         close(fd);
1236                         syslog(LOG_NOTICE, "Removed stale lock on %s (pid %d)",
1237                                dev, pid);
1238                         continue;
1239                     } else
1240                         syslog(LOG_WARNING, "Couldn't remove stale lock on %s",
1241                                dev);
1242                 } else
1243                     syslog(LOG_NOTICE, "Device %s is locked by pid %d",
1244                            dev, pid);
1245             }
1246             close(fd);
1247         } else
1248             syslog(LOG_ERR, "Can't create lock file %s: %m", lock_file);
1249         free(lock_file);
1250         lock_file = NULL;
1251         return -1;
1252     }
1253
1254 #ifdef PIDSTRING
1255     sprintf(hdb_lock_buffer, "%10d\n", getpid());
1256     write(fd, hdb_lock_buffer, 11);
1257 #else
1258     pid = getpid();
1259     write(fd, &pid, sizeof pid);
1260 #endif
1261
1262     close(fd);
1263     return 0;
1264 }
1265
1266 /*
1267  * unlock - remove our lockfile
1268  */
1269 void
1270 unlock()
1271 {
1272     if (lock_file) {
1273         unlink(lock_file);
1274         free(lock_file);
1275         lock_file = NULL;
1276     }
1277 }