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