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"
40 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993 "
41 "The Regents of the University of California."
42 " All rights reserved.");
47 naddr myaddr; /* system address */
48 static char myname[MAXHOSTNAMELEN+1];
52 int supplier; /* supply or broadcast updates */
54 static int ipforwarding = 1; /* kernel forwarding on */
56 static int default_gateway; /* 1=advertise default */
57 static int background = 1;
58 int ridhosts; /* 1=reduce host routes */
59 int mhome; /* 1=want multi-homed host route */
60 int advertise_mhome; /* 1=must continue advertising it */
61 int auth_ok = 1; /* 1=ignore auth if we do not care */
62 int insecure; /* Reply to special queries or not */
64 struct timeval epoch; /* when started */
66 static struct timeval prev_clk;
67 static int usec_fudge;
68 struct timeval now; /* current idea of time */
73 static struct timeval next_bcast; /* next general broadcast */
74 struct timeval no_flash = { /* inhibit flash update */
75 EPOCH+SUPPLY_INTERVAL, 0
78 static struct timeval flush_kern_timer;
82 int rip_sock = -1; /* RIP socket */
83 const struct interface *rip_sock_mcast; /* current multicast interface */
84 int rt_sock; /* routing socket */
88 static int get_rip_sock(naddr, int);
89 static void timevalsub(struct timeval *, struct timeval *, struct timeval *);
90 static void sigalrm(int s UNUSED);
91 static void sigterm(int sig);
101 struct timeval wtime, t2;
105 struct interface *ifp;
110 /* Some shells are badly broken and send SIGHUP to backgrounded
113 signal(SIGHUP, SIG_IGN);
115 openlog("routed", LOG_PID, LOG_DAEMON);
118 gettimeofday(&clk, 0);
121 epoch.tv_sec -= EPOCH;
123 now_stale = EPOCH - STALE_TIME;
124 now_expire = EPOCH - EXPIRE_TIME;
125 now_garbage = EPOCH - GARBAGE_TIME;
128 (void)gethostname(myname, sizeof(myname)-1);
129 (void)gethost(myname, &myaddr);
131 while ((n = getopt(argc, argv, "isqdghmAtvT:F:P:")) != -1) {
151 memset(&parm, 0, sizeof(parm));
152 parm.parm_d_metric = 1;
153 cp = check_parms(&parm);
155 msglog("bad -g: %s", cp);
160 case 'h': /* suppress extra host routes */
164 case 'm': /* advertise host route */
165 mhome = 1; /* on multi-homed hosts */
169 /* Ignore authentication if we do not care.
170 * Crazy as it is, that is what RFC 1723 requires.
183 case 'F': /* minimal routes for SLIP */
185 p = strchr(optarg,',');
186 if (p && *p != '\0') {
187 n = (int)strtoul(p+1, &q, 0);
189 && n <= HOPCNT_INFINITY-1
193 if (!getnet(optarg, &p_net, &p_mask)) {
194 msglog("bad network; \"-F %s\"",
198 memset(&parm, 0, sizeof(parm));
199 parm.parm_net = p_net;
200 parm.parm_mask = p_mask;
201 parm.parm_d_metric = n;
202 cp = check_parms(&parm);
204 msglog("bad -F: %s", cp);
208 /* handle arbitrary parameters.
211 cp = parse_parms(q, 0);
213 msglog("%s in \"-P %s\"", cp, optarg);
218 /* display version */
220 msglog("version 2.31");
230 if (tracename == 0 && argc >= 1) {
234 if (tracename != 0 && tracename[0] == '\0')
238 logbad(0, "usage: routed [-sqdghmAtv] [-T tracefile]"
239 " [-F net[,metric]] [-P parms]");
241 if (geteuid() != 0) {
244 logbad(0, "requires UID 0");
250 mib[3] = IPCTL_FORWARDING;
251 len = sizeof(ipforwarding);
252 if (sysctl(mib, 4, &ipforwarding, &len, 0, 0) < 0)
253 LOGERR("sysctl(IPCTL_FORWARDING)");
257 msglog("-s incompatible with ipforwarding=0");
258 if (default_gateway) {
259 msglog("-g incompatible with ipforwarding=0");
265 if (default_gateway) {
266 if (supplier_set && !supplier) {
267 msglog("-g and -q incompatible");
275 signal(SIGALRM, sigalrm);
277 signal(SIGHUP, sigterm); /* SIGHUP fatal during debugging */
278 signal(SIGTERM, sigterm);
279 signal(SIGINT, sigterm);
280 signal(SIGUSR1, sigtrace_on);
281 signal(SIGUSR2, sigtrace_off);
283 /* get into the background */
284 if (background && daemon(0, 1) < 0)
285 BADERR(0,"daemon()");
289 /* prepare socket connected to the kernel.
291 rt_sock = socket(AF_ROUTE, SOCK_RAW, 0);
293 BADERR(1,"rt_sock = socket()");
294 if (fcntl(rt_sock, F_SETFL, O_NONBLOCK) == -1)
295 logbad(1, "fcntl(rt_sock) O_NONBLOCK: %s", strerror(errno));
297 if (setsockopt(rt_sock, SOL_SOCKET,SO_USELOOPBACK,
298 &off,sizeof(off)) < 0)
299 LOGERR("setsockopt(SO_USELOOPBACK,0)");
304 if (tracename != 0) {
305 strncpy(inittracename, tracename, sizeof(inittracename)-1);
306 set_tracefile(inittracename, "%s", -1);
308 tracelevel_msg("%s", -1); /* turn on tracing to stdio */
313 /* initialize radix tree */
316 /* Pick a random part of the second for our output to minimize
319 * Start broadcasting after hearing from other routers, and
320 * at a random time so a bunch of systems do not get synchronized
321 * after a power failure.
323 intvl_random(&next_bcast, EPOCH+MIN_WAITTIME, EPOCH+SUPPLY_INTERVAL);
324 age_timer.tv_usec = next_bcast.tv_usec;
325 age_timer.tv_sec = EPOCH+MIN_WAITTIME;
326 rdisc_timer = next_bcast;
327 ifinit_timer.tv_usec = next_bcast.tv_usec;
329 /* Collect an initial view of the world by checking the interface
330 * configuration and the kludge file.
339 /* Now turn off stdio if not tracing */
340 if (new_tracelevel == 0)
341 trace_close(background);
343 /* Loop forever, listening and broadcasting.
347 gettimeofday(&clk, 0);
348 if (prev_clk.tv_sec == clk.tv_sec
349 && prev_clk.tv_usec == clk.tv_usec+usec_fudge) {
350 /* Much of `routed` depends on time always advancing.
351 * On systems that do not guarantee that gettimeofday()
352 * produces unique timestamps even if called within
353 * a single tick, use trickery like that in classic
356 clk.tv_usec += ++usec_fudge;
361 timevalsub(&t2, &clk, &prev_clk);
363 || t2.tv_sec > wtime.tv_sec + 5) {
364 /* Deal with time changes before other
365 * housekeeping to keep everything straight.
370 trace_act("time changed by %d sec", (int)dt);
374 timevalsub(&now, &clk, &epoch);
375 now_stale = now.tv_sec - STALE_TIME;
376 now_expire = now.tv_sec - EXPIRE_TIME;
377 now_garbage = now.tv_sec - GARBAGE_TIME;
379 /* deal with signals that should affect tracing */
385 trace_off("exiting with signal %d", stopint);
389 /* look for new or dead interfaces */
390 timevalsub(&wtime, &ifinit_timer, &now);
391 if (wtime.tv_sec <= 0) {
398 /* Check the kernel table occasionally for mysteriously
401 timevalsub(&t2, &flush_kern_timer, &now);
402 if (t2.tv_sec <= 0) {
404 flush_kern_timer.tv_sec = (now.tv_sec
405 + CHECK_QUIET_INTERVAL);
408 if (timercmp(&t2, &wtime, <))
411 /* If it is time, then broadcast our routes.
413 if (supplier || advertise_mhome) {
414 timevalsub(&t2, &next_bcast, &now);
415 if (t2.tv_sec <= 0) {
416 /* Synchronize the aging and broadcast
417 * timers to minimize awakenings
423 /* It is desirable to send routing updates
424 * regularly. So schedule the next update
425 * 30 seconds after the previous one was
426 * scheduled, instead of 30 seconds after
427 * the previous update was finished.
428 * Even if we just started after discovering
429 * a 2nd interface or were otherwise delayed,
430 * pick a 30-second anniversary of the
431 * original broadcast time.
433 n = 1 + (0-t2.tv_sec)/SUPPLY_INTERVAL;
434 next_bcast.tv_sec += n*SUPPLY_INTERVAL;
439 if (timercmp(&t2, &wtime, <))
443 /* If we need a flash update, either do it now or
444 * set the delay to end when it is time.
446 * If we are within MIN_WAITTIME seconds of a full update,
451 && no_flash.tv_sec+MIN_WAITTIME < next_bcast.tv_sec) {
452 /* accurate to the millisecond */
453 if (!timercmp(&no_flash, &now, >))
455 timevalsub(&t2, &no_flash, &now);
456 if (timercmp(&t2, &wtime, <))
460 /* trigger the main aging timer.
462 timevalsub(&t2, &age_timer, &now);
463 if (t2.tv_sec <= 0) {
467 if (timercmp(&t2, &wtime, <))
470 /* update the kernel routing table
472 timevalsub(&t2, &need_kern, &now);
473 if (t2.tv_sec <= 0) {
477 if (timercmp(&t2, &wtime, <))
480 /* take care of router discovery,
481 * but do it in the correct the millisecond
483 if (!timercmp(&rdisc_timer, &now, >)) {
487 timevalsub(&t2, &rdisc_timer, &now);
488 if (timercmp(&t2, &wtime, <))
492 /* wait for input or a timer to expire.
496 n = select(sock_max, &ibits, 0, 0, &wtime);
498 if (n < 0 && errno != EINTR && errno != EAGAIN)
503 if (FD_ISSET(rt_sock, &ibits)) {
507 if (rdisc_sock >= 0 && FD_ISSET(rdisc_sock, &ibits)) {
511 if (rip_sock >= 0 && FD_ISSET(rip_sock, &ibits)) {
512 read_rip(rip_sock, 0);
516 LIST_FOREACH(ifp, &ifnet, int_list) {
519 if (ifp->int_rip_sock >= 0
520 && FD_ISSET(ifp->int_rip_sock, &ibits)) {
521 read_rip(ifp->int_rip_sock, ifp);
531 sigalrm(int s UNUSED)
533 /* Historically, SIGALRM would cause the daemon to check for
534 * new and broken interfaces.
536 ifinit_timer.tv_sec = now.tv_sec;
537 trace_act("SIGALRM");
541 /* watch for fatal signals */
546 (void)signal(sig, SIG_DFL); /* catch it only once */
553 struct interface *ifp;
559 FD_SET(rt_sock, &fdbits);
560 if (sock_max <= rt_sock)
561 sock_max = rt_sock+1;
563 FD_SET(rip_sock, &fdbits);
564 if (sock_max <= rip_sock)
565 sock_max = rip_sock+1;
567 LIST_FOREACH(ifp, &ifnet, int_list) {
568 if (ifp->int_rip_sock >= 0) {
569 FD_SET(ifp->int_rip_sock, &fdbits);
570 if (sock_max <= ifp->int_rip_sock)
571 sock_max = ifp->int_rip_sock+1;
574 if (rdisc_sock >= 0) {
575 FD_SET(rdisc_sock, &fdbits);
576 if (sock_max <= rdisc_sock)
577 sock_max = rdisc_sock+1;
587 #define MIN_SOCKBUF (4*1024)
590 if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
591 logbad(1, "fcntl(%s) O_NONBLOCK: %s",
592 name, strerror(errno));
594 if (setsockopt(sock, SOL_SOCKET,SO_BROADCAST, &on,sizeof(on)) < 0)
595 msglog("setsockopt(%s,SO_BROADCAST): %s",
596 name, strerror(errno));
597 #ifdef USE_PASSIFNAME
599 if (setsockopt(sock, SOL_SOCKET, SO_PASSIFNAME, &on,sizeof(on)) < 0)
600 msglog("setsockopt(%s,SO_PASSIFNAME): %s",
601 name, strerror(errno));
604 if (rbuf >= MIN_SOCKBUF) {
605 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
606 &rbuf, sizeof(rbuf)) < 0)
607 msglog("setsockopt(%s,SO_RCVBUF=%d): %s",
608 name, rbuf, strerror(errno));
610 for (rbuf = 60*1024; ; rbuf -= 4096) {
611 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
612 &rbuf, sizeof(rbuf)) == 0) {
613 trace_act("RCVBUF=%d", rbuf);
616 if (rbuf < MIN_SOCKBUF) {
617 msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
618 name, rbuf, strerror(errno));
628 static int /* <0 or file descriptor */
629 get_rip_sock(naddr addr,
630 int serious) /* 1=failure to bind is serious */
632 struct sockaddr_in rsin;
637 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
638 BADERR(1,"rip_sock = socket()");
640 memset(&rsin, 0, sizeof(rsin));
642 rsin.sin_len = sizeof(rsin);
644 rsin.sin_family = AF_INET;
645 rsin.sin_port = htons(RIP_PORT);
646 rsin.sin_addr.s_addr = addr;
647 if (bind(s, (struct sockaddr *)&rsin, sizeof(rsin)) < 0) {
649 BADERR(errno != EADDRINUSE, "bind(rip_sock)");
653 fix_sock(s,"rip_sock");
656 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
657 &ttl, sizeof(ttl)) < 0)
658 DBGERR(1,"rip_sock setsockopt(IP_MULTICAST_TTL)");
664 /* turn off main RIP socket */
668 struct interface *ifp;
672 if (rip_sock >= 0 && !mhome) {
673 trace_act("turn off RIP");
675 (void)close(rip_sock);
678 /* get non-broadcast sockets to listen to queries.
680 LIST_FOREACH(ifp, &ifnet, int_list) {
681 if (ifp->int_state & IS_REMOTE)
683 if (ifp->int_rip_sock < 0) {
684 addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
687 ifp->int_rip_sock = get_rip_sock(addr, 0);
698 /* turn on RIP multicast input via an interface
701 rip_mcast_on(struct interface *ifp)
704 struct sockaddr_in *sin;
706 if (!IS_RIP_IN_OFF(ifp->int_state)
707 && (ifp->int_if_flags & IFF_MULTICAST)
708 && !(ifp->int_state & IS_ALIAS)) {
709 memset(&gr, 0, sizeof(gr));
710 gr.gr_interface = ifp->int_index;
711 sin = (struct sockaddr_in *)&gr.gr_group;
712 sin->sin_family = AF_INET;
714 sin->sin_len = sizeof(struct sockaddr_in);
716 sin->sin_addr.s_addr = htonl(INADDR_RIP_GROUP);
717 if (setsockopt(rip_sock, IPPROTO_IP, MCAST_JOIN_GROUP,
718 &gr, sizeof(gr)) < 0)
719 LOGERR("setsockopt(MCAST_JOIN_GROUP RIP)");
724 /* Prepare socket used for RIP.
727 rip_on(struct interface *ifp)
729 /* If the main RIP socket is already alive, only start receiving
730 * multicasts for this interface.
738 /* If the main RIP socket is off and it makes sense to turn it on,
739 * then turn it on for all of the interfaces.
740 * It makes sense if either router discovery is off, or if
741 * router discover is on and at most one interface is doing RIP.
743 if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
744 trace_act("turn on RIP");
746 /* Close all of the query sockets so that we can open
747 * the main socket. SO_REUSEPORT is not a solution,
748 * since that would let two daemons bind to the broadcast
751 LIST_FOREACH(ifp, &ifnet, int_list) {
752 if (ifp->int_rip_sock >= 0) {
753 (void)close(ifp->int_rip_sock);
754 ifp->int_rip_sock = -1;
758 rip_sock = get_rip_sock(INADDR_ANY, 1);
759 rip_sock_mcast = NULL;
761 /* Do not advertise anything until we have heard something
763 if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
764 next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
766 LIST_FOREACH(ifp, &ifnet, int_list) {
767 ifp->int_query_time = NEVER;
770 ifinit_timer.tv_sec = now.tv_sec;
772 } else if (ifp != NULL
773 && !(ifp->int_state & IS_REMOTE)
774 && ifp->int_rip_sock < 0) {
775 /* RIP is off, so ensure there are sockets on which
776 * to listen for queries.
778 ifp->int_rip_sock = get_rip_sock(ifp->int_addr, 0);
785 /* die if malloc(3) fails
788 rtmalloc(size_t size,
791 void *p = malloc(size);
793 logbad(1,"malloc(%lu) failed in %s", (u_long)size, msg);
798 /* get a random instant in an interval
801 intvl_random(struct timeval *tp, /* put value here */
802 u_long lo, /* value is after this second */
803 u_long hi) /* and before this */
805 tp->tv_sec = (time_t)(hi == lo
807 : (lo + arc4random_uniform(1 + hi - lo)));
808 tp->tv_usec = arc4random_uniform(1000000);
813 timevaladd(struct timeval *t1,
817 t1->tv_sec += t2->tv_sec;
818 if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
820 t1->tv_usec -= 1000000;
828 timevalsub(struct timeval *t1,
832 t1->tv_sec = t2->tv_sec - t3->tv_sec;
833 if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
835 t1->tv_usec += 1000000;
840 /* put a message into the system log
843 msglog(const char *p, ...)
850 vsyslog(LOG_ERR, p, args);
852 if (ftrace != NULL) {
853 if (ftrace == stdout)
854 (void)fputs("routed: ", ftrace);
856 (void)vfprintf(ftrace, p, args);
858 (void)fputc('\n', ftrace);
863 /* Put a message about a bad system into the system log if
864 * we have not complained about it recently.
866 * It is desirable to complain about all bad systems, but not too often.
867 * In the worst case, it is not practical to keep track of all bad systems.
868 * For example, there can be many systems with the wrong password.
871 msglim(struct msg_limit *lim, naddr addr, const char *p, ...)
875 struct msg_sub *ms1, *ms;
878 /* look for the oldest slot in the table
879 * or the slot for the bad router.
881 ms = ms1 = lim->subs;
882 for (i = MSG_SUBJECT_N; ; i--, ms1++) {
884 /* Reuse a slot at most once every 10 minutes.
886 if (lim->reuse > now.tv_sec) {
890 lim->reuse = now.tv_sec + 10*60;
894 if (ms->addr == addr) {
895 /* Repeat a complaint about a given system at
898 if (ms->until > now.tv_sec)
902 if (ms->until < ms1->until)
907 ms->until = now.tv_sec + 60*60; /* 60 minutes */
910 for (p1 = p; *p1 == ' '; p1++)
913 vsyslog(LOG_ERR, p1, args);
917 /* always display the message if tracing */
918 if (ftrace != NULL) {
920 (void)vfprintf(ftrace, p, args);
922 (void)fputc('\n', ftrace);
928 logbad(int dump, const char *p, ...)
935 vsyslog(LOG_ERR, p, args);
937 (void)fputs("routed: ", stderr);
939 (void)vfprintf(stderr, p, args);
941 (void)fputs("; giving up\n",stderr);
942 (void)fflush(stderr);