main.c revision 1.35 1 /* $NetBSD: main.c,v 1.35 2003/11/14 01:31:24 enami Exp $ */
2
3 /*
4 * Copyright (c) 1983, 1988, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
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. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgment:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include "defs.h"
37 #include "pathnames.h"
38 #ifdef sgi
39 #include "math.h"
40 #endif
41 #include <signal.h>
42 #include <fcntl.h>
43 #include <sys/file.h>
44
45 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993\n"
46 "The Regents of the University of California."
47 " All rights reserved.\n");
48 #ifdef __NetBSD__
49 __RCSID("$NetBSD: main.c,v 1.35 2003/11/14 01:31:24 enami Exp $");
50 #elif defined(__FreeBSD__)
51 __RCSID("$FreeBSD$");
52 #else
53 __RCSID("Revision: 2.27 ");
54 #ident "Revision: 2.27 "
55 #endif
56
57 #if defined(__NetBSD__)
58 #include <util.h>
59 #endif
60
61 pid_t mypid;
62
63 naddr myaddr; /* system address */
64 char myname[MAXHOSTNAMELEN+1];
65
66 int verbose;
67
68 int supplier; /* supply or broadcast updates */
69 int supplier_set;
70 int ipforwarding = 1; /* kernel forwarding on */
71
72 int default_gateway; /* 1=advertise default */
73 int background = 1;
74 int ridhosts; /* 1=reduce host routes */
75 int mhome; /* 1=want multi-homed host route */
76 int advertise_mhome; /* 1=must continue advertising it */
77 int auth_ok = 1; /* 1=ignore auth if we do not care */
78
79 struct timeval epoch; /* when started */
80 struct timeval clk, prev_clk;
81 static int usec_fudge;
82 struct timeval now; /* current idea of time */
83 time_t now_stale;
84 time_t now_expire;
85 time_t now_garbage;
86
87 struct timeval next_bcast; /* next general broadcast */
88 struct timeval no_flash = { /* inhibit flash update */
89 EPOCH+SUPPLY_INTERVAL, 0
90 };
91
92 struct timeval flush_kern_timer;
93
94 fd_set *fdbitsp;
95 int sock_max;
96 int rip_sock = -1; /* RIP socket */
97 struct interface *rip_sock_mcast; /* current multicast interface */
98 int rt_sock; /* routing socket */
99 int rt_sock_seqno;
100
101
102 static int get_rip_sock(naddr, int);
103 static void timevalsub(struct timeval *, struct timeval *, struct timeval *);
104
105 int
106 main(int argc,
107 char *argv[])
108 {
109 int n, mib[4], off;
110 size_t len;
111 char *p, *q;
112 const char *cp;
113 struct timeval wtime, t2;
114 time_t dt;
115 fd_set *ibitsp = NULL;
116 naddr p_net, p_mask;
117 struct interface *ifp;
118 struct parm parm;
119 char *tracename = 0;
120
121
122 /* Some shells are badly broken and send SIGHUP to backgrounded
123 * processes.
124 */
125 signal(SIGHUP, SIG_IGN);
126
127 openlog("routed", LOG_PID, LOG_DAEMON);
128 ftrace = stdout;
129
130 gettimeofday(&clk, 0);
131 prev_clk = clk;
132 epoch = clk;
133 epoch.tv_sec -= EPOCH;
134 now.tv_sec = EPOCH;
135 now_stale = EPOCH - STALE_TIME;
136 now_expire = EPOCH - EXPIRE_TIME;
137 now_garbage = EPOCH - GARBAGE_TIME;
138 wtime.tv_sec = 0;
139
140 (void)gethostname(myname, sizeof(myname) - 1);
141 (void)gethost(myname, &myaddr);
142
143 while ((n = getopt(argc, argv, "sqdghmpAtvT:F:P:")) != -1) {
144 switch (n) {
145 case 's':
146 supplier = 1;
147 supplier_set = 1;
148 break;
149
150 case 'q':
151 supplier = 0;
152 supplier_set = 1;
153 break;
154
155 case 'd':
156 background = 0;
157 break;
158
159 case 'g':
160 memset(&parm, 0, sizeof(parm));
161 parm.parm_d_metric = 1;
162 cp = check_parms(&parm);
163 if (cp != 0)
164 msglog("bad -g: %s", cp);
165 else
166 default_gateway = 1;
167 break;
168
169 case 'h': /* suppress extra host routes */
170 ridhosts = 1;
171 break;
172
173 case 'm': /* advertise host route */
174 mhome = 1; /* on multi-homed hosts */
175 break;
176
177 case 'A':
178 /* Ignore authentication if we do not care.
179 * Crazy as it is, that is what RFC 1723 requires.
180 */
181 auth_ok = 0;
182 break;
183
184 case 't':
185 new_tracelevel++;
186 break;
187
188 case 'T':
189 tracename = optarg;
190 break;
191
192 case 'F': /* minimal routes for SLIP */
193 n = FAKE_METRIC;
194 p = strchr(optarg,',');
195 if (p && *p != '\0') {
196 n = (int)strtoul(p+1, &q, 0);
197 if (*q == '\0'
198 && n <= HOPCNT_INFINITY-1
199 && n >= 1)
200 *p = '\0';
201 }
202 if (!getnet(optarg, &p_net, &p_mask)) {
203 msglog("bad network; \"-F %s\"",
204 optarg);
205 break;
206 }
207 memset(&parm, 0, sizeof(parm));
208 parm.parm_net = p_net;
209 parm.parm_mask = p_mask;
210 parm.parm_d_metric = n;
211 cp = check_parms(&parm);
212 if (cp != 0)
213 msglog("bad -F: %s", cp);
214 break;
215
216 case 'P':
217 /* handle arbitrary parameters.
218 */
219 q = strdup(optarg);
220 cp = parse_parms(q, 0);
221 if (cp != 0)
222 msglog("%s in \"-P %s\"", cp, optarg);
223 free(q);
224 break;
225
226 case 'v':
227 /* display version */
228 verbose++;
229 msglog("version 2.25");
230 break;
231
232 default:
233 goto usage;
234 }
235 }
236 argc -= optind;
237 argv += optind;
238
239 if (tracename == 0 && argc >= 1) {
240 tracename = *argv++;
241 argc--;
242 }
243 if (tracename != 0 && tracename[0] == '\0')
244 goto usage;
245 if (argc != 0) {
246 usage:
247 logbad(0, "usage: routed [-sqdghmpAtv] [-T tracefile]"
248 " [-F net[,metric]] [-P parms]");
249 }
250 if (geteuid() != 0) {
251 if (verbose)
252 exit(0);
253 logbad(0, "requires UID 0");
254 }
255
256 mib[0] = CTL_NET;
257 mib[1] = PF_INET;
258 mib[2] = IPPROTO_IP;
259 mib[3] = IPCTL_FORWARDING;
260 len = sizeof(ipforwarding);
261 if (sysctl(mib, 4, &ipforwarding, &len, 0, 0) < 0)
262 LOGERR("sysctl(IPCTL_FORWARDING)");
263
264 if (!ipforwarding) {
265 if (supplier)
266 msglog("-s incompatible with ipforwarding=0");
267 if (default_gateway) {
268 msglog("-g incompatible with ipforwarding=0");
269 default_gateway = 0;
270 }
271 supplier = 0;
272 supplier_set = 1;
273 }
274 if (default_gateway) {
275 if (supplier_set && !supplier) {
276 msglog("-g and -q incompatible");
277 } else {
278 supplier = 1;
279 supplier_set = 1;
280 }
281 }
282
283
284 signal(SIGALRM, sigalrm);
285 if (!background)
286 signal(SIGHUP, sigterm); /* SIGHUP fatal during debugging */
287 signal(SIGTERM, sigterm);
288 signal(SIGINT, sigterm);
289 signal(SIGUSR1, sigtrace_on);
290 signal(SIGUSR2, sigtrace_off);
291
292 /* get into the background */
293 #ifdef sgi
294 if (0 > _daemonize(background ? 0 : (_DF_NOCHDIR|_DF_NOFORK),
295 STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO))
296 BADERR(0, "_daemonize()");
297 #else
298 if (background && daemon(0, 1) < 0)
299 BADERR(0,"daemon()");
300 #endif
301
302 #if defined(__NetBSD__)
303 pidfile(NULL);
304 #endif
305 mypid = getpid();
306
307 /* prepare socket connected to the kernel.
308 */
309 rt_sock = socket(AF_ROUTE, SOCK_RAW, 0);
310 if (rt_sock < 0)
311 BADERR(1,"rt_sock = socket()");
312 if (fcntl(rt_sock, F_SETFL, O_NONBLOCK) == -1)
313 logbad(1, "fcntl(rt_sock) O_NONBLOCK: %s", strerror(errno));
314 off = 0;
315 if (setsockopt(rt_sock, SOL_SOCKET,SO_USELOOPBACK,
316 &off,sizeof(off)) < 0)
317 LOGERR("setsockopt(SO_USELOOPBACK,0)");
318
319 fix_select();
320
321
322 if (tracename != 0) {
323 strlcpy(inittracename, tracename, sizeof(inittracename));
324 set_tracefile(inittracename, "%s", -1);
325 } else {
326 tracelevel_msg("%s", -1); /* turn on tracing to stdio */
327 }
328
329 bufinit();
330
331 /* initialize radix tree */
332 rtinit();
333
334 /* Pick a random part of the second for our output to minimize
335 * collisions.
336 *
337 * Start broadcasting after hearing from other routers, and
338 * at a random time so a bunch of systems do not get synchronized
339 * after a power failure.
340 */
341 intvl_random(&next_bcast, EPOCH+MIN_WAITTIME, EPOCH+SUPPLY_INTERVAL);
342 age_timer.tv_usec = next_bcast.tv_usec;
343 age_timer.tv_sec = EPOCH+MIN_WAITTIME;
344 rdisc_timer = next_bcast;
345 ifinit_timer.tv_usec = next_bcast.tv_usec;
346
347 /* Collect an initial view of the world by checking the interface
348 * configuration and the kludge file.
349 */
350 gwkludge();
351 ifinit();
352
353 /* Ask for routes */
354 rip_query();
355 rdisc_sol();
356
357 /* Now turn off stdio if not tracing */
358 if (new_tracelevel == 0)
359 trace_close(background);
360
361 /* Loop forever, listening and broadcasting.
362 */
363 for (;;) {
364 prev_clk = clk;
365 gettimeofday(&clk, 0);
366 if (prev_clk.tv_sec == clk.tv_sec
367 && prev_clk.tv_usec == clk.tv_usec+usec_fudge) {
368 /* Much of `routed` depends on time always advancing.
369 * On systems that do not guarantee that gettimeofday()
370 * produces unique timestamps even if called within
371 * a single tick, use trickery like that in classic
372 * BSD kernels.
373 */
374 clk.tv_usec += ++usec_fudge;
375
376 } else {
377 usec_fudge = 0;
378
379 timevalsub(&t2, &clk, &prev_clk);
380 if (t2.tv_sec < 0
381 || t2.tv_sec > wtime.tv_sec + 5) {
382 /* Deal with time changes before other
383 * housekeeping to keep everything straight.
384 */
385 dt = t2.tv_sec;
386 if (dt > 0)
387 dt -= wtime.tv_sec;
388 trace_act("time changed by %d sec", (int)dt);
389 epoch.tv_sec += dt;
390 }
391 }
392 timevalsub(&now, &clk, &epoch);
393 now_stale = now.tv_sec - STALE_TIME;
394 now_expire = now.tv_sec - EXPIRE_TIME;
395 now_garbage = now.tv_sec - GARBAGE_TIME;
396
397 /* deal with signals that should affect tracing */
398 set_tracelevel();
399
400 if (stopint != 0) {
401 rip_bcast(0);
402 rdisc_adv();
403 trace_off("exiting with signal %d", stopint);
404 exit(stopint | 128);
405 }
406
407 /* look for new or dead interfaces */
408 timevalsub(&wtime, &ifinit_timer, &now);
409 if (wtime.tv_sec <= 0) {
410 wtime.tv_sec = 0;
411 ifinit();
412 rip_query();
413 continue;
414 }
415
416 /* Check the kernel table occassionally for mysteriously
417 * evaporated routes
418 */
419 timevalsub(&t2, &flush_kern_timer, &now);
420 if (t2.tv_sec <= 0) {
421 flush_kern();
422 flush_kern_timer.tv_sec = (now.tv_sec
423 + CHECK_QUIET_INTERVAL);
424 continue;
425 }
426 if (timercmp(&t2, &wtime, <))
427 wtime = t2;
428
429 /* If it is time, then broadcast our routes.
430 */
431 if (supplier || advertise_mhome) {
432 timevalsub(&t2, &next_bcast, &now);
433 if (t2.tv_sec <= 0) {
434 /* Synchronize the aging and broadcast
435 * timers to minimize awakenings
436 */
437 age(0);
438
439 rip_bcast(0);
440
441 /* It is desirable to send routing updates
442 * regularly. So schedule the next update
443 * 30 seconds after the previous one was
444 * scheduled, instead of 30 seconds after
445 * the previous update was finished.
446 * Even if we just started after discovering
447 * a 2nd interface or were otherwise delayed,
448 * pick a 30-second aniversary of the
449 * original broadcast time.
450 */
451 n = 1 + (0-t2.tv_sec)/SUPPLY_INTERVAL;
452 next_bcast.tv_sec += n*SUPPLY_INTERVAL;
453
454 continue;
455 }
456
457 if (timercmp(&t2, &wtime, <))
458 wtime = t2;
459 }
460
461 /* If we need a flash update, either do it now or
462 * set the delay to end when it is time.
463 *
464 * If we are within MIN_WAITTIME seconds of a full update,
465 * do not bother.
466 */
467 if (need_flash
468 && supplier
469 && no_flash.tv_sec+MIN_WAITTIME < next_bcast.tv_sec) {
470 /* accurate to the millisecond */
471 if (!timercmp(&no_flash, &now, >))
472 rip_bcast(1);
473 timevalsub(&t2, &no_flash, &now);
474 if (timercmp(&t2, &wtime, <))
475 wtime = t2;
476 }
477
478 /* trigger the main aging timer.
479 */
480 timevalsub(&t2, &age_timer, &now);
481 if (t2.tv_sec <= 0) {
482 age(0);
483 continue;
484 }
485 if (timercmp(&t2, &wtime, <))
486 wtime = t2;
487
488 /* update the kernel routing table
489 */
490 timevalsub(&t2, &need_kern, &now);
491 if (t2.tv_sec <= 0) {
492 age(0);
493 continue;
494 }
495 if (timercmp(&t2, &wtime, <))
496 wtime = t2;
497
498 /* take care of router discovery,
499 * but do it in the correct the millisecond
500 */
501 if (!timercmp(&rdisc_timer, &now, >)) {
502 rdisc_age(0);
503 continue;
504 }
505 timevalsub(&t2, &rdisc_timer, &now);
506 if (timercmp(&t2, &wtime, <))
507 wtime = t2;
508
509
510 /* wait for input or a timer to expire.
511 */
512 trace_flush();
513 if (ibitsp)
514 free(ibitsp);
515 ibitsp = (fd_set *)calloc(howmany(sock_max, NFDBITS),
516 sizeof(fd_mask));
517 if (ibitsp == NULL)
518 BADERR(1, "calloc");
519 memcpy(ibitsp, fdbitsp, howmany(sock_max, NFDBITS) *
520 sizeof(fd_mask));
521 n = select(sock_max, ibitsp, 0, 0, &wtime);
522 if (n <= 0) {
523 if (n < 0 && errno != EINTR && errno != EAGAIN)
524 BADERR(1,"select");
525 continue;
526 }
527
528 if (FD_ISSET(rt_sock, ibitsp)) {
529 read_rt();
530 n--;
531 }
532 if (rdisc_sock >= 0 && FD_ISSET(rdisc_sock, ibitsp)) {
533 read_d();
534 n--;
535 }
536 if (rip_sock >= 0 && FD_ISSET(rip_sock, ibitsp)) {
537 read_rip(rip_sock, 0);
538 n--;
539 }
540
541 for (ifp = ifnet; n > 0 && 0 != ifp; ifp = ifp->int_next) {
542 if (ifp->int_rip_sock >= 0
543 && FD_ISSET(ifp->int_rip_sock, ibitsp)) {
544 read_rip(ifp->int_rip_sock, ifp);
545 n--;
546 }
547 }
548 }
549 }
550
551
552 /* ARGSUSED */
553 void
554 sigalrm(int s UNUSED)
555 {
556 /* Historically, SIGALRM would cause the daemon to check for
557 * new and broken interfaces.
558 */
559 ifinit_timer.tv_sec = now.tv_sec;
560 trace_act("SIGALRM");
561 }
562
563
564 /* watch for fatal signals */
565 void
566 sigterm(int sig)
567 {
568 stopint = sig;
569 (void)signal(sig, SIG_DFL); /* catch it only once */
570 }
571
572
573 void
574 fix_select(void)
575 {
576 struct interface *ifp;
577
578 sock_max = 0;
579
580 if (sock_max <= rt_sock)
581 sock_max = rt_sock + 1;
582 if (rip_sock >= 0)
583 if (sock_max <= rip_sock)
584 sock_max = rip_sock + 1;
585 for (ifp = ifnet; 0 != ifp; ifp = ifp->int_next) {
586 if (ifp->int_rip_sock >= 0)
587 if (sock_max <= ifp->int_rip_sock)
588 sock_max = ifp->int_rip_sock + 1;
589 }
590 if (rdisc_sock >= 0)
591 if (sock_max <= rdisc_sock)
592 sock_max = rdisc_sock + 1;
593
594 if (fdbitsp)
595 free(fdbitsp);
596 fdbitsp = (fd_set *)calloc(howmany(sock_max, NFDBITS),
597 sizeof(fd_mask));
598 if (fdbitsp == NULL)
599 BADERR(1, "calloc");
600
601 FD_SET(rt_sock, fdbitsp);
602 if (rip_sock >= 0)
603 FD_SET(rip_sock, fdbitsp);
604 for (ifp = ifnet; 0 != ifp; ifp = ifp->int_next) {
605 if (ifp->int_rip_sock >= 0)
606 FD_SET(ifp->int_rip_sock, fdbitsp);
607 }
608 if (rdisc_sock >= 0)
609 FD_SET(rdisc_sock, fdbitsp);
610 }
611
612
613 void
614 fix_sock(int sock,
615 const char *name)
616 {
617 int on;
618 #define MIN_SOCKBUF (4*1024)
619 static int rbuf;
620
621 if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
622 logbad(1, "fcntl(%s) O_NONBLOCK: %s",
623 name, strerror(errno));
624 on = 1;
625 if (setsockopt(sock, SOL_SOCKET,SO_BROADCAST, &on,sizeof(on)) < 0)
626 msglog("setsockopt(%s,SO_BROADCAST): %s",
627 name, strerror(errno));
628 #ifdef USE_PASSIFNAME
629 on = 1;
630 if (setsockopt(sock, SOL_SOCKET, SO_PASSIFNAME, &on,sizeof(on)) < 0)
631 msglog("setsockopt(%s,SO_PASSIFNAME): %s",
632 name, strerror(errno));
633 #endif
634
635 if (rbuf >= MIN_SOCKBUF) {
636 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
637 &rbuf, sizeof(rbuf)) < 0)
638 msglog("setsockopt(%s,SO_RCVBUF=%d): %s",
639 name, rbuf, strerror(errno));
640 } else {
641 for (rbuf = 60*1024; ; rbuf -= 4096) {
642 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
643 &rbuf, sizeof(rbuf)) == 0) {
644 trace_act("RCVBUF=%d", rbuf);
645 break;
646 }
647 if (rbuf < MIN_SOCKBUF) {
648 msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
649 name, rbuf, strerror(errno));
650 break;
651 }
652 }
653 }
654 }
655
656
657 /* get a rip socket
658 */
659 static int /* <0 or file descriptor */
660 get_rip_sock(naddr addr,
661 int serious) /* 1=failure to bind is serious */
662 {
663 struct sockaddr_in rsin;
664 unsigned char ttl;
665 int s;
666
667
668 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
669 BADERR(1,"rip_sock = socket()");
670
671 memset(&rsin, 0, sizeof(rsin));
672 #ifdef _HAVE_SIN_LEN
673 rsin.sin_len = sizeof(rsin);
674 #endif
675 rsin.sin_family = AF_INET;
676 rsin.sin_port = htons(RIP_PORT);
677 rsin.sin_addr.s_addr = addr;
678 if (bind(s, (struct sockaddr *)&rsin, sizeof(rsin)) < 0) {
679 if (serious)
680 BADERR(errno != EADDRINUSE, "bind(rip_sock)");
681 return -1;
682 }
683 fix_sock(s,"rip_sock");
684
685 ttl = 1;
686 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
687 &ttl, sizeof(ttl)) < 0)
688 DBGERR(1,"rip_sock setsockopt(IP_MULTICAST_TTL)");
689
690 return s;
691 }
692
693
694 /* turn off main RIP socket */
695 void
696 rip_off(void)
697 {
698 struct interface *ifp;
699 naddr addr;
700
701
702 if (rip_sock >= 0 && !mhome) {
703 trace_act("turn off RIP");
704
705 (void)close(rip_sock);
706 rip_sock = -1;
707
708 /* get non-broadcast sockets to listen to queries.
709 */
710 for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
711 if (ifp->int_state & IS_REMOTE)
712 continue;
713 if (ifp->int_rip_sock < 0) {
714 addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
715 ? ifp->int_dstaddr
716 : ifp->int_addr);
717 ifp->int_rip_sock = get_rip_sock(addr, 0);
718 }
719 }
720
721 fix_select();
722
723 age(0);
724 }
725 }
726
727
728 /* turn on RIP multicast input via an interface
729 */
730 static void
731 rip_mcast_on(struct interface *ifp)
732 {
733 struct ip_mreq m;
734
735 if (!IS_RIP_IN_OFF(ifp->int_state)
736 && (ifp->int_if_flags & IFF_MULTICAST)
737 #ifdef MCAST_PPP_BUG
738 && !(ifp->int_if_flags & IFF_POINTOPOINT)
739 #endif
740 && !(ifp->int_state & IS_ALIAS)) {
741 m.imr_multiaddr.s_addr = htonl(INADDR_RIP_GROUP);
742 #ifdef MCAST_IFINDEX
743 m.imr_interface.s_addr = htonl(ifp->int_index);
744 #else
745 m.imr_interface.s_addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
746 ? ifp->int_dstaddr
747 : ifp->int_addr);
748 #endif
749 if (setsockopt(rip_sock,IPPROTO_IP, IP_ADD_MEMBERSHIP,
750 &m, sizeof(m)) < 0)
751 LOGERR("setsockopt(IP_ADD_MEMBERSHIP RIP)");
752 }
753 }
754
755
756 /* Prepare socket used for RIP.
757 */
758 void
759 rip_on(struct interface *ifp)
760 {
761 /* If the main RIP socket is already alive, only start receiving
762 * multicasts for this interface.
763 */
764 if (rip_sock >= 0) {
765 if (ifp != 0)
766 rip_mcast_on(ifp);
767 return;
768 }
769
770 /* If the main RIP socket is off and it makes sense to turn it on,
771 * then turn it on for all of the interfaces.
772 * It makes sense if either router discovery is off, or if
773 * router discover is on and at most one interface is doing RIP.
774 */
775 if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
776 trace_act("turn on RIP");
777
778 /* Close all of the query sockets so that we can open
779 * the main socket. SO_REUSEPORT is not a solution,
780 * since that would let two daemons bind to the broadcast
781 * socket.
782 */
783 for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
784 if (ifp->int_rip_sock >= 0) {
785 (void)close(ifp->int_rip_sock);
786 ifp->int_rip_sock = -1;
787 }
788 }
789
790 rip_sock = get_rip_sock(INADDR_ANY, 1);
791 rip_sock_mcast = 0;
792
793 /* Do not advertise anything until we have heard something
794 */
795 if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
796 next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
797
798 for (ifp = ifnet; ifp != 0; ifp = ifp->int_next) {
799 ifp->int_query_time = NEVER;
800 rip_mcast_on(ifp);
801 }
802 ifinit_timer.tv_sec = now.tv_sec;
803
804 } else if (ifp != 0
805 && !(ifp->int_state & IS_REMOTE)
806 && ifp->int_rip_sock < 0) {
807 /* RIP is off, so ensure there are sockets on which
808 * to listen for queries.
809 */
810 ifp->int_rip_sock = get_rip_sock(ifp->int_addr, 0);
811 }
812
813 fix_select();
814 }
815
816
817 /* die if malloc(3) fails
818 */
819 void *
820 rtmalloc(size_t size,
821 const char *msg)
822 {
823 void *p = malloc(size);
824 if (p == 0)
825 logbad(1,"malloc(%lu) failed in %s", (u_long)size, msg);
826 return p;
827 }
828
829
830 /* get a random instant in an interval
831 */
832 void
833 intvl_random(struct timeval *tp, /* put value here */
834 u_long lo, /* value is after this second */
835 u_long hi) /* and before this */
836 {
837 tp->tv_sec = (time_t)(hi == lo
838 ? lo
839 : (lo + arc4random() % ((hi - lo))));
840 tp->tv_usec = arc4random() % 1000000;
841 }
842
843
844 void
845 timevaladd(struct timeval *t1,
846 struct timeval *t2)
847 {
848
849 t1->tv_sec += t2->tv_sec;
850 if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
851 t1->tv_sec++;
852 t1->tv_usec -= 1000000;
853 }
854 }
855
856
857 /* t1 = t2 - t3
858 */
859 static void
860 timevalsub(struct timeval *t1,
861 struct timeval *t2,
862 struct timeval *t3)
863 {
864 t1->tv_sec = t2->tv_sec - t3->tv_sec;
865 if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
866 t1->tv_sec--;
867 t1->tv_usec += 1000000;
868 }
869 }
870
871
872 /* put a message into the system log
873 */
874 void
875 msglog(const char *p, ...)
876 {
877 va_list args;
878
879 trace_flush();
880
881 va_start(args, p);
882 vsyslog(LOG_ERR, p, args);
883 va_end(args);
884
885 if (ftrace != 0) {
886 if (ftrace == stdout)
887 (void)fputs("routed: ", ftrace);
888 va_start(args, p);
889 (void)vfprintf(ftrace, p, args);
890 va_end(args);
891 (void)fputc('\n', ftrace);
892 }
893 }
894
895
896 /* Put a message about a bad system into the system log if
897 * we have not complained about it recently.
898 *
899 * It is desirable to complain about all bad systems, but not too often.
900 * In the worst case, it is not practical to keep track of all bad systems.
901 * For example, there can be many systems with the wrong password.
902 */
903 void
904 msglim(struct msg_limit *lim, naddr addr, const char *p, ...)
905 {
906 va_list args;
907 int i;
908 struct msg_sub *ms1, *ms;
909 const char *p1;
910
911 /* look for the oldest slot in the table
912 * or the slot for the bad router.
913 */
914 ms = ms1 = lim->subs;
915 for (i = MSG_SUBJECT_N; ; i--, ms1++) {
916 if (i == 0) {
917 /* Reuse a slot at most once every 10 minutes.
918 */
919 if (lim->reuse > now.tv_sec) {
920 ms = 0;
921 } else {
922 ms = ms1;
923 lim->reuse = now.tv_sec + 10*60;
924 }
925 break;
926 }
927 if (ms->addr == addr) {
928 /* Repeat a complaint about a given system at
929 * most once an hour.
930 */
931 if (ms->until > now.tv_sec)
932 ms = 0;
933 break;
934 }
935 if (ms->until < ms1->until)
936 ms = ms1;
937 }
938 if (ms != 0) {
939 ms->addr = addr;
940 ms->until = now.tv_sec + 60*60; /* 60 minutes */
941
942 trace_flush();
943 for (p1 = p; *p1 == ' '; p1++)
944 continue;
945 va_start(args, p);
946 vsyslog(LOG_ERR, p1, args);
947 va_end(args);
948 }
949
950 /* always display the message if tracing */
951 if (ftrace != 0) {
952 va_start(args, p);
953 (void)vfprintf(ftrace, p, args);
954 (void)fputc('\n', ftrace);
955 va_end(args);
956 }
957 }
958
959
960 void
961 logbad(int dump, const char *p, ...)
962 {
963 va_list args;
964
965 trace_flush();
966
967 va_start(args, p);
968 vsyslog(LOG_ERR, p, args);
969 va_end(args);
970
971 (void)fputs("routed: ", stderr);
972 va_start(args, p);
973 (void)vfprintf(stderr, p, args);
974 va_end(args);
975 (void)fputs("; giving up\n",stderr);
976 (void)fflush(stderr);
977
978 if (dump)
979 abort();
980 exit(1);
981 }
982