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