2 * Copyright (c) 1983, 1988, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * $FreeBSD: src/sbin/routed/main.c,v 1.11.2.1 2000/08/14 17:00:03 sheldonh Exp $
33 #include "pathnames.h"
38 #if !defined(__NetBSD__)
40 "@(#) Copyright (c) 1983, 1988, 1993\n\
41 The Regents of the University of California. All rights reserved.\n";
42 static char sccsid
[] __attribute__((unused
)) = "@(#)main.c 8.1 (Berkeley) 6/5/93";
43 #elif defined(__NetBSD__)
45 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993\n\
46 The Regents of the University of California. All rights reserved.\n");
52 naddr myaddr
; /* system address */
53 char myname
[MAXHOSTNAMELEN
+1];
57 int supplier
; /* supply or broadcast updates */
59 int ipforwarding
= 1; /* kernel forwarding on */
61 int default_gateway
; /* 1=advertise default */
63 int ridhosts
; /* 1=reduce host routes */
64 int mhome
; /* 1=want multi-homed host route */
65 int advertise_mhome
; /* 1=must continue advertising it */
66 int auth_ok
= 1; /* 1=ignore auth if we do not care */
68 struct timeval epoch
; /* when started */
69 struct timeval clk
, prev_clk
;
70 static int usec_fudge
;
71 struct timeval now
; /* current idea of time */
76 struct timeval next_bcast
; /* next general broadcast */
77 struct timeval no_flash
= { /* inhibit flash update */
78 EPOCH
+SUPPLY_INTERVAL
, 0
81 struct timeval flush_kern_timer
;
85 int rip_sock
= -1; /* RIP socket */
86 struct interface
*rip_sock_mcast
; /* current multicast interface */
87 int rt_sock
; /* routing socket */
91 static int get_rip_sock(naddr
, int);
92 static void timevalsub(struct timeval
*, struct timeval
*, struct timeval
*);
102 struct timeval wtime
, t2
;
106 struct interface
*ifp
;
111 /* Some shells are badly broken and send SIGHUP to backgrounded
114 signal(SIGHUP
, SIG_IGN
);
116 openlog("routed", LOG_PID
| LOG_ODELAY
, LOG_DAEMON
);
119 gettimeofday(&clk
, 0);
122 epoch
.tv_sec
-= EPOCH
;
124 now_stale
= EPOCH
- STALE_TIME
;
125 now_expire
= EPOCH
- EXPIRE_TIME
;
126 now_garbage
= EPOCH
- GARBAGE_TIME
;
129 gethostname(myname
, sizeof(myname
)-1);
130 gethost(myname
, &myaddr
);
132 while ((n
= getopt(argc
, argv
, "sqdghmpAtvT:F:P:")) != -1) {
149 memset(&parm
, 0, sizeof(parm
));
150 parm
.parm_d_metric
= 1;
151 cp
= check_parms(&parm
);
153 msglog("bad -g: %s", cp
);
158 case 'h': /* suppress extra host routes */
162 case 'm': /* advertise host route */
163 mhome
= 1; /* on multi-homed hosts */
167 /* Ignore authentication if we do not care.
168 * Crazy as it is, that is what RFC 1723 requires.
181 case 'F': /* minimal routes for SLIP */
183 p
= strchr(optarg
,',');
184 if (p
&& *p
!= '\0') {
185 n
= (int)strtoul(p
+1, &q
, 0);
187 && n
<= HOPCNT_INFINITY
-1
191 if (!getnet(optarg
, &p_net
, &p_mask
)) {
192 msglog("bad network; \"-F %s\"",
196 memset(&parm
, 0, sizeof(parm
));
197 parm
.parm_net
= p_net
;
198 parm
.parm_mask
= p_mask
;
199 parm
.parm_d_metric
= n
;
200 cp
= check_parms(&parm
);
202 msglog("bad -F: %s", cp
);
206 /* handle arbitrary parameters.
209 cp
= parse_parms(q
, 0);
211 msglog("%s in \"-P %s\"", cp
, optarg
);
216 /* display version */
218 msglog("version 2.22");
228 if (tracename
== 0 && argc
>= 1) {
232 if (tracename
!= 0 && tracename
[0] == '\0')
236 logbad(0, "usage: routed [-sqdghmpAtv] [-T tracefile]"
237 " [-F net[,metric]] [-P parms]");
239 if (geteuid() != 0) {
242 logbad(0, "requires UID 0");
248 mib
[3] = IPCTL_FORWARDING
;
249 len
= sizeof(ipforwarding
);
250 if (sysctl(mib
, 4, &ipforwarding
, &len
, 0, 0) < 0)
251 LOGERR("sysctl(IPCTL_FORWARDING)");
255 msglog("-s incompatible with ipforwarding=0");
256 if (default_gateway
) {
257 msglog("-g incompatible with ipforwarding=0");
263 if (default_gateway
) {
264 if (supplier_set
&& !supplier
) {
265 msglog("-g and -q incompatible");
273 signal(SIGALRM
, sigalrm
);
275 signal(SIGHUP
, sigterm
); /* SIGHUP fatal during debugging */
276 signal(SIGTERM
, sigterm
);
277 signal(SIGINT
, sigterm
);
278 signal(SIGUSR1
, sigtrace_on
);
279 signal(SIGUSR2
, sigtrace_off
);
281 /* get into the background */
282 if (background
&& daemon(0, 1) < 0)
283 BADERR(0,"daemon()");
286 srandom((int)(clk
.tv_sec
^ clk
.tv_usec
^ mypid
));
288 /* prepare socket connected to the kernel.
290 rt_sock
= socket(AF_ROUTE
, SOCK_RAW
, 0);
292 BADERR(1,"rt_sock = socket()");
293 if (fcntl(rt_sock
, F_SETFL
, O_NONBLOCK
) == -1)
294 logbad(1, "fcntl(rt_sock) O_NONBLOCK: %s", strerror(errno
));
296 if (setsockopt(rt_sock
, SOL_SOCKET
,SO_USELOOPBACK
,
297 &off
,sizeof(off
)) < 0)
298 LOGERR("setsockopt(SO_USELOOPBACK,0)");
303 if (tracename
!= 0) {
304 strncpy(inittracename
, tracename
, sizeof(inittracename
)-1);
305 set_tracefile(inittracename
, "%s", -1);
307 tracelevel_msg("%s", -1); /* turn on tracing to stdio */
312 /* initialize radix tree */
315 /* Pick a random part of the second for our output to minimize
318 * Start broadcasting after hearing from other routers, and
319 * at a random time so a bunch of systems do not get synchronized
320 * after a power failure.
322 intvl_random(&next_bcast
, EPOCH
+MIN_WAITTIME
, EPOCH
+SUPPLY_INTERVAL
);
323 age_timer
.tv_usec
= next_bcast
.tv_usec
;
324 age_timer
.tv_sec
= EPOCH
+MIN_WAITTIME
;
325 rdisc_timer
= next_bcast
;
326 ifinit_timer
.tv_usec
= next_bcast
.tv_usec
;
328 /* Collect an initial view of the world by checking the interface
329 * configuration and the kludge file.
338 /* Now turn off stdio if not tracing */
339 if (new_tracelevel
== 0)
340 trace_close(background
);
342 /* Loop forever, listening and broadcasting.
346 gettimeofday(&clk
, 0);
347 if (prev_clk
.tv_sec
== clk
.tv_sec
348 && prev_clk
.tv_usec
== clk
.tv_usec
+usec_fudge
) {
349 /* Much of `routed` depends on time always advancing.
350 * On systems that do not guarantee that gettimeofday()
351 * produces unique timestamps even if called within
352 * a single tick, use trickery like that in classic
355 clk
.tv_usec
+= ++usec_fudge
;
360 timevalsub(&t2
, &clk
, &prev_clk
);
362 || t2
.tv_sec
> wtime
.tv_sec
+ 5) {
363 /* Deal with time changes before other
364 * housekeeping to keep everything straight.
369 trace_act("time changed by %d sec", (int)dt
);
373 timevalsub(&now
, &clk
, &epoch
);
374 now_stale
= now
.tv_sec
- STALE_TIME
;
375 now_expire
= now
.tv_sec
- EXPIRE_TIME
;
376 now_garbage
= now
.tv_sec
- GARBAGE_TIME
;
378 /* deal with signals that should affect tracing */
384 trace_off("exiting with signal %d", stopint
);
388 /* look for new or dead interfaces */
389 timevalsub(&wtime
, &ifinit_timer
, &now
);
390 if (wtime
.tv_sec
<= 0) {
397 /* Check the kernel table occassionally for mysteriously
400 timevalsub(&t2
, &flush_kern_timer
, &now
);
401 if (t2
.tv_sec
<= 0) {
403 flush_kern_timer
.tv_sec
= (now
.tv_sec
404 + CHECK_QUIET_INTERVAL
);
407 if (timercmp(&t2
, &wtime
, <))
410 /* If it is time, then broadcast our routes.
412 if (supplier
|| advertise_mhome
) {
413 timevalsub(&t2
, &next_bcast
, &now
);
414 if (t2
.tv_sec
<= 0) {
415 /* Synchronize the aging and broadcast
416 * timers to minimize awakenings
422 /* It is desirable to send routing updates
423 * regularly. So schedule the next update
424 * 30 seconds after the previous one was
425 * scheduled, instead of 30 seconds after
426 * the previous update was finished.
427 * Even if we just started after discovering
428 * a 2nd interface or were otherwise delayed,
429 * pick a 30-second aniversary of the
430 * original broadcast time.
432 n
= 1 + (0-t2
.tv_sec
)/SUPPLY_INTERVAL
;
433 next_bcast
.tv_sec
+= n
*SUPPLY_INTERVAL
;
438 if (timercmp(&t2
, &wtime
, <))
442 /* If we need a flash update, either do it now or
443 * set the delay to end when it is time.
445 * If we are within MIN_WAITTIME seconds of a full update,
450 && no_flash
.tv_sec
+MIN_WAITTIME
< next_bcast
.tv_sec
) {
451 /* accurate to the millisecond */
452 if (!timercmp(&no_flash
, &now
, >))
454 timevalsub(&t2
, &no_flash
, &now
);
455 if (timercmp(&t2
, &wtime
, <))
459 /* trigger the main aging timer.
461 timevalsub(&t2
, &age_timer
, &now
);
462 if (t2
.tv_sec
<= 0) {
466 if (timercmp(&t2
, &wtime
, <))
469 /* update the kernel routing table
471 timevalsub(&t2
, &need_kern
, &now
);
472 if (t2
.tv_sec
<= 0) {
476 if (timercmp(&t2
, &wtime
, <))
479 /* take care of router discovery,
480 * but do it in the correct the millisecond
482 if (!timercmp(&rdisc_timer
, &now
, >)) {
486 timevalsub(&t2
, &rdisc_timer
, &now
);
487 if (timercmp(&t2
, &wtime
, <))
491 /* wait for input or a timer to expire.
495 n
= select(sock_max
, &ibits
, 0, 0, &wtime
);
497 if (n
< 0 && errno
!= EINTR
&& errno
!= EAGAIN
)
502 if (FD_ISSET(rt_sock
, &ibits
)) {
506 if (rdisc_sock
>= 0 && FD_ISSET(rdisc_sock
, &ibits
)) {
510 if (rip_sock
>= 0 && FD_ISSET(rip_sock
, &ibits
)) {
511 read_rip(rip_sock
, 0);
515 for (ifp
= ifnet
; n
> 0 && 0 != ifp
; ifp
= ifp
->int_next
) {
516 if (ifp
->int_rip_sock
>= 0
517 && FD_ISSET(ifp
->int_rip_sock
, &ibits
)) {
518 read_rip(ifp
->int_rip_sock
, ifp
);
528 sigalrm(int s UNUSED
)
530 /* Historically, SIGALRM would cause the daemon to check for
531 * new and broken interfaces.
533 ifinit_timer
.tv_sec
= now
.tv_sec
;
534 trace_act("SIGALRM");
538 /* watch for fatal signals */
543 signal(sig
, SIG_DFL
); /* catch it only once */
550 struct interface
*ifp
;
556 FD_SET(rt_sock
, &fdbits
);
557 if (sock_max
<= rt_sock
)
558 sock_max
= rt_sock
+1;
560 FD_SET(rip_sock
, &fdbits
);
561 if (sock_max
<= rip_sock
)
562 sock_max
= rip_sock
+1;
564 for (ifp
= ifnet
; NULL
!= ifp
; ifp
= ifp
->int_next
) {
565 if (ifp
->int_rip_sock
>= 0) {
566 FD_SET(ifp
->int_rip_sock
, &fdbits
);
567 if (sock_max
<= ifp
->int_rip_sock
)
568 sock_max
= ifp
->int_rip_sock
+1;
571 if (rdisc_sock
>= 0) {
572 FD_SET(rdisc_sock
, &fdbits
);
573 if (sock_max
<= rdisc_sock
)
574 sock_max
= rdisc_sock
+1;
584 #define MIN_SOCKBUF (4*1024)
587 if (fcntl(sock
, F_SETFL
, O_NONBLOCK
) == -1)
588 logbad(1, "fcntl(%s) O_NONBLOCK: %s",
589 name
, strerror(errno
));
591 if (setsockopt(sock
, SOL_SOCKET
,SO_BROADCAST
, &on
,sizeof(on
)) < 0)
592 msglog("setsockopt(%s,SO_BROADCAST): %s",
593 name
, strerror(errno
));
594 #ifdef USE_PASSIFNAME
596 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSIFNAME
, &on
,sizeof(on
)) < 0)
597 msglog("setsockopt(%s,SO_PASSIFNAME): %s",
598 name
, strerror(errno
));
601 if (rbuf
>= MIN_SOCKBUF
) {
602 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
,
603 &rbuf
, sizeof(rbuf
)) < 0)
604 msglog("setsockopt(%s,SO_RCVBUF=%d): %s",
605 name
, rbuf
, strerror(errno
));
607 for (rbuf
= 60*1024; ; rbuf
-= 4096) {
608 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVBUF
,
609 &rbuf
, sizeof(rbuf
)) == 0) {
610 trace_act("RCVBUF=%d", rbuf
);
613 if (rbuf
< MIN_SOCKBUF
) {
614 msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
615 name
, rbuf
, strerror(errno
));
625 static int /* <0 or file descriptor */
626 get_rip_sock(naddr addr
,
627 int serious
) /* 1=failure to bind is serious */
629 struct sockaddr_in in
;
634 if ((s
= socket(AF_INET
, SOCK_DGRAM
, 0)) < 0)
635 BADERR(1,"rip_sock = socket()");
637 memset(&in
, 0, sizeof(in
));
639 in
.sin_len
= sizeof(in
);
641 in
.sin_family
= AF_INET
;
642 in
.sin_port
= htons(RIP_PORT
);
643 in
.sin_addr
.s_addr
= addr
;
644 if (bind(s
, (struct sockaddr
*)&in
, sizeof(in
)) < 0) {
646 BADERR(errno
!= EADDRINUSE
, "bind(rip_sock)");
649 fix_sock(s
,"rip_sock");
652 if (setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_TTL
,
653 &ttl
, sizeof(ttl
)) < 0)
654 DBGERR(1,"rip_sock setsockopt(IP_MULTICAST_TTL)");
660 /* turn off main RIP socket */
664 struct interface
*ifp
;
668 if (rip_sock
>= 0 && !mhome
) {
669 trace_act("turn off RIP");
674 /* get non-broadcast sockets to listen to queries.
676 for (ifp
= ifnet
; ifp
!= NULL
; ifp
= ifp
->int_next
) {
677 if (ifp
->int_state
& IS_REMOTE
)
679 if (ifp
->int_rip_sock
< 0) {
680 addr
= ((ifp
->int_if_flags
& IFF_POINTOPOINT
)
683 ifp
->int_rip_sock
= get_rip_sock(addr
, 0);
694 /* turn on RIP multicast input via an interface
697 rip_mcast_on(struct interface
*ifp
)
701 if (!IS_RIP_IN_OFF(ifp
->int_state
)
702 && (ifp
->int_if_flags
& IFF_MULTICAST
)
704 && !(ifp
->int_if_flags
& IFF_POINTOPOINT
)
706 && !(ifp
->int_state
& IS_ALIAS
)) {
707 m
.imr_multiaddr
.s_addr
= htonl(INADDR_RIP_GROUP
);
708 m
.imr_interface
.s_addr
= ((ifp
->int_if_flags
& IFF_POINTOPOINT
)
711 if (setsockopt(rip_sock
,IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
713 LOGERR("setsockopt(IP_ADD_MEMBERSHIP RIP)");
718 /* Prepare socket used for RIP.
721 rip_on(struct interface
*ifp
)
723 /* If the main RIP socket is already alive, only start receiving
724 * multicasts for this interface.
732 /* If the main RIP socket is off and it makes sense to turn it on,
733 * then turn it on for all of the interfaces.
734 * It makes sense if either router discovery is off, or if
735 * router discover is on and at most one interface is doing RIP.
737 if (rip_interfaces
> 0 && (!rdisc_ok
|| rip_interfaces
> 1)) {
738 trace_act("turn on RIP");
740 /* Close all of the query sockets so that we can open
741 * the main socket. SO_REUSEPORT is not a solution,
742 * since that would let two daemons bind to the broadcast
745 for (ifp
= ifnet
; ifp
!= NULL
; ifp
= ifp
->int_next
) {
746 if (ifp
->int_rip_sock
>= 0) {
747 close(ifp
->int_rip_sock
);
748 ifp
->int_rip_sock
= -1;
752 rip_sock
= get_rip_sock(INADDR_ANY
, 1);
753 rip_sock_mcast
= NULL
;
755 /* Do not advertise anything until we have heard something
757 if (next_bcast
.tv_sec
< now
.tv_sec
+MIN_WAITTIME
)
758 next_bcast
.tv_sec
= now
.tv_sec
+MIN_WAITTIME
;
760 for (ifp
= ifnet
; ifp
!= NULL
; ifp
= ifp
->int_next
) {
761 ifp
->int_query_time
= NEVER
;
764 ifinit_timer
.tv_sec
= now
.tv_sec
;
766 } else if (ifp
!= NULL
767 && !(ifp
->int_state
& IS_REMOTE
)
768 && ifp
->int_rip_sock
< 0) {
769 /* RIP is off, so ensure there are sockets on which
770 * to listen for queries.
772 ifp
->int_rip_sock
= get_rip_sock(ifp
->int_addr
, 0);
779 /* die if malloc(3) fails
782 rtmalloc(size_t size
,
785 void *p
= malloc(size
);
787 logbad(1,"malloc(%lu) failed in %s", (u_long
)size
, msg
);
792 /* get a random instant in an interval
795 intvl_random(struct timeval
*tp
, /* put value here */
796 u_long lo
, /* value is after this second */
797 u_long hi
) /* and before this */
799 tp
->tv_sec
= (time_t)(hi
== lo
801 : (lo
+ random() % ((hi
- lo
))));
802 tp
->tv_usec
= random() % 1000000;
807 timevaladd(struct timeval
*t1
,
811 t1
->tv_sec
+= t2
->tv_sec
;
812 if ((t1
->tv_usec
+= t2
->tv_usec
) >= 1000000) {
814 t1
->tv_usec
-= 1000000;
822 timevalsub(struct timeval
*t1
,
826 t1
->tv_sec
= t2
->tv_sec
- t3
->tv_sec
;
827 if ((t1
->tv_usec
= t2
->tv_usec
- t3
->tv_usec
) < 0) {
829 t1
->tv_usec
+= 1000000;
834 /* put a message into the system log
837 msglog(const char *p
, ...)
844 vsyslog(LOG_ERR
, p
, args
);
847 if (ftrace
== stdout
)
848 fputs("routed: ", ftrace
);
849 vfprintf(ftrace
, p
, args
);
855 /* Put a message about a bad system into the system log if
856 * we have not complained about it recently.
858 * It is desirable to complain about all bad systems, but not too often.
859 * In the worst case, it is not practical to keep track of all bad systems.
860 * For example, there can be many systems with the wrong password.
863 msglim(struct msg_limit
*lim
, naddr addr
, const char *p
, ...)
867 struct msg_sub
*ms1
, *ms
;
872 /* look for the oldest slot in the table
873 * or the slot for the bad router.
875 ms
= ms1
= lim
->subs
;
876 for (i
= MSG_SUBJECT_N
; ; i
--, ms1
++) {
878 /* Reuse a slot at most once every 10 minutes.
880 if (lim
->reuse
> now
.tv_sec
) {
884 lim
->reuse
= now
.tv_sec
+ 10*60;
888 if (ms
->addr
== addr
) {
889 /* Repeat a complaint about a given system at
892 if (ms
->until
> now
.tv_sec
)
896 if (ms
->until
< ms1
->until
)
901 ms
->until
= now
.tv_sec
+ 60*60; /* 60 minutes */
904 for (p1
= p
; *p1
== ' '; p1
++)
906 vsyslog(LOG_ERR
, p1
, args
);
909 /* always display the message if tracing */
911 vfprintf(ftrace
, p
, args
);
918 logbad(int dump
, const char *p
, ...)
925 vsyslog(LOG_ERR
, p
, args
);
927 fputs("routed: ", stderr
);
928 vfprintf(stderr
, p
, args
);
929 fputs("; giving up\n",stderr
);