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