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