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