1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1983, 1988, 1993
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 * $FreeBSD$
32 */
33
34#include "defs.h"
35
36#ifdef __NetBSD__
37__RCSID("$NetBSD$");
38#elif defined(__FreeBSD__)
39__RCSID("$FreeBSD$");
40#else
41__RCSID("$Revision: 2.27 $");
42#ident "$Revision: 2.27 $"
43#endif
44
45
46u_int update_seqno;
47
48
49/* walk the tree of routes with this for output
50 */
51static struct {
52	struct sockaddr_in to;
53	naddr	to_mask;
54	naddr	to_net;
55	naddr	to_std_mask;
56	naddr	to_std_net;
57	struct interface *ifp;		/* usually output interface */
58	struct auth *a;
59	char	metric;			/* adjust metrics by interface */
60	int	npackets;
61	int	gen_limit;
62	u_int	state;
63#define	    WS_ST_FLASH	    0x001	/* send only changed routes */
64#define	    WS_ST_RIP2_ALL  0x002	/* send full featured RIPv2 */
65#define	    WS_ST_AG	    0x004	/* ok to aggregate subnets */
66#define	    WS_ST_SUPER_AG  0x008	/* ok to aggregate networks */
67#define	    WS_ST_QUERY	    0x010	/* responding to a query */
68#define	    WS_ST_TO_ON_NET 0x020	/* sending onto one of our nets */
69#define	    WS_ST_DEFAULT   0x040	/* faking a default */
70} ws;
71
72/* A buffer for what can be heard by both RIPv1 and RIPv2 listeners */
73struct ws_buf v12buf;
74static union pkt_buf ripv12_buf;
75
76/* Another for only RIPv2 listeners */
77static struct ws_buf v2buf;
78static union pkt_buf rip_v2_buf;
79
80
81
82void
83bufinit(void)
84{
85	ripv12_buf.rip.rip_cmd = RIPCMD_RESPONSE;
86	v12buf.buf = &ripv12_buf.rip;
87	v12buf.base = &v12buf.buf->rip_nets[0];
88
89	rip_v2_buf.rip.rip_cmd = RIPCMD_RESPONSE;
90	rip_v2_buf.rip.rip_vers = RIPv2;
91	v2buf.buf = &rip_v2_buf.rip;
92	v2buf.base = &v2buf.buf->rip_nets[0];
93}
94
95
96/* Send the contents of the global buffer via the non-multicast socket
97 */
98int					/* <0 on failure */
99output(enum output_type type,
100       struct sockaddr_in *dst,		/* send to here */
101       struct interface *ifp,
102       struct rip *buf,
103       int size)			/* this many bytes */
104{
105	struct sockaddr_in osin;
106	int flags;
107	const char *msg;
108	int res;
109	int soc;
110	int serrno;
111
112	assert(ifp != NULL);
113	osin = *dst;
114	if (osin.sin_port == 0)
115		osin.sin_port = htons(RIP_PORT);
116#ifdef _HAVE_SIN_LEN
117	if (osin.sin_len == 0)
118		osin.sin_len = sizeof(osin);
119#endif
120
121	soc = rip_sock;
122	flags = 0;
123
124	switch (type) {
125	case OUT_QUERY:
126		msg = "Answer Query";
127		if (soc < 0)
128			soc = ifp->int_rip_sock;
129		break;
130	case OUT_UNICAST:
131		msg = "Send";
132		if (soc < 0)
133			soc = ifp->int_rip_sock;
134		flags = MSG_DONTROUTE;
135		break;
136	case OUT_BROADCAST:
137		if (ifp->int_if_flags & IFF_POINTOPOINT) {
138			msg = "Send";
139		} else {
140			msg = "Send bcast";
141		}
142		flags = MSG_DONTROUTE;
143		break;
144	case OUT_MULTICAST:
145		if ((ifp->int_if_flags & (IFF_POINTOPOINT|IFF_MULTICAST)) ==
146		    IFF_POINTOPOINT) {
147			msg = "Send pt-to-pt";
148		} else if (ifp->int_state & IS_DUP) {
149			trace_act("abort multicast output via %s"
150				  " with duplicate address",
151				  ifp->int_name);
152			return 0;
153		} else {
154			msg = "Send mcast";
155			if (rip_sock_mcast != ifp) {
156				struct ip_mreqn mreqn;
157
158				memset(&mreqn, 0, sizeof(struct ip_mreqn));
159				mreqn.imr_ifindex = ifp->int_index;
160				if (0 > setsockopt(rip_sock,
161						   IPPROTO_IP,
162						   IP_MULTICAST_IF,
163						   &mreqn,
164						   sizeof(mreqn))) {
165					serrno = errno;
166					LOGERR("setsockopt(rip_sock, "
167					       "IP_MULTICAST_IF)");
168					errno = serrno;
169					ifp = NULL;
170					return -1;
171				}
172				rip_sock_mcast = ifp;
173			}
174			osin.sin_addr.s_addr = htonl(INADDR_RIP_GROUP);
175		}
176		break;
177
178	case NO_OUT_MULTICAST:
179	case NO_OUT_RIPV2:
180	default:
181#ifdef DEBUG
182		abort();
183#endif
184		return -1;
185	}
186
187	trace_rip(msg, "to", &osin, ifp, buf, size);
188
189	res = sendto(soc, buf, size, flags,
190		     (struct sockaddr *)&osin, sizeof(osin));
191	if (res < 0
192	    && (ifp == NULL || !(ifp->int_state & IS_BROKE))) {
193		serrno = errno;
194		msglog("%s sendto(%s%s%s.%d): %s", msg,
195		       ifp != NULL ? ifp->int_name : "",
196		       ifp != NULL ? ", " : "",
197		       inet_ntoa(osin.sin_addr),
198		       ntohs(osin.sin_port),
199		       strerror(errno));
200		errno = serrno;
201	}
202
203	return res;
204}
205
206
207/* Find the first key for a packet to send.
208 * Try for a key that is eligible and has not expired, but settle for
209 * the last key if they have all expired.
210 * If no key is ready yet, give up.
211 */
212struct auth *
213find_auth(struct interface *ifp)
214{
215	struct auth *ap, *res;
216	int i;
217
218
219	if (ifp == NULL)
220		return 0;
221
222	res = NULL;
223	ap = ifp->int_auth;
224	for (i = 0; i < MAX_AUTH_KEYS; i++, ap++) {
225		/* stop looking after the last key */
226		if (ap->type == RIP_AUTH_NONE)
227			break;
228
229		/* ignore keys that are not ready yet */
230		if ((u_long)ap->start > (u_long)clk.tv_sec)
231			continue;
232
233		if ((u_long)ap->end < (u_long)clk.tv_sec) {
234			/* note best expired password as a fall-back */
235			if (res == NULL || (u_long)ap->end > (u_long)res->end)
236				res = ap;
237			continue;
238		}
239
240		/* note key with the best future */
241		if (res == NULL || (u_long)res->end < (u_long)ap->end)
242			res = ap;
243	}
244	return res;
245}
246
247
248void
249clr_ws_buf(struct ws_buf *wb,
250	   struct auth *ap)
251{
252	struct netauth *na;
253
254	wb->lim = wb->base + NETS_LEN;
255	wb->n = wb->base;
256	memset(wb->n, 0, NETS_LEN*sizeof(*wb->n));
257
258	/* (start to) install authentication if appropriate
259	 */
260	if (ap == NULL)
261		return;
262
263	na = (struct netauth*)wb->n;
264	if (ap->type == RIP_AUTH_PW) {
265		na->a_family = RIP_AF_AUTH;
266		na->a_type = RIP_AUTH_PW;
267		memcpy(na->au.au_pw, ap->key, sizeof(na->au.au_pw));
268		wb->n++;
269
270	} else if (ap->type ==  RIP_AUTH_MD5) {
271		na->a_family = RIP_AF_AUTH;
272		na->a_type = RIP_AUTH_MD5;
273		na->au.a_md5.md5_keyid = ap->keyid;
274		na->au.a_md5.md5_auth_len = RIP_AUTH_MD5_KEY_LEN;
275		na->au.a_md5.md5_seqno = htonl(clk.tv_sec);
276		wb->n++;
277		wb->lim--;		/* make room for trailer */
278	}
279}
280
281
282void
283end_md5_auth(struct ws_buf *wb,
284	     struct auth *ap)
285{
286	struct netauth *na, *na2;
287	MD5_CTX md5_ctx;
288	int len;
289
290
291	na = (struct netauth*)wb->base;
292	na2 = (struct netauth*)wb->n;
293	len = (char *)na2-(char *)wb->buf;
294	na2->a_family = RIP_AF_AUTH;
295	na2->a_type = htons(1);
296	na->au.a_md5.md5_pkt_len = htons(len);
297	MD5Init(&md5_ctx);
298	MD5Update(&md5_ctx, (u_char *)wb->buf, len + RIP_AUTH_MD5_HASH_XTRA);
299	MD5Update(&md5_ctx, ap->key, RIP_AUTH_MD5_KEY_LEN);
300	MD5Final(na2->au.au_pw, &md5_ctx);
301	wb->n++;
302}
303
304
305/* Send the buffer
306 */
307static void
308supply_write(struct ws_buf *wb)
309{
310	/* Output multicast only if legal.
311	 * If we would multicast and it would be illegal, then discard the
312	 * packet.
313	 */
314	switch (wb->type) {
315	case NO_OUT_MULTICAST:
316		trace_pkt("skip multicast to %s because impossible",
317			  naddr_ntoa(ws.to.sin_addr.s_addr));
318		break;
319	case NO_OUT_RIPV2:
320		break;
321	default:
322		if (ws.a != NULL && ws.a->type == RIP_AUTH_MD5)
323			end_md5_auth(wb,ws.a);
324		if (output(wb->type, &ws.to, ws.ifp, wb->buf,
325			   ((char *)wb->n - (char*)wb->buf)) < 0
326		    && ws.ifp != NULL)
327			if_sick(ws.ifp);
328		ws.npackets++;
329		break;
330	}
331
332	clr_ws_buf(wb,ws.a);
333}
334
335
336/* put an entry into the packet
337 */
338static void
339supply_out(struct ag_info *ag)
340{
341	int i;
342	naddr mask, v1_mask, dst_h, ddst_h = 0;
343	struct ws_buf *wb;
344
345
346	/* Skip this route if doing a flash update and it and the routes
347	 * it aggregates have not changed recently.
348	 */
349	if (ag->ag_seqno < update_seqno
350	    && (ws.state & WS_ST_FLASH))
351		return;
352
353	dst_h = ag->ag_dst_h;
354	mask = ag->ag_mask;
355	v1_mask = ripv1_mask_host(htonl(dst_h),
356				  (ws.state & WS_ST_TO_ON_NET) ? ws.ifp : 0);
357	i = 0;
358
359	/* If we are sending RIPv2 packets that cannot (or must not) be
360	 * heard by RIPv1 listeners, do not worry about sub- or supernets.
361	 * Subnets (from other networks) can only be sent via multicast.
362	 * A pair of subnet routes might have been promoted so that they
363	 * are legal to send by RIPv1.
364	 * If RIPv1 is off, use the multicast buffer.
365	 */
366	if ((ws.state & WS_ST_RIP2_ALL)
367	    || ((ag->ag_state & AGS_RIPV2) && v1_mask != mask)) {
368		/* use the RIPv2-only buffer */
369		wb = &v2buf;
370
371	} else {
372		/* use the RIPv1-or-RIPv2 buffer */
373		wb = &v12buf;
374
375		/* Convert supernet route into corresponding set of network
376		 * routes for RIPv1, but leave non-contiguous netmasks
377		 * to ag_check().
378		 */
379		if (v1_mask > mask
380		    && mask + (mask & -mask) == 0) {
381			ddst_h = v1_mask & -v1_mask;
382			i = (v1_mask & ~mask)/ddst_h;
383
384			if (i > ws.gen_limit) {
385				/* Punt if we would have to generate an
386				 * unreasonable number of routes.
387				 */
388				if (TRACECONTENTS)
389					trace_misc("sending %s-->%s as 1"
390						   " instead of %d routes",
391						   addrname(htonl(dst_h), mask,
392							1),
393						   naddr_ntoa(ws.to.sin_addr
394							.s_addr),
395						   i+1);
396				i = 0;
397
398			} else {
399				mask = v1_mask;
400				ws.gen_limit -= i;
401			}
402		}
403	}
404
405	do {
406		wb->n->n_family = RIP_AF_INET;
407		wb->n->n_dst = htonl(dst_h);
408		/* If the route is from router-discovery or we are
409		 * shutting down, admit only a bad metric.
410		 */
411		wb->n->n_metric = ((stopint || ag->ag_metric < 1)
412				   ? HOPCNT_INFINITY
413				   : ag->ag_metric);
414		wb->n->n_metric = htonl(wb->n->n_metric);
415		/* Any non-zero bits in the supposedly unused RIPv1 fields
416		 * cause the old `routed` to ignore the route.
417		 * That means the mask and so forth cannot be sent
418		 * in the hybrid RIPv1/RIPv2 mode.
419		 */
420		if (ws.state & WS_ST_RIP2_ALL) {
421			if (ag->ag_nhop != 0
422			    && ((ws.state & WS_ST_QUERY)
423				|| (ag->ag_nhop != ws.ifp->int_addr
424				    && on_net(ag->ag_nhop,
425					      ws.ifp->int_net,
426					      ws.ifp->int_mask))))
427				wb->n->n_nhop = ag->ag_nhop;
428			wb->n->n_mask = htonl(mask);
429			wb->n->n_tag = ag->ag_tag;
430		}
431		dst_h += ddst_h;
432
433		if (++wb->n >= wb->lim)
434			supply_write(wb);
435	} while (i-- != 0);
436}
437
438
439/* supply one route from the table
440 */
441/* ARGSUSED */
442static int
443walk_supply(struct radix_node *rn,
444	    struct walkarg *argp UNUSED)
445{
446#define RT ((struct rt_entry *)rn)
447	u_short ags;
448	char metric, pref;
449	naddr dst, nhop;
450	struct rt_spare *rts;
451	int i;
452
453
454	/* Do not advertise external remote interfaces or passive interfaces.
455	 */
456	if ((RT->rt_state & RS_IF)
457	    && RT->rt_ifp != 0
458	    && (RT->rt_ifp->int_state & IS_PASSIVE)
459	    && !(RT->rt_state & RS_MHOME))
460		return 0;
461
462	/* If being quiet about our ability to forward, then
463	 * do not say anything unless responding to a query,
464	 * except about our main interface.
465	 */
466	if (!supplier && !(ws.state & WS_ST_QUERY)
467	    && !(RT->rt_state & RS_MHOME))
468		return 0;
469
470	dst = RT->rt_dst;
471
472	/* do not collide with the fake default route */
473	if (dst == RIP_DEFAULT
474	    && (ws.state & WS_ST_DEFAULT))
475		return 0;
476
477	if (RT->rt_state & RS_NET_SYN) {
478		if (RT->rt_state & RS_NET_INT) {
479			/* Do not send manual synthetic network routes
480			 * into the subnet.
481			 */
482			if (on_net(ws.to.sin_addr.s_addr,
483				   ntohl(dst), RT->rt_mask))
484				return 0;
485
486		} else {
487			/* Do not send automatic synthetic network routes
488			 * if they are not needed because no RIPv1 listeners
489			 * can hear them.
490			 */
491			if (ws.state & WS_ST_RIP2_ALL)
492				return 0;
493
494			/* Do not send automatic synthetic network routes to
495			 * the real subnet.
496			 */
497			if (on_net(ws.to.sin_addr.s_addr,
498				   ntohl(dst), RT->rt_mask))
499				return 0;
500		}
501		nhop = 0;
502
503	} else {
504		/* Advertise the next hop if this is not a route for one
505		 * of our interfaces and the next hop is on the same
506		 * network as the target.
507		 * The final determination is made by supply_out().
508		 */
509		if (!(RT->rt_state & RS_IF)
510		    && RT->rt_gate != myaddr
511		    && RT->rt_gate != loopaddr)
512			nhop = RT->rt_gate;
513		else
514			nhop = 0;
515	}
516
517	metric = RT->rt_metric;
518	ags = 0;
519
520	if (RT->rt_state & RS_MHOME) {
521		/* retain host route of multi-homed servers */
522		;
523
524	} else if (RT_ISHOST(RT)) {
525		/* We should always suppress (into existing network routes)
526		 * the host routes for the local end of our point-to-point
527		 * links.
528		 * If we are suppressing host routes in general, then do so.
529		 * Avoid advertising host routes onto their own network,
530		 * where they should be handled by proxy-ARP.
531		 */
532		if ((RT->rt_state & RS_LOCAL)
533		    || ridhosts
534		    || on_net(dst, ws.to_net, ws.to_mask))
535			ags |= AGS_SUPPRESS;
536
537		/* Aggregate stray host routes into network routes if allowed.
538		 * We cannot aggregate host routes into small network routes
539		 * without confusing RIPv1 listeners into thinking the
540		 * network routes are host routes.
541		 */
542		if ((ws.state & WS_ST_AG) && (ws.state & WS_ST_RIP2_ALL))
543			ags |= AGS_AGGREGATE;
544
545	} else {
546		/* Always suppress network routes into other, existing
547		 * network routes
548		 */
549		ags |= AGS_SUPPRESS;
550
551		/* Generate supernets if allowed.
552		 * If we can be heard by RIPv1 systems, we will
553		 * later convert back to ordinary nets.
554		 * This unifies dealing with received supernets.
555		 */
556		if ((ws.state & WS_ST_AG)
557		    && ((RT->rt_state & RS_SUBNET)
558			|| (ws.state & WS_ST_SUPER_AG)))
559			ags |= AGS_AGGREGATE;
560	}
561
562	/* Do not send RIPv1 advertisements of subnets to other
563	 * networks. If possible, multicast them by RIPv2.
564	 */
565	if ((RT->rt_state & RS_SUBNET)
566	    && !(ws.state & WS_ST_RIP2_ALL)
567	    && !on_net(dst, ws.to_std_net, ws.to_std_mask))
568		ags |= AGS_RIPV2 | AGS_AGGREGATE;
569
570
571	/* Do not send a route back to where it came from, except in
572	 * response to a query.  This is "split-horizon".  That means not
573	 * advertising back to the same network	and so via the same interface.
574	 *
575	 * We want to suppress routes that might have been fragmented
576	 * from this route by a RIPv1 router and sent back to us, and so we
577	 * cannot forget this route here.  Let the split-horizon route
578	 * suppress the fragmented routes and then itself be forgotten.
579	 *
580	 * Include the routes for both ends of point-to-point interfaces
581	 * among those suppressed by split-horizon, since the other side
582	 * should knows them as well as we do.
583	 *
584	 * Notice spare routes with the same metric that we are about to
585	 * advertise, to split the horizon on redundant, inactive paths.
586	 *
587	 * Do not suppress advertisements of interface-related addresses on
588	 * non-point-to-point interfaces.  This ensures that we have something
589	 * to say every 30 seconds to help detect broken Ethernets or
590	 * other interfaces where one packet every 30 seconds costs nothing.
591	 */
592	if (ws.ifp != NULL
593	    && !(ws.state & WS_ST_QUERY)
594	    && (ws.state & WS_ST_TO_ON_NET)
595	    && (!(RT->rt_state & RS_IF)
596		|| ws.ifp->int_if_flags & IFF_POINTOPOINT)) {
597		for (rts = RT->rt_spares, i = NUM_SPARES; i != 0; i--, rts++) {
598			if (rts->rts_metric > metric
599			    || rts->rts_ifp != ws.ifp)
600				continue;
601
602			/* If we do not mark the route with AGS_SPLIT_HZ here,
603			 * it will be poisoned-reverse, or advertised back
604			 * toward its source with an infinite metric.
605			 * If we have recently advertised the route with a
606			 * better metric than we now have, then we should
607			 * poison-reverse the route before suppressing it for
608			 * split-horizon.
609			 *
610			 * In almost all cases, if there is no spare for the
611			 * route then it is either old and dead or a brand
612			 * new route. If it is brand new, there is no need
613			 * for poison-reverse. If it is old and dead, it
614			 * is already poisoned.
615			 */
616			if (RT->rt_poison_time < now_expire
617			    || RT->rt_poison_metric >= metric
618			    || RT->rt_spares[1].rts_gate == 0) {
619				ags |= AGS_SPLIT_HZ;
620				ags &= ~AGS_SUPPRESS;
621			}
622			metric = HOPCNT_INFINITY;
623			break;
624		}
625	}
626
627	/* Keep track of the best metric with which the
628	 * route has been advertised recently.
629	 */
630	if (RT->rt_poison_metric >= metric
631	    || RT->rt_poison_time < now_expire) {
632		RT->rt_poison_time = now.tv_sec;
633		RT->rt_poison_metric = metric;
634	}
635
636	/* Adjust the outgoing metric by the cost of the link.
637	 * Avoid aggregation when a route is counting to infinity.
638	 */
639	pref = RT->rt_poison_metric + ws.metric;
640	metric += ws.metric;
641
642	/* Do not advertise stable routes that will be ignored,
643	 * unless we are answering a query.
644	 * If the route recently was advertised with a metric that
645	 * would have been less than infinity through this interface,
646	 * we need to continue to advertise it in order to poison it.
647	 */
648	if (metric >= HOPCNT_INFINITY) {
649		if (!(ws.state & WS_ST_QUERY)
650		    && (pref >= HOPCNT_INFINITY
651			|| RT->rt_poison_time < now_garbage))
652			return 0;
653
654		metric = HOPCNT_INFINITY;
655	}
656
657	ag_check(dst, RT->rt_mask, 0, nhop, metric, pref,
658		 RT->rt_seqno, RT->rt_tag, ags, supply_out);
659	return 0;
660#undef RT
661}
662
663
664/* Supply dst with the contents of the routing tables.
665 * If this won't fit in one packet, chop it up into several.
666 */
667void
668supply(struct sockaddr_in *dst,
669       struct interface *ifp,		/* output interface */
670       enum output_type type,
671       int flash,			/* 1=flash update */
672       int vers,			/* RIP version */
673       int passwd_ok)			/* OK to include cleartext password */
674{
675	struct rt_entry *rt;
676	int def_metric;
677
678	ws.state = 0;
679	ws.gen_limit = 1024;
680
681	ws.to = *dst;
682	ws.to_std_mask = std_mask(ws.to.sin_addr.s_addr);
683	ws.to_std_net = ntohl(ws.to.sin_addr.s_addr) & ws.to_std_mask;
684
685	if (ifp != NULL) {
686		ws.to_mask = ifp->int_mask;
687		ws.to_net = ifp->int_net;
688		if (on_net(ws.to.sin_addr.s_addr, ws.to_net, ws.to_mask))
689			ws.state |= WS_ST_TO_ON_NET;
690
691	} else {
692		ws.to_mask = ripv1_mask_net(ws.to.sin_addr.s_addr, 0);
693		ws.to_net = ntohl(ws.to.sin_addr.s_addr) & ws.to_mask;
694		rt = rtfind(dst->sin_addr.s_addr);
695		if (rt)
696			ifp = rt->rt_ifp;
697	}
698
699	ws.npackets = 0;
700	if (flash)
701		ws.state |= WS_ST_FLASH;
702
703	if ((ws.ifp = ifp) == NULL) {
704		ws.metric = 1;
705	} else {
706		/* Adjust the advertised metric by the outgoing interface
707		 * metric.
708		 */
709		ws.metric = ifp->int_metric + 1 + ifp->int_adj_outmetric;
710	}
711
712	ripv12_buf.rip.rip_vers = vers;
713
714	switch (type) {
715	case OUT_MULTICAST:
716		if (ifp != NULL && ifp->int_if_flags & IFF_MULTICAST)
717			v2buf.type = OUT_MULTICAST;
718		else
719			v2buf.type = NO_OUT_MULTICAST;
720		v12buf.type = OUT_BROADCAST;
721		break;
722
723	case OUT_QUERY:
724		ws.state |= WS_ST_QUERY;
725		/* FALLTHROUGH */
726	case OUT_BROADCAST:
727	case OUT_UNICAST:
728		v2buf.type = (vers == RIPv2) ? type : NO_OUT_RIPV2;
729		v12buf.type = type;
730		break;
731
732	case NO_OUT_MULTICAST:
733	case NO_OUT_RIPV2:
734		break;			/* no output */
735	}
736
737	if (vers == RIPv2) {
738		/* full RIPv2 only if cannot be heard by RIPv1 listeners */
739		if (type != OUT_BROADCAST)
740			ws.state |= WS_ST_RIP2_ALL;
741		if ((ws.state & WS_ST_QUERY)
742		    || !(ws.state & WS_ST_TO_ON_NET)) {
743			ws.state |= (WS_ST_AG | WS_ST_SUPER_AG);
744		} else if (ifp == NULL || !(ifp->int_state & IS_NO_AG)) {
745			ws.state |= WS_ST_AG;
746			if (type != OUT_BROADCAST
747			    && (ifp == NULL
748				|| !(ifp->int_state & IS_NO_SUPER_AG)))
749				ws.state |= WS_ST_SUPER_AG;
750		}
751	}
752
753	ws.a = (vers == RIPv2) ? find_auth(ifp) : 0;
754	if (!passwd_ok && ws.a != NULL && ws.a->type == RIP_AUTH_PW)
755		ws.a = NULL;
756	clr_ws_buf(&v12buf,ws.a);
757	clr_ws_buf(&v2buf,ws.a);
758
759	/*  Fake a default route if asked and if there is not already
760	 * a better, real default route.
761	 */
762	if (supplier && ifp && (def_metric = ifp->int_d_metric) != 0) {
763		if ((rt = rtget(RIP_DEFAULT, 0)) == NULL
764		    || rt->rt_metric+ws.metric >= def_metric) {
765			ws.state |= WS_ST_DEFAULT;
766			ag_check(0, 0, 0, 0, def_metric, def_metric,
767				 0, 0, 0, supply_out);
768		} else {
769			def_metric = rt->rt_metric+ws.metric;
770		}
771
772		/* If both RIPv2 and the poor-man's router discovery
773		 * kludge are on, arrange to advertise an extra
774		 * default route via RIPv1.
775		 */
776		if ((ws.state & WS_ST_RIP2_ALL)
777		    && (ifp->int_state & IS_PM_RDISC)) {
778			ripv12_buf.rip.rip_vers = RIPv1;
779			v12buf.n->n_family = RIP_AF_INET;
780			v12buf.n->n_dst = htonl(RIP_DEFAULT);
781			v12buf.n->n_metric = htonl(def_metric);
782			v12buf.n++;
783		}
784	}
785
786	(void)rn_walktree(rhead, walk_supply, 0);
787	ag_flush(0,0,supply_out);
788
789	/* Flush the packet buffers, provided they are not empty and
790	 * do not contain only the password.
791	 */
792	if (v12buf.n != v12buf.base
793	    && (v12buf.n > v12buf.base+1
794		|| v12buf.base->n_family != RIP_AF_AUTH))
795		supply_write(&v12buf);
796	if (v2buf.n != v2buf.base
797	    && (v2buf.n > v2buf.base+1
798		|| v2buf.base->n_family != RIP_AF_AUTH))
799		supply_write(&v2buf);
800
801	/* If we sent nothing and this is an answer to a query, send
802	 * an empty buffer.
803	 */
804	if (ws.npackets == 0
805	    && (ws.state & WS_ST_QUERY))
806		supply_write(&v12buf);
807}
808
809
810/* send all of the routing table or just do a flash update
811 */
812void
813rip_bcast(int flash)
814{
815#ifdef _HAVE_SIN_LEN
816	static struct sockaddr_in dst = {sizeof(dst), AF_INET, 0, {0}, {0}};
817#else
818	static struct sockaddr_in dst = {AF_INET};
819#endif
820	struct interface *ifp;
821	enum output_type type;
822	int vers;
823	struct timeval rtime;
824
825
826	need_flash = 0;
827	intvl_random(&rtime, MIN_WAITTIME, MAX_WAITTIME);
828	no_flash = rtime;
829	timevaladd(&no_flash, &now);
830
831	if (rip_sock < 0)
832		return;
833
834	trace_act("send %s and inhibit dynamic updates for %.3f sec",
835		  flash ? "dynamic update" : "all routes",
836		  rtime.tv_sec + ((float)rtime.tv_usec)/1000000.0);
837
838	LIST_FOREACH(ifp, &ifnet, int_list) {
839		/* Skip interfaces not doing RIP.
840		 * Do try broken interfaces to see if they have healed.
841		 */
842		if (IS_RIP_OUT_OFF(ifp->int_state))
843			continue;
844
845		/* skip turned off interfaces */
846		if (!iff_up(ifp->int_if_flags))
847			continue;
848
849		vers = (ifp->int_state & IS_NO_RIPV1_OUT) ? RIPv2 : RIPv1;
850
851		if (ifp->int_if_flags & IFF_BROADCAST) {
852			/* ordinary, hardware interface */
853			dst.sin_addr.s_addr = ifp->int_brdaddr;
854
855			if (vers == RIPv2
856			    && !(ifp->int_state  & IS_NO_RIP_MCAST)) {
857				type = OUT_MULTICAST;
858			} else {
859				type = OUT_BROADCAST;
860			}
861
862		} else if (ifp->int_if_flags & IFF_POINTOPOINT) {
863			/* point-to-point hardware interface */
864			dst.sin_addr.s_addr = ifp->int_dstaddr;
865			if (vers == RIPv2 &&
866			    ifp->int_if_flags & IFF_MULTICAST &&
867			    !(ifp->int_state  & IS_NO_RIP_MCAST)) {
868				type = OUT_MULTICAST;
869			} else {
870				type = OUT_UNICAST;
871			}
872
873		} else if (ifp->int_state & IS_REMOTE) {
874			/* remote interface */
875			dst.sin_addr.s_addr = ifp->int_addr;
876			type = OUT_UNICAST;
877
878		} else {
879			/* ATM, HIPPI, etc. */
880			continue;
881		}
882
883		supply(&dst, ifp, type, flash, vers, 1);
884	}
885
886	update_seqno++;			/* all routes are up to date */
887}
888
889
890/* Ask for routes
891 * Do it only once to an interface, and not even after the interface
892 * was broken and recovered.
893 */
894void
895rip_query(void)
896{
897#ifdef _HAVE_SIN_LEN
898	static struct sockaddr_in dst = {sizeof(dst), AF_INET, 0, {0}, {0}};
899#else
900	static struct sockaddr_in dst = {AF_INET};
901#endif
902	struct interface *ifp;
903	struct rip buf;
904	enum output_type type;
905
906
907	if (rip_sock < 0)
908		return;
909
910	memset(&buf, 0, sizeof(buf));
911
912	LIST_FOREACH(ifp, &ifnet, int_list) {
913		/* Skip interfaces those already queried.
914		 * Do not ask via interfaces through which we don't
915		 * accept input.  Do not ask via interfaces that cannot
916		 * send RIP packets.
917		 * Do try broken interfaces to see if they have healed.
918		 */
919		if (IS_RIP_IN_OFF(ifp->int_state)
920		    || ifp->int_query_time != NEVER)
921			continue;
922
923		/* skip turned off interfaces */
924		if (!iff_up(ifp->int_if_flags))
925			continue;
926
927		buf.rip_vers = (ifp->int_state&IS_NO_RIPV1_OUT) ? RIPv2:RIPv1;
928		buf.rip_cmd = RIPCMD_REQUEST;
929		buf.rip_nets[0].n_family = RIP_AF_UNSPEC;
930		buf.rip_nets[0].n_metric = htonl(HOPCNT_INFINITY);
931
932		/* Send a RIPv1 query only if allowed and if we will
933		 * listen to RIPv1 routers.
934		 */
935		if ((ifp->int_state & IS_NO_RIPV1_OUT)
936		    || (ifp->int_state & IS_NO_RIPV1_IN)) {
937			buf.rip_vers = RIPv2;
938		} else {
939			buf.rip_vers = RIPv1;
940		}
941
942		if (ifp->int_if_flags & IFF_BROADCAST) {
943			/* ordinary, hardware interface */
944			dst.sin_addr.s_addr = ifp->int_brdaddr;
945
946			/* Broadcast RIPv1 queries and RIPv2 queries
947			 * when the hardware cannot multicast.
948			 */
949			if (buf.rip_vers == RIPv2
950			    && (ifp->int_if_flags & IFF_MULTICAST)
951			    && !(ifp->int_state  & IS_NO_RIP_MCAST)) {
952				type = OUT_MULTICAST;
953			} else {
954				type = OUT_BROADCAST;
955			}
956
957		} else if (ifp->int_if_flags & IFF_POINTOPOINT) {
958			/* point-to-point hardware interface */
959			dst.sin_addr.s_addr = ifp->int_dstaddr;
960			type = OUT_UNICAST;
961
962		} else if (ifp->int_state & IS_REMOTE) {
963			/* remote interface */
964			dst.sin_addr.s_addr = ifp->int_addr;
965			type = OUT_UNICAST;
966
967		} else {
968			/* ATM, HIPPI, etc. */
969			continue;
970		}
971
972		ifp->int_query_time = now.tv_sec+SUPPLY_INTERVAL;
973		if (output(type, &dst, ifp, &buf, sizeof(buf)) < 0)
974			if_sick(ifp);
975	}
976}
977