xref: /freebsd/sbin/routed/rdisc.c (revision 74bf4e164ba5851606a27d4feff27717452583e5)
1 /*
2  * Copyright (c) 1995
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  * 4. 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.
16  *
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.
28  *
29  * $FreeBSD$
30  */
31 
32 #include "defs.h"
33 #include <netinet/in_systm.h>
34 #include <netinet/ip.h>
35 #include <netinet/ip_icmp.h>
36 
37 #ifdef __NetBSD__
38 __RCSID("$NetBSD$");
39 #elif defined(__FreeBSD__)
40 __RCSID("$FreeBSD$");
41 #else
42 __RCSID("$Revision: 2.27 $");
43 #ident "$Revision: 2.27 $"
44 #endif
45 #ident "$FreeBSD$"
46 
47 /* router advertisement ICMP packet */
48 struct icmp_ad {
49 	u_int8_t    icmp_type;		/* type of message */
50 	u_int8_t    icmp_code;		/* type sub code */
51 	u_int16_t   icmp_cksum;		/* ones complement cksum of struct */
52 	u_int8_t    icmp_ad_num;	/* # of following router addresses */
53 	u_int8_t    icmp_ad_asize;	/* 2--words in each advertisement */
54 	u_int16_t   icmp_ad_life;	/* seconds of validity */
55 	struct icmp_ad_info {
56 	    n_long  icmp_ad_addr;
57 	    n_long  icmp_ad_pref;
58 	} icmp_ad_info[1];
59 };
60 
61 /* router solicitation ICMP packet */
62 struct icmp_so {
63 	u_int8_t    icmp_type;		/* type of message */
64 	u_int8_t    icmp_code;		/* type sub code */
65 	u_int16_t   icmp_cksum;		/* ones complement cksum of struct */
66 	n_long	    icmp_so_rsvd;
67 };
68 
69 union ad_u {
70 	struct icmp icmp;
71 	struct icmp_ad ad;
72 	struct icmp_so so;
73 };
74 
75 
76 int	rdisc_sock = -1;		/* router-discovery raw socket */
77 struct interface *rdisc_sock_mcast;	/* current multicast interface */
78 
79 struct timeval rdisc_timer;
80 int rdisc_ok;				/* using solicited route */
81 
82 
83 #define MAX_ADS 16			/* at least one per interface */
84 struct dr {				/* accumulated advertisements */
85     struct interface *dr_ifp;
86     naddr   dr_gate;			/* gateway */
87     time_t  dr_ts;			/* when received */
88     time_t  dr_life;			/* lifetime in host byte order */
89     n_long  dr_recv_pref;		/* received but biased preference */
90     n_long  dr_pref;			/* preference adjusted by metric */
91 } *cur_drp, drs[MAX_ADS];
92 
93 /* convert between signed, balanced around zero,
94  * and unsigned zero-based preferences */
95 #define SIGN_PREF(p) ((p) ^ MIN_PreferenceLevel)
96 #define UNSIGN_PREF(p) SIGN_PREF(p)
97 /* adjust unsigned preference by interface metric,
98  * without driving it to infinity */
99 #define PREF(p, ifp) ((int)(p) <= ((ifp)->int_metric+(ifp)->int_adj_outmetric)\
100 		      ? ((p) != 0 ? 1 : 0)				    \
101 		      : (p) - ((ifp)->int_metric+(ifp)->int_adj_outmetric))
102 
103 static void rdisc_sort(void);
104 
105 
106 /* dump an ICMP Router Discovery Advertisement Message
107  */
108 static void
109 trace_rdisc(const char	*act,
110 	    naddr	from,
111 	    naddr	to,
112 	    struct interface *ifp,
113 	    union ad_u	*p,
114 	    u_int	len)
115 {
116 	int i;
117 	n_long *wp, *lim;
118 
119 
120 	if (!TRACEPACKETS || ftrace == 0)
121 		return;
122 
123 	lastlog();
124 
125 	if (p->icmp.icmp_type == ICMP_ROUTERADVERT) {
126 		(void)fprintf(ftrace, "%s Router Ad"
127 			      " from %s to %s via %s life=%d\n",
128 			      act, naddr_ntoa(from), naddr_ntoa(to),
129 			      ifp ? ifp->int_name : "?",
130 			      ntohs(p->ad.icmp_ad_life));
131 		if (!TRACECONTENTS)
132 			return;
133 
134 		wp = &p->ad.icmp_ad_info[0].icmp_ad_addr;
135 		lim = &wp[(len - sizeof(p->ad)) / sizeof(*wp)];
136 		for (i = 0; i < p->ad.icmp_ad_num && wp <= lim; i++) {
137 			(void)fprintf(ftrace, "\t%s preference=%d",
138 				      naddr_ntoa(wp[0]), (int)ntohl(wp[1]));
139 			wp += p->ad.icmp_ad_asize;
140 		}
141 		(void)fputc('\n',ftrace);
142 
143 	} else {
144 		trace_act("%s Router Solic. from %s to %s via %s value=%#x",
145 			  act, naddr_ntoa(from), naddr_ntoa(to),
146 			  ifp ? ifp->int_name : "?",
147 			  (int)ntohl(p->so.icmp_so_rsvd));
148 	}
149 }
150 
151 /* prepare Router Discovery socket.
152  */
153 static void
154 get_rdisc_sock(void)
155 {
156 	if (rdisc_sock < 0) {
157 		rdisc_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
158 		if (rdisc_sock < 0)
159 			BADERR(1,"rdisc_sock = socket()");
160 		fix_sock(rdisc_sock,"rdisc_sock");
161 		fix_select();
162 	}
163 }
164 
165 
166 /* Pick multicast group for router-discovery socket
167  */
168 void
169 set_rdisc_mg(struct interface *ifp,
170 	     int on)			/* 0=turn it off */
171 {
172 	struct ip_mreq m;
173 
174 	if (rdisc_sock < 0) {
175 		/* Create the raw socket so that we can hear at least
176 		 * broadcast router discovery packets.
177 		 */
178 		if ((ifp->int_state & IS_NO_RDISC) == IS_NO_RDISC
179 		    || !on)
180 			return;
181 		get_rdisc_sock();
182 	}
183 
184 	if (!(ifp->int_if_flags & IFF_MULTICAST)) {
185 		ifp->int_state &= ~(IS_ALL_HOSTS | IS_ALL_ROUTERS);
186 		return;
187 	}
188 
189 #ifdef MCAST_PPP_BUG
190 	if (ifp->int_if_flags & IFF_POINTOPOINT)
191 		return;
192 #endif
193 	memset(&m, 0, sizeof(m));
194 #ifdef MCAST_IFINDEX
195 	m.imr_interface.s_addr = htonl(ifp->int_index);
196 #else
197 	m.imr_interface.s_addr = ((ifp->int_if_flags & IFF_POINTOPOINT)
198 				  ? ifp->int_dstaddr
199 				  : ifp->int_addr);
200 #endif
201 	if (supplier
202 	    || (ifp->int_state & IS_NO_ADV_IN)
203 	    || !on) {
204 		/* stop listening to advertisements
205 		 */
206 		if (ifp->int_state & IS_ALL_HOSTS) {
207 			m.imr_multiaddr.s_addr = htonl(INADDR_ALLHOSTS_GROUP);
208 			if (setsockopt(rdisc_sock, IPPROTO_IP,
209 				       IP_DROP_MEMBERSHIP,
210 				       &m, sizeof(m)) < 0)
211 				LOGERR("IP_DROP_MEMBERSHIP ALLHOSTS");
212 			ifp->int_state &= ~IS_ALL_HOSTS;
213 		}
214 
215 	} else if (!(ifp->int_state & IS_ALL_HOSTS)) {
216 		/* start listening to advertisements
217 		 */
218 		m.imr_multiaddr.s_addr = htonl(INADDR_ALLHOSTS_GROUP);
219 		if (setsockopt(rdisc_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
220 			       &m, sizeof(m)) < 0) {
221 			LOGERR("IP_ADD_MEMBERSHIP ALLHOSTS");
222 		} else {
223 			ifp->int_state |= IS_ALL_HOSTS;
224 		}
225 	}
226 
227 	if (!supplier
228 	    || (ifp->int_state & IS_NO_ADV_OUT)
229 	    || !on) {
230 		/* stop listening to solicitations
231 		 */
232 		if (ifp->int_state & IS_ALL_ROUTERS) {
233 			m.imr_multiaddr.s_addr=htonl(INADDR_ALLROUTERS_GROUP);
234 			if (setsockopt(rdisc_sock, IPPROTO_IP,
235 				       IP_DROP_MEMBERSHIP,
236 				       &m, sizeof(m)) < 0)
237 				LOGERR("IP_DROP_MEMBERSHIP ALLROUTERS");
238 			ifp->int_state &= ~IS_ALL_ROUTERS;
239 		}
240 
241 	} else if (!(ifp->int_state & IS_ALL_ROUTERS)) {
242 		/* start hearing solicitations
243 		 */
244 		m.imr_multiaddr.s_addr=htonl(INADDR_ALLROUTERS_GROUP);
245 		if (setsockopt(rdisc_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
246 			       &m, sizeof(m)) < 0) {
247 			LOGERR("IP_ADD_MEMBERSHIP ALLROUTERS");
248 		} else {
249 			ifp->int_state |= IS_ALL_ROUTERS;
250 		}
251 	}
252 }
253 
254 
255 /* start supplying routes
256  */
257 void
258 set_supplier(void)
259 {
260 	struct interface *ifp;
261 	struct dr *drp;
262 
263 	if (supplier_set)
264 		return;
265 
266 	trace_act("start supplying routes");
267 
268 	/* Forget discovered routes.
269 	 */
270 	for (drp = drs; drp < &drs[MAX_ADS]; drp++) {
271 		drp->dr_recv_pref = 0;
272 		drp->dr_life = 0;
273 	}
274 	rdisc_age(0);
275 
276 	supplier_set = 1;
277 	supplier = 1;
278 
279 	/* Do not start advertising until we have heard some RIP routes */
280 	LIM_SEC(rdisc_timer, now.tv_sec+MIN_WAITTIME);
281 
282 	/* Switch router discovery multicast groups from soliciting
283 	 * to advertising.
284 	 */
285 	for (ifp = ifnet; ifp; ifp = ifp->int_next) {
286 		if (ifp->int_state & IS_BROKE)
287 			continue;
288 		ifp->int_rdisc_cnt = 0;
289 		ifp->int_rdisc_timer.tv_usec = rdisc_timer.tv_usec;
290 		ifp->int_rdisc_timer.tv_sec = now.tv_sec+MIN_WAITTIME;
291 		set_rdisc_mg(ifp, 1);
292 	}
293 
294 	/* get rid of any redirects */
295 	del_redirects(0,0);
296 }
297 
298 
299 /* age discovered routes and find the best one
300  */
301 void
302 rdisc_age(naddr bad_gate)
303 {
304 	time_t sec;
305 	struct dr *drp;
306 
307 
308 	/* If only advertising, then do only that. */
309 	if (supplier) {
310 		/* If switching from client to server, get rid of old
311 		 * default routes.
312 		 */
313 		if (cur_drp != 0)
314 			rdisc_sort();
315 		rdisc_adv();
316 		return;
317 	}
318 
319 	/* If we are being told about a bad router,
320 	 * then age the discovered default route, and if there is
321 	 * no alternative, solicit a replacement.
322 	 */
323 	if (bad_gate != 0) {
324 		/* Look for the bad discovered default route.
325 		 * Age it and note its interface.
326 		 */
327 		for (drp = drs; drp < &drs[MAX_ADS]; drp++) {
328 			if (drp->dr_ts == 0)
329 				continue;
330 
331 			/* When we find the bad router, then age the route
332 			 * to at most SUPPLY_INTERVAL.
333 			 * This is contrary to RFC 1256, but defends against
334 			 * black holes.
335 			 */
336 			if (drp->dr_gate == bad_gate) {
337 				sec = (now.tv_sec - drp->dr_life
338 				       + SUPPLY_INTERVAL);
339 				if (drp->dr_ts > sec) {
340 					trace_act("age 0.0.0.0 --> %s via %s",
341 						  naddr_ntoa(drp->dr_gate),
342 						  drp->dr_ifp->int_name);
343 					drp->dr_ts = sec;
344 				}
345 				break;
346 			}
347 		}
348 	}
349 
350 	rdisc_sol();
351 	rdisc_sort();
352 
353 	/* Delete old redirected routes to keep the kernel table small,
354 	 * and to prevent black holes.  Check that the kernel table
355 	 * matches the daemon table (i.e. has the default route).
356 	 * But only if RIP is not running and we are not dealing with
357 	 * a bad gateway, since otherwise age() will be called.
358 	 */
359 	if (rip_sock < 0 && bad_gate == 0)
360 		age(0);
361 }
362 
363 
364 /* Zap all routes discovered via an interface that has gone bad
365  *	This should only be called when !(ifp->int_state & IS_ALIAS)
366  */
367 void
368 if_bad_rdisc(struct interface *ifp)
369 {
370 	struct dr *drp;
371 
372 	for (drp = drs; drp < &drs[MAX_ADS]; drp++) {
373 		if (drp->dr_ifp != ifp)
374 			continue;
375 		drp->dr_recv_pref = 0;
376 		drp->dr_ts = 0;
377 		drp->dr_life = 0;
378 	}
379 
380 	/* make a note to re-solicit, turn RIP on or off, etc. */
381 	rdisc_timer.tv_sec = 0;
382 }
383 
384 
385 /* mark an interface ok for router discovering.
386  */
387 void
388 if_ok_rdisc(struct interface *ifp)
389 {
390 	set_rdisc_mg(ifp, 1);
391 
392 	ifp->int_rdisc_cnt = 0;
393 	ifp->int_rdisc_timer.tv_sec = now.tv_sec + (supplier
394 						    ? MIN_WAITTIME
395 						    : MAX_SOLICITATION_DELAY);
396 	if (timercmp(&rdisc_timer, &ifp->int_rdisc_timer, >))
397 		rdisc_timer = ifp->int_rdisc_timer;
398 }
399 
400 
401 /* get rid of a dead discovered router
402  */
403 static void
404 del_rdisc(struct dr *drp)
405 {
406 	struct interface *ifp;
407 	naddr gate;
408 	int i;
409 
410 
411 	del_redirects(gate = drp->dr_gate, 0);
412 	drp->dr_ts = 0;
413 	drp->dr_life = 0;
414 
415 
416 	/* Count the other discovered routes on the interface.
417 	 */
418 	i = 0;
419 	ifp = drp->dr_ifp;
420 	for (drp = drs; drp < &drs[MAX_ADS]; drp++) {
421 		if (drp->dr_ts != 0
422 		    && drp->dr_ifp == ifp)
423 			i++;
424 	}
425 
426 	/* If that was the last good discovered router on the interface,
427 	 * then solicit a new one.
428 	 * This is contrary to RFC 1256, but defends against black holes.
429 	 */
430 	if (i != 0) {
431 		trace_act("discovered router %s via %s"
432 			  " is bad--have %d remaining",
433 			  naddr_ntoa(gate), ifp->int_name, i);
434 	} else if (ifp->int_rdisc_cnt >= MAX_SOLICITATIONS) {
435 		trace_act("last discovered router %s via %s"
436 			  " is bad--re-solicit",
437 			  naddr_ntoa(gate), ifp->int_name);
438 		ifp->int_rdisc_cnt = 0;
439 		ifp->int_rdisc_timer.tv_sec = 0;
440 		rdisc_sol();
441 	} else {
442 		trace_act("last discovered router %s via %s"
443 			  " is bad--wait to solicit",
444 			  naddr_ntoa(gate), ifp->int_name);
445 	}
446 }
447 
448 
449 /* Find the best discovered route,
450  * and discard stale routers.
451  */
452 static void
453 rdisc_sort(void)
454 {
455 	struct dr *drp, *new_drp;
456 	struct rt_entry *rt;
457 	struct rt_spare new;
458 	struct interface *ifp;
459 	u_int new_st = 0;
460 	n_long new_pref = 0;
461 
462 
463 	/* Find the best discovered route.
464 	 */
465 	new_drp = 0;
466 	for (drp = drs; drp < &drs[MAX_ADS]; drp++) {
467 		if (drp->dr_ts == 0)
468 			continue;
469 		ifp = drp->dr_ifp;
470 
471 		/* Get rid of expired discovered routers.
472 		 */
473 		if (drp->dr_ts + drp->dr_life <= now.tv_sec) {
474 			del_rdisc(drp);
475 			continue;
476 		}
477 
478 		LIM_SEC(rdisc_timer, drp->dr_ts+drp->dr_life+1);
479 
480 		/* Update preference with possibly changed interface
481 		 * metric.
482 		 */
483 		drp->dr_pref = PREF(drp->dr_recv_pref, ifp);
484 
485 		/* Prefer the current route to prevent thrashing.
486 		 * Prefer shorter lifetimes to speed the detection of
487 		 * bad routers.
488 		 * Avoid sick interfaces.
489 		 */
490 		if (new_drp == 0
491 		    || (!((new_st ^ drp->dr_ifp->int_state) & IS_SICK)
492 			&& (new_pref < drp->dr_pref
493 			    || (new_pref == drp->dr_pref
494 				&& (drp == cur_drp
495 				    || (new_drp != cur_drp
496 					&& new_drp->dr_life > drp->dr_life)))))
497 		    || ((new_st & IS_SICK)
498 			&& !(drp->dr_ifp->int_state & IS_SICK))) {
499 			    new_drp = drp;
500 			    new_st = drp->dr_ifp->int_state;
501 			    new_pref = drp->dr_pref;
502 		}
503 	}
504 
505 	/* switch to a better default route
506 	 */
507 	if (new_drp != cur_drp) {
508 		rt = rtget(RIP_DEFAULT, 0);
509 
510 		/* Stop using discovered routes if they are all bad
511 		 */
512 		if (new_drp == 0) {
513 			trace_act("turn off Router Discovery client");
514 			rdisc_ok = 0;
515 
516 			if (rt != 0
517 			    && (rt->rt_state & RS_RDISC)) {
518 				new = rt->rt_spares[0];
519 				new.rts_metric = HOPCNT_INFINITY;
520 				new.rts_time = now.tv_sec - GARBAGE_TIME;
521 				rtchange(rt, rt->rt_state & ~RS_RDISC,
522 					 &new, 0);
523 				rtswitch(rt, 0);
524 			}
525 
526 		} else {
527 			if (cur_drp == 0) {
528 				trace_act("turn on Router Discovery client"
529 					  " using %s via %s",
530 					  naddr_ntoa(new_drp->dr_gate),
531 					  new_drp->dr_ifp->int_name);
532 				rdisc_ok = 1;
533 
534 			} else {
535 				trace_act("switch Router Discovery from"
536 					  " %s via %s to %s via %s",
537 					  naddr_ntoa(cur_drp->dr_gate),
538 					  cur_drp->dr_ifp->int_name,
539 					  naddr_ntoa(new_drp->dr_gate),
540 					  new_drp->dr_ifp->int_name);
541 			}
542 
543 			memset(&new, 0, sizeof(new));
544 			new.rts_ifp = new_drp->dr_ifp;
545 			new.rts_gate = new_drp->dr_gate;
546 			new.rts_router = new_drp->dr_gate;
547 			new.rts_metric = HOPCNT_INFINITY-1;
548 			new.rts_time = now.tv_sec;
549 			if (rt != 0) {
550 				rtchange(rt, rt->rt_state | RS_RDISC, &new, 0);
551 			} else {
552 				rtadd(RIP_DEFAULT, 0, RS_RDISC, &new);
553 			}
554 		}
555 
556 		cur_drp = new_drp;
557 	}
558 
559 	/* turn RIP on or off */
560 	if (!rdisc_ok || rip_interfaces > 1) {
561 		rip_on(0);
562 	} else {
563 		rip_off();
564 	}
565 }
566 
567 
568 /* handle a single address in an advertisement
569  */
570 static void
571 parse_ad(naddr from,
572 	 naddr gate,
573 	 n_long pref,			/* signed and in network order */
574 	 u_short life,			/* in host byte order */
575 	 struct interface *ifp)
576 {
577 	static struct msg_limit bad_gate;
578 	struct dr *drp, *new_drp;
579 
580 
581 	if (gate == RIP_DEFAULT
582 	    || !check_dst(gate)) {
583 		msglim(&bad_gate, from,"router %s advertising bad gateway %s",
584 		       naddr_ntoa(from),
585 		       naddr_ntoa(gate));
586 		return;
587 	}
588 
589 	/* ignore pointers to ourself and routes via unreachable networks
590 	 */
591 	if (ifwithaddr(gate, 1, 0) != 0) {
592 		trace_pkt("    discard Router Discovery Ad pointing at us");
593 		return;
594 	}
595 	if (!on_net(gate, ifp->int_net, ifp->int_mask)) {
596 		trace_pkt("    discard Router Discovery Ad"
597 			  " toward unreachable net");
598 		return;
599 	}
600 
601 	/* Convert preference to an unsigned value
602 	 * and later bias it by the metric of the interface.
603 	 */
604 	pref = UNSIGN_PREF(ntohl(pref));
605 
606 	if (pref == 0 || life < MinMaxAdvertiseInterval) {
607 		pref = 0;
608 		life = 0;
609 	}
610 
611 	for (new_drp = 0, drp = drs; drp < &drs[MAX_ADS]; drp++) {
612 		/* accept new info for a familiar entry
613 		 */
614 		if (drp->dr_gate == gate) {
615 			new_drp = drp;
616 			break;
617 		}
618 
619 		if (life == 0)
620 			continue;	/* do not worry about dead ads */
621 
622 		if (drp->dr_ts == 0) {
623 			new_drp = drp;	/* use unused entry */
624 
625 		} else if (new_drp == 0) {
626 			/* look for an entry worse than the new one to
627 			 * reuse.
628 			 */
629 			if ((!(ifp->int_state & IS_SICK)
630 			     && (drp->dr_ifp->int_state & IS_SICK))
631 			    || (pref > drp->dr_pref
632 				&& !((ifp->int_state ^ drp->dr_ifp->int_state)
633 				     & IS_SICK)))
634 				new_drp = drp;
635 
636 		} else if (new_drp->dr_ts != 0) {
637 			/* look for the least valuable entry to reuse
638 			 */
639 			if ((!(new_drp->dr_ifp->int_state & IS_SICK)
640 			     && (drp->dr_ifp->int_state & IS_SICK))
641 			    || (new_drp->dr_pref > drp->dr_pref
642 				&& !((new_drp->dr_ifp->int_state
643 				      ^ drp->dr_ifp->int_state)
644 				     & IS_SICK)))
645 				new_drp = drp;
646 		}
647 	}
648 
649 	/* forget it if all of the current entries are better */
650 	if (new_drp == 0)
651 		return;
652 
653 	new_drp->dr_ifp = ifp;
654 	new_drp->dr_gate = gate;
655 	new_drp->dr_ts = now.tv_sec;
656 	new_drp->dr_life = life;
657 	new_drp->dr_recv_pref = pref;
658 	/* bias functional preference by metric of the interface */
659 	new_drp->dr_pref = PREF(pref,ifp);
660 
661 	/* after hearing a good advertisement, stop asking
662 	 */
663 	if (!(ifp->int_state & IS_SICK))
664 		ifp->int_rdisc_cnt = MAX_SOLICITATIONS;
665 }
666 
667 
668 /* Compute the IP checksum
669  *	This assumes the packet is less than 32K long.
670  */
671 static u_short
672 in_cksum(u_short *p,
673 	 u_int len)
674 {
675 	u_int sum = 0;
676 	int nwords = len >> 1;
677 
678 	while (nwords-- != 0)
679 		sum += *p++;
680 
681 	if (len & 1)
682 		sum += *(u_char *)p;
683 
684 	/* end-around-carry */
685 	sum = (sum >> 16) + (sum & 0xffff);
686 	sum += (sum >> 16);
687 	return (~sum);
688 }
689 
690 
691 /* Send a router discovery advertisement or solicitation ICMP packet.
692  */
693 static void
694 send_rdisc(union ad_u *p,
695 	   int p_size,
696 	   struct interface *ifp,
697 	   naddr dst,			/* 0 or unicast destination */
698 	   int	type)			/* 0=unicast, 1=bcast, 2=mcast */
699 {
700 	struct sockaddr_in rsin;
701 	int flags;
702 	const char *msg;
703 	naddr tgt_mcast;
704 
705 
706 	memset(&rsin, 0, sizeof(rsin));
707 	rsin.sin_addr.s_addr = dst;
708 	rsin.sin_family = AF_INET;
709 #ifdef _HAVE_SIN_LEN
710 	rsin.sin_len = sizeof(rsin);
711 #endif
712 	flags = MSG_DONTROUTE;
713 
714 	switch (type) {
715 	case 0:				/* unicast */
716 	default:
717 		msg = "Send";
718 		break;
719 
720 	case 1:				/* broadcast */
721 		if (ifp->int_if_flags & IFF_POINTOPOINT) {
722 			msg = "Send pt-to-pt";
723 			rsin.sin_addr.s_addr = ifp->int_dstaddr;
724 		} else {
725 			msg = "Send broadcast";
726 			rsin.sin_addr.s_addr = ifp->int_brdaddr;
727 		}
728 		break;
729 
730 	case 2:				/* multicast */
731 		msg = "Send multicast";
732 		if (ifp->int_state & IS_DUP) {
733 			trace_act("abort multicast output via %s"
734 				  " with duplicate address",
735 				  ifp->int_name);
736 			return;
737 		}
738 		if (rdisc_sock_mcast != ifp) {
739 			/* select the right interface. */
740 #ifdef MCAST_IFINDEX
741 			/* specify ifindex */
742 			tgt_mcast = htonl(ifp->int_index);
743 #else
744 #ifdef MCAST_PPP_BUG
745 			/* Do not specify the primary interface explicitly
746 			 * if we have the multicast point-to-point kernel
747 			 * bug, since the kernel will do the wrong thing
748 			 * if the local address of a point-to-point link
749 			 * is the same as the address of an ordinary
750 			 * interface.
751 			 */
752 			if (ifp->int_addr == myaddr) {
753 				tgt_mcast = 0;
754 			} else
755 #endif
756 			tgt_mcast = ifp->int_addr;
757 #endif
758 			if (0 > setsockopt(rdisc_sock,
759 					   IPPROTO_IP, IP_MULTICAST_IF,
760 					   &tgt_mcast, sizeof(tgt_mcast))) {
761 				LOGERR("setsockopt(rdisc_sock,"
762 				       "IP_MULTICAST_IF)");
763 				rdisc_sock_mcast = 0;
764 				return;
765 			}
766 			rdisc_sock_mcast = ifp;
767 		}
768 		flags = 0;
769 		break;
770 	}
771 
772 	if (rdisc_sock < 0)
773 		get_rdisc_sock();
774 
775 	trace_rdisc(msg, ifp->int_addr, rsin.sin_addr.s_addr, ifp,
776 		    p, p_size);
777 
778 	if (0 > sendto(rdisc_sock, p, p_size, flags,
779 		       (struct sockaddr *)&rsin, sizeof(rsin))) {
780 		if (ifp == 0 || !(ifp->int_state & IS_BROKE))
781 			msglog("sendto(%s%s%s): %s",
782 			       ifp != 0 ? ifp->int_name : "",
783 			       ifp != 0 ? ", " : "",
784 			       inet_ntoa(rsin.sin_addr),
785 			       strerror(errno));
786 		if (ifp != 0)
787 			if_sick(ifp);
788 	}
789 }
790 
791 
792 /* Send an advertisement
793  */
794 static void
795 send_adv(struct interface *ifp,
796 	 naddr	dst,			/* 0 or unicast destination */
797 	 int	type)			/* 0=unicast, 1=bcast, 2=mcast */
798 {
799 	union ad_u u;
800 	n_long pref;
801 
802 
803 	memset(&u, 0, sizeof(u.ad));
804 
805 	u.ad.icmp_type = ICMP_ROUTERADVERT;
806 	u.ad.icmp_ad_num = 1;
807 	u.ad.icmp_ad_asize = sizeof(u.ad.icmp_ad_info[0])/4;
808 
809 	u.ad.icmp_ad_life = stopint ? 0 : htons(ifp->int_rdisc_int*3);
810 
811 	/* Convert the configured preference to an unsigned value,
812 	 * bias it by the interface metric, and then send it as a
813 	 * signed, network byte order value.
814 	 */
815 	pref = UNSIGN_PREF(ifp->int_rdisc_pref);
816 	u.ad.icmp_ad_info[0].icmp_ad_pref = htonl(SIGN_PREF(PREF(pref, ifp)));
817 
818 	u.ad.icmp_ad_info[0].icmp_ad_addr = ifp->int_addr;
819 
820 	u.ad.icmp_cksum = in_cksum((u_short*)&u.ad, sizeof(u.ad));
821 
822 	send_rdisc(&u, sizeof(u.ad), ifp, dst, type);
823 }
824 
825 
826 /* Advertise for Router Discovery
827  */
828 void
829 rdisc_adv(void)
830 {
831 	struct interface *ifp;
832 
833 	if (!supplier)
834 		return;
835 
836 	rdisc_timer.tv_sec = now.tv_sec + NEVER;
837 
838 	for (ifp = ifnet; ifp; ifp = ifp->int_next) {
839 		if (0 != (ifp->int_state & (IS_NO_ADV_OUT | IS_BROKE)))
840 			continue;
841 
842 		if (!timercmp(&ifp->int_rdisc_timer, &now, >)
843 		    || stopint) {
844 			send_adv(ifp, htonl(INADDR_ALLHOSTS_GROUP),
845 				 (ifp->int_state&IS_BCAST_RDISC) ? 1 : 2);
846 			ifp->int_rdisc_cnt++;
847 
848 			intvl_random(&ifp->int_rdisc_timer,
849 				     (ifp->int_rdisc_int*3)/4,
850 				     ifp->int_rdisc_int);
851 			if (ifp->int_rdisc_cnt < MAX_INITIAL_ADVERTS
852 			    && (ifp->int_rdisc_timer.tv_sec
853 				> MAX_INITIAL_ADVERT_INTERVAL)) {
854 				ifp->int_rdisc_timer.tv_sec
855 				= MAX_INITIAL_ADVERT_INTERVAL;
856 			}
857 			timevaladd(&ifp->int_rdisc_timer, &now);
858 		}
859 
860 		if (timercmp(&rdisc_timer, &ifp->int_rdisc_timer, >))
861 			rdisc_timer = ifp->int_rdisc_timer;
862 	}
863 }
864 
865 
866 /* Solicit for Router Discovery
867  */
868 void
869 rdisc_sol(void)
870 {
871 	struct interface *ifp;
872 	union ad_u u;
873 
874 
875 	if (supplier)
876 		return;
877 
878 	rdisc_timer.tv_sec = now.tv_sec + NEVER;
879 
880 	for (ifp = ifnet; ifp; ifp = ifp->int_next) {
881 		if (0 != (ifp->int_state & (IS_NO_SOL_OUT | IS_BROKE))
882 		    || ifp->int_rdisc_cnt >= MAX_SOLICITATIONS)
883 			continue;
884 
885 		if (!timercmp(&ifp->int_rdisc_timer, &now, >)) {
886 			memset(&u, 0, sizeof(u.so));
887 			u.so.icmp_type = ICMP_ROUTERSOLICIT;
888 			u.so.icmp_cksum = in_cksum((u_short*)&u.so,
889 						   sizeof(u.so));
890 			send_rdisc(&u, sizeof(u.so), ifp,
891 				   htonl(INADDR_ALLROUTERS_GROUP),
892 				   ((ifp->int_state&IS_BCAST_RDISC) ? 1 : 2));
893 
894 			if (++ifp->int_rdisc_cnt >= MAX_SOLICITATIONS)
895 				continue;
896 
897 			ifp->int_rdisc_timer.tv_sec = SOLICITATION_INTERVAL;
898 			ifp->int_rdisc_timer.tv_usec = 0;
899 			timevaladd(&ifp->int_rdisc_timer, &now);
900 		}
901 
902 		if (timercmp(&rdisc_timer, &ifp->int_rdisc_timer, >))
903 			rdisc_timer = ifp->int_rdisc_timer;
904 	}
905 }
906 
907 
908 /* check the IP header of a possible Router Discovery ICMP packet */
909 static struct interface *		/* 0 if bad */
910 ck_icmp(const char *act,
911 	naddr	from,
912 	struct interface *ifp,
913 	naddr	to,
914 	union ad_u *p,
915 	u_int	len)
916 {
917 	const char *type;
918 
919 
920 	if (p->icmp.icmp_type == ICMP_ROUTERADVERT) {
921 		type = "advertisement";
922 	} else if (p->icmp.icmp_type == ICMP_ROUTERSOLICIT) {
923 		type = "solicitation";
924 	} else {
925 		return 0;
926 	}
927 
928 	if (p->icmp.icmp_code != 0) {
929 		trace_pkt("unrecognized ICMP Router %s code=%d from %s to %s",
930 			  type, p->icmp.icmp_code,
931 			  naddr_ntoa(from), naddr_ntoa(to));
932 		return 0;
933 	}
934 
935 	trace_rdisc(act, from, to, ifp, p, len);
936 
937 	if (ifp == 0)
938 		trace_pkt("unknown interface for router-discovery %s"
939 			  " from %s to %s",
940 			  type, naddr_ntoa(from), naddr_ntoa(to));
941 
942 	return ifp;
943 }
944 
945 
946 /* read packets from the router discovery socket
947  */
948 void
949 read_d(void)
950 {
951 	static struct msg_limit bad_asize, bad_len;
952 #ifdef USE_PASSIFNAME
953 	static struct msg_limit  bad_name;
954 #endif
955 	struct sockaddr_in from;
956 	int n, fromlen, cc, hlen;
957 	struct {
958 #ifdef USE_PASSIFNAME
959 		char	ifname[IFNAMSIZ];
960 #endif
961 		union {
962 			struct ip ip;
963 			u_short s[512/2];
964 			u_char	b[512];
965 		} pkt;
966 	} buf;
967 	union ad_u *p;
968 	n_long *wp;
969 	struct interface *ifp;
970 
971 
972 	for (;;) {
973 		fromlen = sizeof(from);
974 		cc = recvfrom(rdisc_sock, &buf, sizeof(buf), 0,
975 			      (struct sockaddr*)&from,
976 			      &fromlen);
977 		if (cc <= 0) {
978 			if (cc < 0 && errno != EWOULDBLOCK)
979 				LOGERR("recvfrom(rdisc_sock)");
980 			break;
981 		}
982 		if (fromlen != sizeof(struct sockaddr_in))
983 			logbad(1,"impossible recvfrom(rdisc_sock) fromlen=%d",
984 			       fromlen);
985 #ifdef USE_PASSIFNAME
986 		if ((cc -= sizeof(buf.ifname)) < 0)
987 			logbad(0,"missing USE_PASSIFNAME; only %d bytes",
988 			       cc+sizeof(buf.ifname));
989 #endif
990 
991 		hlen = buf.pkt.ip.ip_hl << 2;
992 		if (cc < hlen + ICMP_MINLEN)
993 			continue;
994 		p = (union ad_u *)&buf.pkt.b[hlen];
995 		cc -= hlen;
996 
997 #ifdef USE_PASSIFNAME
998 		ifp = ifwithname(buf.ifname, 0);
999 		if (ifp == 0)
1000 			msglim(&bad_name, from.sin_addr.s_addr,
1001 			       "impossible rdisc if_ name %.*s",
1002 			       IFNAMSIZ, buf.ifname);
1003 #else
1004 		/* If we could tell the interface on which a packet from
1005 		 * address 0 arrived, we could deal with such solicitations.
1006 		 */
1007 		ifp = ((from.sin_addr.s_addr == 0)
1008 		       ? 0 : iflookup(from.sin_addr.s_addr));
1009 #endif
1010 		ifp = ck_icmp("Recv", from.sin_addr.s_addr, ifp,
1011 			      buf.pkt.ip.ip_dst.s_addr, p, cc);
1012 		if (ifp == 0)
1013 			continue;
1014 		if (ifwithaddr(from.sin_addr.s_addr, 0, 0)) {
1015 			trace_pkt("    "
1016 				  "discard our own Router Discovery message");
1017 			continue;
1018 		}
1019 
1020 		switch (p->icmp.icmp_type) {
1021 		case ICMP_ROUTERADVERT:
1022 			if (p->ad.icmp_ad_asize*4
1023 			    < (int)sizeof(p->ad.icmp_ad_info[0])) {
1024 				msglim(&bad_asize, from.sin_addr.s_addr,
1025 				       "intolerable rdisc address size=%d",
1026 				       p->ad.icmp_ad_asize);
1027 				continue;
1028 			}
1029 			if (p->ad.icmp_ad_num == 0) {
1030 				trace_pkt("    empty?");
1031 				continue;
1032 			}
1033 			if (cc != (int)(sizeof(p->ad)
1034 					- sizeof(p->ad.icmp_ad_info)
1035 					+ (p->ad.icmp_ad_num
1036 					   * sizeof(p->ad.icmp_ad_info[0])))) {
1037 				msglim(&bad_len, from.sin_addr.s_addr,
1038 				       "rdisc length %d does not match ad_num"
1039 				       " %d", cc, p->ad.icmp_ad_num);
1040 				continue;
1041 			}
1042 			if (supplier)
1043 				continue;
1044 			if (ifp->int_state & IS_NO_ADV_IN)
1045 				continue;
1046 
1047 			wp = &p->ad.icmp_ad_info[0].icmp_ad_addr;
1048 			for (n = 0; n < p->ad.icmp_ad_num; n++) {
1049 				parse_ad(from.sin_addr.s_addr,
1050 					 wp[0], wp[1],
1051 					 ntohs(p->ad.icmp_ad_life),
1052 					 ifp);
1053 				wp += p->ad.icmp_ad_asize;
1054 			}
1055 			break;
1056 
1057 
1058 		case ICMP_ROUTERSOLICIT:
1059 			if (!supplier)
1060 				continue;
1061 			if (ifp->int_state & IS_NO_ADV_OUT)
1062 				continue;
1063 			if (stopint)
1064 				continue;
1065 
1066 			/* XXX
1067 			 * We should handle messages from address 0.
1068 			 */
1069 
1070 			/* Respond with a point-to-point advertisement */
1071 			send_adv(ifp, from.sin_addr.s_addr, 0);
1072 			break;
1073 		}
1074 	}
1075 
1076 	rdisc_sort();
1077 }
1078