2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1983, 1988, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include "pathnames.h"
43 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993 "
44 "The Regents of the University of California."
45 " All rights reserved.");
49 #elif defined(__FreeBSD__)
52 __RCSID("$Revision: 2.31 $");
53 #ident "$Revision: 2.31 $"
58 naddr myaddr; /* system address */
59 static char myname[MAXHOSTNAMELEN+1];
63 int supplier; /* supply or broadcast updates */
65 static int ipforwarding = 1; /* kernel forwarding on */
67 static int default_gateway; /* 1=advertise default */
68 static int background = 1;
69 int ridhosts; /* 1=reduce host routes */
70 int mhome; /* 1=want multi-homed host route */
71 int advertise_mhome; /* 1=must continue advertising it */
72 int auth_ok = 1; /* 1=ignore auth if we do not care */
73 int insecure; /* Reply to special queries or not */
75 struct timeval epoch; /* when started */
77 static struct timeval prev_clk;
78 static int usec_fudge;
79 struct timeval now; /* current idea of time */
84 static struct timeval next_bcast; /* next general broadcast */
85 struct timeval no_flash = { /* inhibit flash update */
86 EPOCH+SUPPLY_INTERVAL, 0
89 static struct timeval flush_kern_timer;
93 int rip_sock = -1; /* RIP socket */
94 const struct interface *rip_sock_mcast; /* current multicast interface */
95 int rt_sock; /* routing socket */
99 static int get_rip_sock(naddr, int);
100 static void timevalsub(struct timeval *, struct timeval *, struct timeval *);
101 static void sigalrm(int s UNUSED);
102 static void sigterm(int sig);
112 struct timeval wtime, t2;
116 struct interface *ifp;
121 /* Some shells are badly broken and send SIGHUP to backgrounded
124 signal(SIGHUP, SIG_IGN);
126 openlog("routed", LOG_PID, LOG_DAEMON);
129 gettimeofday(&clk, 0);
132 epoch.tv_sec -= EPOCH;
134 now_stale = EPOCH - STALE_TIME;
135 now_expire = EPOCH - EXPIRE_TIME;
136 now_garbage = EPOCH - GARBAGE_TIME;
139 (void)gethostname(myname, sizeof(myname)-1);
140 (void)gethost(myname, &myaddr);
142 while ((n = getopt(argc, argv, "isqdghmAtvT:F:P:")) != -1) {
162 memset(&parm, 0, sizeof(parm));
163 parm.parm_d_metric = 1;
164 cp = check_parms(&parm);
166 msglog("bad -g: %s", cp);
171 case 'h': /* suppress extra host routes */
175 case 'm': /* advertise host route */
176 mhome = 1; /* on multi-homed hosts */
180 /* Ignore authentication if we do not care.
181 * Crazy as it is, that is what RFC 1723 requires.
194 case 'F': /* minimal routes for SLIP */
196 p = strchr(optarg,',');
197 if (p && *p != '\0') {
198 n = (int)strtoul(p+1, &q, 0);
200 && n <= HOPCNT_INFINITY-1
204 if (!getnet(optarg, &p_net, &p_mask)) {
205 msglog("bad network; \"-F %s\"",
209 memset(&parm, 0, sizeof(parm));
210 parm.parm_net = p_net;
211 parm.parm_mask = p_mask;
212 parm.parm_d_metric = n;
213 cp = check_parms(&parm);
215 msglog("bad -F: %s", cp);
219 /* handle arbitrary parameters.
222 cp = parse_parms(q, 0);
224 msglog("%s in \"-P %s\"", cp, optarg);
229 /* display version */
231 msglog("version 2.31");
241 if (tracename == 0 && argc >= 1) {
245 if (tracename != 0 && tracename[0] == '\0')
249 logbad(0, "usage: routed [-sqdghmAtv] [-T tracefile]"
250 " [-F net[,metric]] [-P parms]");
252 if (geteuid() != 0) {
255 logbad(0, "requires UID 0");
261 mib[3] = IPCTL_FORWARDING;
262 len = sizeof(ipforwarding);
263 if (sysctl(mib, 4, &ipforwarding, &len, 0, 0) < 0)
264 LOGERR("sysctl(IPCTL_FORWARDING)");
268 msglog("-s incompatible with ipforwarding=0");
269 if (default_gateway) {
270 msglog("-g incompatible with ipforwarding=0");
276 if (default_gateway) {
277 if (supplier_set && !supplier) {
278 msglog("-g and -q incompatible");
286 signal(SIGALRM, sigalrm);
288 signal(SIGHUP, sigterm); /* SIGHUP fatal during debugging */
289 signal(SIGTERM, sigterm);
290 signal(SIGINT, sigterm);
291 signal(SIGUSR1, sigtrace_on);
292 signal(SIGUSR2, sigtrace_off);
294 /* get into the background */
296 if (0 > _daemonize(background ? 0 : (_DF_NOCHDIR|_DF_NOFORK),
297 STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO))
298 BADERR(0, "_daemonize()");
300 if (background && daemon(0, 1) < 0)
301 BADERR(0,"daemon()");
304 #if defined(__NetBSD__)
309 /* prepare socket connected to the kernel.
311 rt_sock = socket(AF_ROUTE, SOCK_RAW, 0);
313 BADERR(1,"rt_sock = socket()");
314 if (fcntl(rt_sock, F_SETFL, O_NONBLOCK) == -1)
315 logbad(1, "fcntl(rt_sock) O_NONBLOCK: %s", strerror(errno));
317 if (setsockopt(rt_sock, SOL_SOCKET,SO_USELOOPBACK,
318 &off,sizeof(off)) < 0)
319 LOGERR("setsockopt(SO_USELOOPBACK,0)");
324 if (tracename != 0) {
325 strncpy(inittracename, tracename, sizeof(inittracename)-1);
326 set_tracefile(inittracename, "%s", -1);
328 tracelevel_msg("%s", -1); /* turn on tracing to stdio */
333 /* initialize radix tree */
336 /* Pick a random part of the second for our output to minimize
339 * Start broadcasting after hearing from other routers, and
340 * at a random time so a bunch of systems do not get synchronized
341 * after a power failure.
343 intvl_random(&next_bcast, EPOCH+MIN_WAITTIME, EPOCH+SUPPLY_INTERVAL);
344 age_timer.tv_usec = next_bcast.tv_usec;
345 age_timer.tv_sec = EPOCH+MIN_WAITTIME;
346 rdisc_timer = next_bcast;
347 ifinit_timer.tv_usec = next_bcast.tv_usec;
349 /* Collect an initial view of the world by checking the interface
350 * configuration and the kludge file.
359 /* Now turn off stdio if not tracing */
360 if (new_tracelevel == 0)
361 trace_close(background);
363 /* Loop forever, listening and broadcasting.
367 gettimeofday(&clk, 0);
368 if (prev_clk.tv_sec == clk.tv_sec
369 && prev_clk.tv_usec == clk.tv_usec+usec_fudge) {
370 /* Much of `routed` depends on time always advancing.
371 * On systems that do not guarantee that gettimeofday()
372 * produces unique timestamps even if called within
373 * a single tick, use trickery like that in classic
376 clk.tv_usec += ++usec_fudge;
381 timevalsub(&t2, &clk, &prev_clk);
383 || t2.tv_sec > wtime.tv_sec + 5) {
384 /* Deal with time changes before other
385 * housekeeping to keep everything straight.
390 trace_act("time changed by %d sec", (int)dt);
394 timevalsub(&now, &clk, &epoch);
395 now_stale = now.tv_sec - STALE_TIME;
396 now_expire = now.tv_sec - EXPIRE_TIME;
397 now_garbage = now.tv_sec - GARBAGE_TIME;
399 /* deal with signals that should affect tracing */
405 trace_off("exiting with signal %d", stopint);
409 /* look for new or dead interfaces */
410 timevalsub(&wtime, &ifinit_timer, &now);
411 if (wtime.tv_sec <= 0) {
418 /* Check the kernel table occasionally for mysteriously
421 timevalsub(&t2, &flush_kern_timer, &now);
422 if (t2.tv_sec <= 0) {
424 flush_kern_timer.tv_sec = (now.tv_sec
425 + CHECK_QUIET_INTERVAL);
428 if (timercmp(&t2, &wtime, <))
431 /* If it is time, then broadcast our routes.
433 if (supplier || advertise_mhome) {
434 timevalsub(&t2, &next_bcast, &now);
435 if (t2.tv_sec <= 0) {
436 /* Synchronize the aging and broadcast
437 * timers to minimize awakenings
443 /* It is desirable to send routing updates
444 * regularly. So schedule the next update
445 * 30 seconds after the previous one was
446 * scheduled, instead of 30 seconds after
447 * the previous update was finished.
448 * Even if we just started after discovering
449 * a 2nd interface or were otherwise delayed,
450 * pick a 30-second anniversary of the
451 * original broadcast time.
453 n = 1 + (0-t2.tv_sec)/SUPPLY_INTERVAL;
454 next_bcast.tv_sec += n*SUPPLY_INTERVAL;
459 if (timercmp(&t2, &wtime, <))
463 /* If we need a flash update, either do it now or
464 * set the delay to end when it is time.
466 * If we are within MIN_WAITTIME seconds of a full update,
471 && no_flash.tv_sec+MIN_WAITTIME < next_bcast.tv_sec) {
472 /* accurate to the millisecond */
473 if (!timercmp(&no_flash, &now, >))
475 timevalsub(&t2, &no_flash, &now);
476 if (timercmp(&t2, &wtime, <))
480 /* trigger the main aging timer.
482 timevalsub(&t2, &age_timer, &now);
483 if (t2.tv_sec <= 0) {
487 if (timercmp(&t2, &wtime, <))
490 /* update the kernel routing table
492 timevalsub(&t2, &need_kern, &now);
493 if (t2.tv_sec <= 0) {
497 if (timercmp(&t2, &wtime, <))
500 /* take care of router discovery,
501 * but do it in the correct the millisecond
503 if (!timercmp(&rdisc_timer, &now, >)) {
507 timevalsub(&t2, &rdisc_timer, &now);
508 if (timercmp(&t2, &wtime, <))
512 /* wait for input or a timer to expire.
516 n = select(sock_max, &ibits, 0, 0, &wtime);
518 if (n < 0 && errno != EINTR && errno != EAGAIN)
523 if (FD_ISSET(rt_sock, &ibits)) {
527 if (rdisc_sock >= 0 && FD_ISSET(rdisc_sock, &ibits)) {
531 if (rip_sock >= 0 && FD_ISSET(rip_sock, &ibits)) {
532 read_rip(rip_sock, 0);
536 LIST_FOREACH(ifp, &ifnet, int_list) {
539 if (ifp->int_rip_sock >= 0
540 && FD_ISSET(ifp->int_rip_sock, &ibits)) {
541 read_rip(ifp->int_rip_sock, ifp);
551 sigalrm(int s UNUSED)
553 /* Historically, SIGALRM would cause the daemon to check for
554 * new and broken interfaces.
556 ifinit_timer.tv_sec = now.tv_sec;
557 trace_act("SIGALRM");
561 /* watch for fatal signals */
566 (void)signal(sig, SIG_DFL); /* catch it only once */
573 struct interface *ifp;
579 FD_SET(rt_sock, &fdbits);
580 if (sock_max <= rt_sock)
581 sock_max = rt_sock+1;
583 FD_SET(rip_sock, &fdbits);
584 if (sock_max <= rip_sock)
585 sock_max = rip_sock+1;
587 LIST_FOREACH(ifp, &ifnet, int_list) {
588 if (ifp->int_rip_sock >= 0) {
589 FD_SET(ifp->int_rip_sock, &fdbits);
590 if (sock_max <= ifp->int_rip_sock)
591 sock_max = ifp->int_rip_sock+1;
594 if (rdisc_sock >= 0) {
595 FD_SET(rdisc_sock, &fdbits);
596 if (sock_max <= rdisc_sock)
597 sock_max = rdisc_sock+1;
607 #define MIN_SOCKBUF (4*1024)
610 if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
611 logbad(1, "fcntl(%s) O_NONBLOCK: %s",
612 name, strerror(errno));
614 if (setsockopt(sock, SOL_SOCKET,SO_BROADCAST, &on,sizeof(on)) < 0)
615 msglog("setsockopt(%s,SO_BROADCAST): %s",
616 name, strerror(errno));
617 #ifdef USE_PASSIFNAME
619 if (setsockopt(sock, SOL_SOCKET, SO_PASSIFNAME, &on,sizeof(on)) < 0)
620 msglog("setsockopt(%s,SO_PASSIFNAME): %s",
621 name, strerror(errno));
624 if (rbuf >= MIN_SOCKBUF) {
625 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
626 &rbuf, sizeof(rbuf)) < 0)
627 msglog("setsockopt(%s,SO_RCVBUF=%d): %s",
628 name, rbuf, strerror(errno));
630 for (rbuf = 60*1024; ; rbuf -= 4096) {
631 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
632 &rbuf, sizeof(rbuf)) == 0) {
633 trace_act("RCVBUF=%d", rbuf);
636 if (rbuf < MIN_SOCKBUF) {
637 msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
638 name, rbuf, strerror(errno));
648 static int /* <0 or file descriptor */
649 get_rip_sock(naddr addr,
650 int serious) /* 1=failure to bind is serious */
652 struct sockaddr_in rsin;
657 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
658 BADERR(1,"rip_sock = socket()");
660 memset(&rsin, 0, sizeof(rsin));
662 rsin.sin_len = sizeof(rsin);
664 rsin.sin_family = AF_INET;
665 rsin.sin_port = htons(RIP_PORT);
666 rsin.sin_addr.s_addr = addr;
667 if (bind(s, (struct sockaddr *)&rsin, sizeof(rsin)) < 0) {
669 BADERR(errno != EADDRINUSE, "bind(rip_sock)");
673 fix_sock(s,"rip_sock");
676 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
677 &ttl, sizeof(ttl)) < 0)
678 DBGERR(1,"rip_sock setsockopt(IP_MULTICAST_TTL)");
684 /* turn off main RIP socket */
688 struct interface *ifp;
692 if (rip_sock >= 0 && !mhome) {
693 trace_act("turn off RIP");
695 (void)close(rip_sock);
698 /* get non-broadcast sockets to listen to queries.
700 LIST_FOREACH(ifp, &ifnet, int_list) {
701 if (ifp->int_state & IS_REMOTE)
703 if (ifp->int_rip_sock < 0) {
704 addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
707 ifp->int_rip_sock = get_rip_sock(addr, 0);
718 /* turn on RIP multicast input via an interface
721 rip_mcast_on(struct interface *ifp)
724 struct sockaddr_in *sin;
726 if (!IS_RIP_IN_OFF(ifp->int_state)
727 && (ifp->int_if_flags & IFF_MULTICAST)
728 && !(ifp->int_state & IS_ALIAS)) {
729 memset(&gr, 0, sizeof(gr));
730 gr.gr_interface = ifp->int_index;
731 sin = (struct sockaddr_in *)&gr.gr_group;
732 sin->sin_family = AF_INET;
734 sin->sin_len = sizeof(struct sockaddr_in);
736 sin->sin_addr.s_addr = htonl(INADDR_RIP_GROUP);
737 if (setsockopt(rip_sock, IPPROTO_IP, MCAST_JOIN_GROUP,
738 &gr, sizeof(gr)) < 0)
739 LOGERR("setsockopt(MCAST_JOIN_GROUP RIP)");
744 /* Prepare socket used for RIP.
747 rip_on(struct interface *ifp)
749 /* If the main RIP socket is already alive, only start receiving
750 * multicasts for this interface.
758 /* If the main RIP socket is off and it makes sense to turn it on,
759 * then turn it on for all of the interfaces.
760 * It makes sense if either router discovery is off, or if
761 * router discover is on and at most one interface is doing RIP.
763 if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
764 trace_act("turn on RIP");
766 /* Close all of the query sockets so that we can open
767 * the main socket. SO_REUSEPORT is not a solution,
768 * since that would let two daemons bind to the broadcast
771 LIST_FOREACH(ifp, &ifnet, int_list) {
772 if (ifp->int_rip_sock >= 0) {
773 (void)close(ifp->int_rip_sock);
774 ifp->int_rip_sock = -1;
778 rip_sock = get_rip_sock(INADDR_ANY, 1);
779 rip_sock_mcast = NULL;
781 /* Do not advertise anything until we have heard something
783 if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
784 next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
786 LIST_FOREACH(ifp, &ifnet, int_list) {
787 ifp->int_query_time = NEVER;
790 ifinit_timer.tv_sec = now.tv_sec;
792 } else if (ifp != NULL
793 && !(ifp->int_state & IS_REMOTE)
794 && ifp->int_rip_sock < 0) {
795 /* RIP is off, so ensure there are sockets on which
796 * to listen for queries.
798 ifp->int_rip_sock = get_rip_sock(ifp->int_addr, 0);
805 /* die if malloc(3) fails
808 rtmalloc(size_t size,
811 void *p = malloc(size);
813 logbad(1,"malloc(%lu) failed in %s", (u_long)size, msg);
818 /* get a random instant in an interval
821 intvl_random(struct timeval *tp, /* put value here */
822 u_long lo, /* value is after this second */
823 u_long hi) /* and before this */
825 tp->tv_sec = (time_t)(hi == lo
827 : (lo + arc4random_uniform(1 + hi - lo)));
828 tp->tv_usec = arc4random_uniform(1000000);
833 timevaladd(struct timeval *t1,
837 t1->tv_sec += t2->tv_sec;
838 if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
840 t1->tv_usec -= 1000000;
848 timevalsub(struct timeval *t1,
852 t1->tv_sec = t2->tv_sec - t3->tv_sec;
853 if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
855 t1->tv_usec += 1000000;
860 /* put a message into the system log
863 msglog(const char *p, ...)
870 vsyslog(LOG_ERR, p, args);
872 if (ftrace != NULL) {
873 if (ftrace == stdout)
874 (void)fputs("routed: ", ftrace);
876 (void)vfprintf(ftrace, p, args);
878 (void)fputc('\n', ftrace);
883 /* Put a message about a bad system into the system log if
884 * we have not complained about it recently.
886 * It is desirable to complain about all bad systems, but not too often.
887 * In the worst case, it is not practical to keep track of all bad systems.
888 * For example, there can be many systems with the wrong password.
891 msglim(struct msg_limit *lim, naddr addr, const char *p, ...)
895 struct msg_sub *ms1, *ms;
898 /* look for the oldest slot in the table
899 * or the slot for the bad router.
901 ms = ms1 = lim->subs;
902 for (i = MSG_SUBJECT_N; ; i--, ms1++) {
904 /* Reuse a slot at most once every 10 minutes.
906 if (lim->reuse > now.tv_sec) {
910 lim->reuse = now.tv_sec + 10*60;
914 if (ms->addr == addr) {
915 /* Repeat a complaint about a given system at
918 if (ms->until > now.tv_sec)
922 if (ms->until < ms1->until)
927 ms->until = now.tv_sec + 60*60; /* 60 minutes */
930 for (p1 = p; *p1 == ' '; p1++)
933 vsyslog(LOG_ERR, p1, args);
937 /* always display the message if tracing */
938 if (ftrace != NULL) {
940 (void)vfprintf(ftrace, p, args);
942 (void)fputc('\n', ftrace);
948 logbad(int dump, const char *p, ...)
955 vsyslog(LOG_ERR, p, args);
957 (void)fputs("routed: ", stderr);
959 (void)vfprintf(stderr, p, args);
961 (void)fputs("; giving up\n",stderr);
962 (void)fflush(stderr);