]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/routed/main.c
dialog: import dialog 1.3-20210117
[FreeBSD/FreeBSD.git] / sbin / routed / main.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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. 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.
18  *
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
29  * SUCH DAMAGE.
30  *
31  * $FreeBSD$
32  */
33
34 #include "defs.h"
35 #include "pathnames.h"
36 #include <signal.h>
37 #include <fcntl.h>
38 #include <sys/file.h>
39
40 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993 "
41             "The Regents of the University of California."
42             "  All rights reserved.");
43 __RCSID("$FreeBSD$");
44
45 pid_t   mypid;
46
47 naddr   myaddr;                         /* system address */
48 static char myname[MAXHOSTNAMELEN+1];
49
50 static int verbose;
51
52 int     supplier;                       /* supply or broadcast updates */
53 int     supplier_set;
54 static int ipforwarding = 1;            /* kernel forwarding on */
55
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 */
63
64 struct timeval epoch;                   /* when started */
65 struct timeval clk;
66 static struct timeval prev_clk;
67 static int usec_fudge;
68 struct timeval now;                     /* current idea of time */
69 time_t  now_stale;
70 time_t  now_expire;
71 time_t  now_garbage;
72
73 static struct timeval next_bcast;       /* next general broadcast */
74 struct timeval no_flash = {             /* inhibit flash update */
75         EPOCH+SUPPLY_INTERVAL, 0
76 };
77
78 static struct timeval flush_kern_timer;
79
80 static fd_set fdbits;
81 static int sock_max;
82 int     rip_sock = -1;                  /* RIP socket */
83 const struct interface *rip_sock_mcast; /* current multicast interface */
84 int     rt_sock;                        /* routing socket */
85 int     rt_sock_seqno;
86
87
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);
92
93 int
94 main(int argc,
95      char *argv[])
96 {
97         int n, mib[4], off;
98         size_t len;
99         char *p, *q;
100         const char *cp;
101         struct timeval wtime, t2;
102         time_t dt;
103         fd_set ibits;
104         naddr p_net, p_mask;
105         struct interface *ifp;
106         struct parm parm;
107         char *tracename = 0;
108
109
110         /* Some shells are badly broken and send SIGHUP to backgrounded
111          * processes.
112          */
113         signal(SIGHUP, SIG_IGN);
114
115         openlog("routed", LOG_PID, LOG_DAEMON);
116         ftrace = stdout;
117
118         gettimeofday(&clk, 0);
119         prev_clk = clk;
120         epoch = clk;
121         epoch.tv_sec -= EPOCH;
122         now.tv_sec = EPOCH;
123         now_stale = EPOCH - STALE_TIME;
124         now_expire = EPOCH - EXPIRE_TIME;
125         now_garbage = EPOCH - GARBAGE_TIME;
126         wtime.tv_sec = 0;
127
128         (void)gethostname(myname, sizeof(myname)-1);
129         (void)gethost(myname, &myaddr);
130
131         while ((n = getopt(argc, argv, "isqdghmAtvT:F:P:")) != -1) {
132                 switch (n) {
133                 case 'i':
134                         insecure++;
135                         break;
136                 case 's':
137                         supplier = 1;
138                         supplier_set = 1;
139                         break;
140
141                 case 'q':
142                         supplier = 0;
143                         supplier_set = 1;
144                         break;
145
146                 case 'd':
147                         background = 0;
148                         break;
149
150                 case 'g':
151                         memset(&parm, 0, sizeof(parm));
152                         parm.parm_d_metric = 1;
153                         cp = check_parms(&parm);
154                         if (cp != 0)
155                                 msglog("bad -g: %s", cp);
156                         else
157                                 default_gateway = 1;
158                         break;
159
160                 case 'h':               /* suppress extra host routes */
161                         ridhosts = 1;
162                         break;
163
164                 case 'm':               /* advertise host route */
165                         mhome = 1;      /* on multi-homed hosts */
166                         break;
167
168                 case 'A':
169                         /* Ignore authentication if we do not care.
170                          * Crazy as it is, that is what RFC 1723 requires.
171                          */
172                         auth_ok = 0;
173                         break;
174
175                 case 't':
176                         new_tracelevel++;
177                         break;
178
179                 case 'T':
180                         tracename = optarg;
181                         break;
182
183                 case 'F':               /* minimal routes for SLIP */
184                         n = FAKE_METRIC;
185                         p = strchr(optarg,',');
186                         if (p && *p != '\0') {
187                                 n = (int)strtoul(p+1, &q, 0);
188                                 if (*q == '\0'
189                                     && n <= HOPCNT_INFINITY-1
190                                     && n >= 1)
191                                         *p = '\0';
192                         }
193                         if (!getnet(optarg, &p_net, &p_mask)) {
194                                 msglog("bad network; \"-F %s\"",
195                                        optarg);
196                                 break;
197                         }
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);
203                         if (cp != 0)
204                                 msglog("bad -F: %s", cp);
205                         break;
206
207                 case 'P':
208                         /* handle arbitrary parameters.
209                          */
210                         q = strdup(optarg);
211                         cp = parse_parms(q, 0);
212                         if (cp != 0)
213                                 msglog("%s in \"-P %s\"", cp, optarg);
214                         free(q);
215                         break;
216
217                 case 'v':
218                         /* display version */
219                         verbose++;
220                         msglog("version 2.31");
221                         break;
222
223                 default:
224                         goto usage;
225                 }
226         }
227         argc -= optind;
228         argv += optind;
229
230         if (tracename == 0 && argc >= 1) {
231                 tracename = *argv++;
232                 argc--;
233         }
234         if (tracename != 0 && tracename[0] == '\0')
235                 goto usage;
236         if (argc != 0) {
237 usage:
238                 logbad(0, "usage: routed [-sqdghmAtv] [-T tracefile]"
239                        " [-F net[,metric]] [-P parms]");
240         }
241         if (geteuid() != 0) {
242                 if (verbose)
243                         exit(0);
244                 logbad(0, "requires UID 0");
245         }
246
247         mib[0] = CTL_NET;
248         mib[1] = PF_INET;
249         mib[2] = IPPROTO_IP;
250         mib[3] = IPCTL_FORWARDING;
251         len = sizeof(ipforwarding);
252         if (sysctl(mib, 4, &ipforwarding, &len, 0, 0) < 0)
253                 LOGERR("sysctl(IPCTL_FORWARDING)");
254
255         if (!ipforwarding) {
256                 if (supplier)
257                         msglog("-s incompatible with ipforwarding=0");
258                 if (default_gateway) {
259                         msglog("-g incompatible with ipforwarding=0");
260                         default_gateway = 0;
261                 }
262                 supplier = 0;
263                 supplier_set = 1;
264         }
265         if (default_gateway) {
266                 if (supplier_set && !supplier) {
267                         msglog("-g and -q incompatible");
268                 } else {
269                         supplier = 1;
270                         supplier_set = 1;
271                 }
272         }
273
274
275         signal(SIGALRM, sigalrm);
276         if (!background)
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);
282
283         /* get into the background */
284         if (background && daemon(0, 1) < 0)
285                 BADERR(0,"daemon()");
286
287         mypid = getpid();
288
289         /* prepare socket connected to the kernel.
290          */
291         rt_sock = socket(AF_ROUTE, SOCK_RAW, 0);
292         if (rt_sock < 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));
296         off = 0;
297         if (setsockopt(rt_sock, SOL_SOCKET,SO_USELOOPBACK,
298                        &off,sizeof(off)) < 0)
299                 LOGERR("setsockopt(SO_USELOOPBACK,0)");
300
301         fix_select();
302
303
304         if (tracename != 0) {
305                 strncpy(inittracename, tracename, sizeof(inittracename)-1);
306                 set_tracefile(inittracename, "%s", -1);
307         } else {
308                 tracelevel_msg("%s", -1);   /* turn on tracing to stdio */
309         }
310
311         bufinit();
312
313         /* initialize radix tree */
314         rtinit();
315
316         /* Pick a random part of the second for our output to minimize
317          * collisions.
318          *
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.
322          */
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;
328
329         /* Collect an initial view of the world by checking the interface
330          * configuration and the kludge file.
331          */
332         gwkludge();
333         ifinit();
334
335         /* Ask for routes */
336         rip_query();
337         rdisc_sol();
338
339         /* Now turn off stdio if not tracing */
340         if (new_tracelevel == 0)
341                 trace_close(background);
342
343         /* Loop forever, listening and broadcasting.
344          */
345         for (;;) {
346                 prev_clk = clk;
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
354                          * BSD kernels.
355                          */
356                         clk.tv_usec += ++usec_fudge;
357
358                 } else {
359                         usec_fudge = 0;
360
361                         timevalsub(&t2, &clk, &prev_clk);
362                         if (t2.tv_sec < 0
363                             || t2.tv_sec > wtime.tv_sec + 5) {
364                                 /* Deal with time changes before other
365                                  * housekeeping to keep everything straight.
366                                  */
367                                 dt = t2.tv_sec;
368                                 if (dt > 0)
369                                         dt -= wtime.tv_sec;
370                                 trace_act("time changed by %d sec", (int)dt);
371                                 epoch.tv_sec += dt;
372                         }
373                 }
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;
378
379                 /* deal with signals that should affect tracing */
380                 set_tracelevel();
381
382                 if (stopint != 0) {
383                         rip_bcast(0);
384                         rdisc_adv();
385                         trace_off("exiting with signal %d", stopint);
386                         exit(stopint | 128);
387                 }
388
389                 /* look for new or dead interfaces */
390                 timevalsub(&wtime, &ifinit_timer, &now);
391                 if (wtime.tv_sec <= 0) {
392                         wtime.tv_sec = 0;
393                         ifinit();
394                         rip_query();
395                         continue;
396                 }
397
398                 /* Check the kernel table occasionally for mysteriously
399                  * evaporated routes
400                  */
401                 timevalsub(&t2, &flush_kern_timer, &now);
402                 if (t2.tv_sec <= 0) {
403                         flush_kern();
404                         flush_kern_timer.tv_sec = (now.tv_sec
405                                                    + CHECK_QUIET_INTERVAL);
406                         continue;
407                 }
408                 if (timercmp(&t2, &wtime, <))
409                         wtime = t2;
410
411                 /* If it is time, then broadcast our routes.
412                  */
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
418                                  */
419                                 age(0);
420
421                                 rip_bcast(0);
422
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.
432                                  */
433                                 n = 1 + (0-t2.tv_sec)/SUPPLY_INTERVAL;
434                                 next_bcast.tv_sec += n*SUPPLY_INTERVAL;
435
436                                 continue;
437                         }
438
439                         if (timercmp(&t2, &wtime, <))
440                                 wtime = t2;
441                 }
442
443                 /* If we need a flash update, either do it now or
444                  * set the delay to end when it is time.
445                  *
446                  * If we are within MIN_WAITTIME seconds of a full update,
447                  * do not bother.
448                  */
449                 if (need_flash
450                     && supplier
451                     && no_flash.tv_sec+MIN_WAITTIME < next_bcast.tv_sec) {
452                         /* accurate to the millisecond */
453                         if (!timercmp(&no_flash, &now, >))
454                                 rip_bcast(1);
455                         timevalsub(&t2, &no_flash, &now);
456                         if (timercmp(&t2, &wtime, <))
457                                 wtime = t2;
458                 }
459
460                 /* trigger the main aging timer.
461                  */
462                 timevalsub(&t2, &age_timer, &now);
463                 if (t2.tv_sec <= 0) {
464                         age(0);
465                         continue;
466                 }
467                 if (timercmp(&t2, &wtime, <))
468                         wtime = t2;
469
470                 /* update the kernel routing table
471                  */
472                 timevalsub(&t2, &need_kern, &now);
473                 if (t2.tv_sec <= 0) {
474                         age(0);
475                         continue;
476                 }
477                 if (timercmp(&t2, &wtime, <))
478                         wtime = t2;
479
480                 /* take care of router discovery,
481                  * but do it in the correct the millisecond
482                  */
483                 if (!timercmp(&rdisc_timer, &now, >)) {
484                         rdisc_age(0);
485                         continue;
486                 }
487                 timevalsub(&t2, &rdisc_timer, &now);
488                 if (timercmp(&t2, &wtime, <))
489                         wtime = t2;
490
491
492                 /* wait for input or a timer to expire.
493                  */
494                 trace_flush();
495                 ibits = fdbits;
496                 n = select(sock_max, &ibits, 0, 0, &wtime);
497                 if (n <= 0) {
498                         if (n < 0 && errno != EINTR && errno != EAGAIN)
499                                 BADERR(1,"select");
500                         continue;
501                 }
502
503                 if (FD_ISSET(rt_sock, &ibits)) {
504                         read_rt();
505                         n--;
506                 }
507                 if (rdisc_sock >= 0 && FD_ISSET(rdisc_sock, &ibits)) {
508                         read_d();
509                         n--;
510                 }
511                 if (rip_sock >= 0 && FD_ISSET(rip_sock, &ibits)) {
512                         read_rip(rip_sock, 0);
513                         n--;
514                 }
515
516                 LIST_FOREACH(ifp, &ifnet, int_list) {
517                         if (n <= 0)
518                                 break;
519                         if (ifp->int_rip_sock >= 0
520                             && FD_ISSET(ifp->int_rip_sock, &ibits)) {
521                                 read_rip(ifp->int_rip_sock, ifp);
522                                 n--;
523                         }
524                 }
525         }
526 }
527
528
529 /* ARGSUSED */
530 static void
531 sigalrm(int s UNUSED)
532 {
533         /* Historically, SIGALRM would cause the daemon to check for
534          * new and broken interfaces.
535          */
536         ifinit_timer.tv_sec = now.tv_sec;
537         trace_act("SIGALRM");
538 }
539
540
541 /* watch for fatal signals */
542 static void
543 sigterm(int sig)
544 {
545         stopint = sig;
546         (void)signal(sig, SIG_DFL);     /* catch it only once */
547 }
548
549
550 void
551 fix_select(void)
552 {
553         struct interface *ifp;
554
555
556         FD_ZERO(&fdbits);
557         sock_max = 0;
558
559         FD_SET(rt_sock, &fdbits);
560         if (sock_max <= rt_sock)
561                 sock_max = rt_sock+1;
562         if (rip_sock >= 0) {
563                 FD_SET(rip_sock, &fdbits);
564                 if (sock_max <= rip_sock)
565                         sock_max = rip_sock+1;
566         }
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;
572                 }
573         }
574         if (rdisc_sock >= 0) {
575                 FD_SET(rdisc_sock, &fdbits);
576                 if (sock_max <= rdisc_sock)
577                         sock_max = rdisc_sock+1;
578         }
579 }
580
581
582 void
583 fix_sock(int sock,
584          const char *name)
585 {
586         int on;
587 #define MIN_SOCKBUF (4*1024)
588         static int rbuf;
589
590         if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1)
591                 logbad(1, "fcntl(%s) O_NONBLOCK: %s",
592                        name, strerror(errno));
593         on = 1;
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
598         on = 1;
599         if (setsockopt(sock, SOL_SOCKET, SO_PASSIFNAME, &on,sizeof(on)) < 0)
600                 msglog("setsockopt(%s,SO_PASSIFNAME): %s",
601                        name, strerror(errno));
602 #endif
603
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));
609         } else {
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);
614                                 break;
615                         }
616                         if (rbuf < MIN_SOCKBUF) {
617                                 msglog("setsockopt(%s,SO_RCVBUF = %d): %s",
618                                        name, rbuf, strerror(errno));
619                                 break;
620                         }
621                 }
622         }
623 }
624
625
626 /* get a rip socket
627  */
628 static int                              /* <0 or file descriptor */
629 get_rip_sock(naddr addr,
630              int serious)               /* 1=failure to bind is serious */
631 {
632         struct sockaddr_in rsin;
633         unsigned char ttl;
634         int s;
635
636
637         if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
638                 BADERR(1,"rip_sock = socket()");
639
640         memset(&rsin, 0, sizeof(rsin));
641 #ifdef _HAVE_SIN_LEN
642         rsin.sin_len = sizeof(rsin);
643 #endif
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) {
648                 if (serious)
649                         BADERR(errno != EADDRINUSE, "bind(rip_sock)");
650                 close(s);
651                 return -1;
652         }
653         fix_sock(s,"rip_sock");
654
655         ttl = 1;
656         if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
657                        &ttl, sizeof(ttl)) < 0)
658                 DBGERR(1,"rip_sock setsockopt(IP_MULTICAST_TTL)");
659
660         return s;
661 }
662
663
664 /* turn off main RIP socket */
665 void
666 rip_off(void)
667 {
668         struct interface *ifp;
669         naddr addr;
670
671
672         if (rip_sock >= 0 && !mhome) {
673                 trace_act("turn off RIP");
674
675                 (void)close(rip_sock);
676                 rip_sock = -1;
677
678                 /* get non-broadcast sockets to listen to queries.
679                  */
680                 LIST_FOREACH(ifp, &ifnet, int_list) {
681                         if (ifp->int_state & IS_REMOTE)
682                                 continue;
683                         if (ifp->int_rip_sock < 0) {
684                                 addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
685                                         ? ifp->int_dstaddr
686                                         : ifp->int_addr);
687                                 ifp->int_rip_sock = get_rip_sock(addr, 0);
688                         }
689                 }
690
691                 fix_select();
692
693                 age(0);
694         }
695 }
696
697
698 /* turn on RIP multicast input via an interface
699  */
700 static void
701 rip_mcast_on(struct interface *ifp)
702 {
703         struct group_req gr;
704         struct sockaddr_in *sin;
705
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;
713 #ifdef _HAVE_SIN_LEN
714                 sin->sin_len = sizeof(struct sockaddr_in);
715 #endif
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)");
720         }
721 }
722
723
724 /* Prepare socket used for RIP.
725  */
726 void
727 rip_on(struct interface *ifp)
728 {
729         /* If the main RIP socket is already alive, only start receiving
730          * multicasts for this interface.
731          */
732         if (rip_sock >= 0) {
733                 if (ifp != NULL)
734                         rip_mcast_on(ifp);
735                 return;
736         }
737
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.
742          */
743         if (rip_interfaces > 0 && (!rdisc_ok || rip_interfaces > 1)) {
744                 trace_act("turn on RIP");
745
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
749                  * socket.
750                  */
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;
755                         }
756                 }
757
758                 rip_sock = get_rip_sock(INADDR_ANY, 1);
759                 rip_sock_mcast = NULL;
760
761                 /* Do not advertise anything until we have heard something
762                  */
763                 if (next_bcast.tv_sec < now.tv_sec+MIN_WAITTIME)
764                         next_bcast.tv_sec = now.tv_sec+MIN_WAITTIME;
765
766                 LIST_FOREACH(ifp, &ifnet, int_list) {
767                         ifp->int_query_time = NEVER;
768                         rip_mcast_on(ifp);
769                 }
770                 ifinit_timer.tv_sec = now.tv_sec;
771
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.
777                  */
778                 ifp->int_rip_sock = get_rip_sock(ifp->int_addr, 0);
779         }
780
781         fix_select();
782 }
783
784
785 /* die if malloc(3) fails
786  */
787 void *
788 rtmalloc(size_t size,
789          const char *msg)
790 {
791         void *p = malloc(size);
792         if (p == NULL)
793                 logbad(1,"malloc(%lu) failed in %s", (u_long)size, msg);
794         return p;
795 }
796
797
798 /* get a random instant in an interval
799  */
800 void
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 */
804 {
805         tp->tv_sec = (time_t)(hi == lo
806                               ? lo
807                               : (lo + arc4random_uniform(1 + hi - lo)));
808         tp->tv_usec = arc4random_uniform(1000000);
809 }
810
811
812 void
813 timevaladd(struct timeval *t1,
814            struct timeval *t2)
815 {
816
817         t1->tv_sec += t2->tv_sec;
818         if ((t1->tv_usec += t2->tv_usec) >= 1000000) {
819                 t1->tv_sec++;
820                 t1->tv_usec -= 1000000;
821         }
822 }
823
824
825 /* t1 = t2 - t3
826  */
827 static void
828 timevalsub(struct timeval *t1,
829            struct timeval *t2,
830            struct timeval *t3)
831 {
832         t1->tv_sec = t2->tv_sec - t3->tv_sec;
833         if ((t1->tv_usec = t2->tv_usec - t3->tv_usec) < 0) {
834                 t1->tv_sec--;
835                 t1->tv_usec += 1000000;
836         }
837 }
838
839
840 /* put a message into the system log
841  */
842 void
843 msglog(const char *p, ...)
844 {
845         va_list args;
846
847         trace_flush();
848
849         va_start(args, p);
850         vsyslog(LOG_ERR, p, args);
851         va_end(args);
852         if (ftrace != NULL) {
853                 if (ftrace == stdout)
854                         (void)fputs("routed: ", ftrace);
855                 va_start(args, p);
856                 (void)vfprintf(ftrace, p, args);
857                 va_end(args);
858                 (void)fputc('\n', ftrace);
859         }
860 }
861
862
863 /* Put a message about a bad system into the system log if
864  * we have not complained about it recently.
865  *
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.
869  */
870 void
871 msglim(struct msg_limit *lim, naddr addr, const char *p, ...)
872 {
873         va_list args;
874         int i;
875         struct msg_sub *ms1, *ms;
876         const char *p1;
877
878         /* look for the oldest slot in the table
879          * or the slot for the bad router.
880          */
881         ms = ms1 = lim->subs;
882         for (i = MSG_SUBJECT_N; ; i--, ms1++) {
883                 if (i == 0) {
884                         /* Reuse a slot at most once every 10 minutes.
885                          */
886                         if (lim->reuse > now.tv_sec) {
887                                 ms = NULL;
888                         } else {
889                                 ms = ms1;
890                                 lim->reuse = now.tv_sec + 10*60;
891                         }
892                         break;
893                 }
894                 if (ms->addr == addr) {
895                         /* Repeat a complaint about a given system at
896                          * most once an hour.
897                          */
898                         if (ms->until > now.tv_sec)
899                                 ms = NULL;
900                         break;
901                 }
902                 if (ms->until < ms1->until)
903                         ms = ms1;
904         }
905         if (ms != NULL) {
906                 ms->addr = addr;
907                 ms->until = now.tv_sec + 60*60; /* 60 minutes */
908
909                 trace_flush();
910                 for (p1 = p; *p1 == ' '; p1++)
911                         continue;
912                 va_start(args, p);
913                 vsyslog(LOG_ERR, p1, args);
914                 va_end(args);
915         }
916
917         /* always display the message if tracing */
918         if (ftrace != NULL) {
919                 va_start(args, p);
920                 (void)vfprintf(ftrace, p, args);
921                 va_end(args);
922                 (void)fputc('\n', ftrace);
923         }
924 }
925
926
927 void
928 logbad(int dump, const char *p, ...)
929 {
930         va_list args;
931
932         trace_flush();
933
934         va_start(args, p);
935         vsyslog(LOG_ERR, p, args);
936         va_end(args);
937         (void)fputs("routed: ", stderr);
938         va_start(args, p);
939         (void)vfprintf(stderr, p, args);
940         va_end(args);
941         (void)fputs("; giving up\n",stderr);
942         (void)fflush(stderr);
943
944         if (dump)
945                 abort();
946         exit(1);
947 }