xref: /freebsd/sys/net/route.c (revision dba7640e44c5ec148a84b0d58c6c9a3c9e5147f3)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1991, 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  *	@(#)route.c	8.3.1.1 (Berkeley) 2/23/95
32  * $FreeBSD$
33  */
34 /************************************************************************
35  * Note: In this file a 'fib' is a "forwarding information base"	*
36  * Which is the new name for an in kernel routing (next hop) table.	*
37  ***********************************************************************/
38 
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 #include "opt_mrouting.h"
42 #include "opt_route.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/socket.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <sys/sysproto.h>
52 #include <sys/proc.h>
53 #include <sys/domain.h>
54 #include <sys/eventhandler.h>
55 #include <sys/kernel.h>
56 #include <sys/lock.h>
57 #include <sys/rmlock.h>
58 
59 #include <net/if.h>
60 #include <net/if_var.h>
61 #include <net/if_dl.h>
62 #include <net/route.h>
63 #include <net/route/route_ctl.h>
64 #include <net/route/route_var.h>
65 #include <net/route/nhop.h>
66 #include <net/vnet.h>
67 
68 #include <netinet/in.h>
69 #include <netinet/ip_mroute.h>
70 
71 VNET_PCPUSTAT_DEFINE(struct rtstat, rtstat);
72 
73 VNET_PCPUSTAT_SYSINIT(rtstat);
74 #ifdef VIMAGE
75 VNET_PCPUSTAT_SYSUNINIT(rtstat);
76 #endif
77 
78 EVENTHANDLER_LIST_DEFINE(rt_addrmsg);
79 
80 static int rt_ifdelroute(const struct rtentry *rt, const struct nhop_object *,
81     void *arg);
82 static int rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info,
83     int flags);
84 
85 /*
86  * route initialization must occur before ip6_init2(), which happenas at
87  * SI_ORDER_MIDDLE.
88  */
89 static void
90 route_init(void)
91 {
92 
93 	nhops_init();
94 }
95 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, NULL);
96 
97 struct rib_head *
98 rt_table_init(int offset, int family, u_int fibnum)
99 {
100 	struct rib_head *rh;
101 
102 	rh = malloc(sizeof(struct rib_head), M_RTABLE, M_WAITOK | M_ZERO);
103 
104 	/* TODO: These details should be hidded inside radix.c */
105 	/* Init masks tree */
106 	rn_inithead_internal(&rh->head, rh->rnh_nodes, offset);
107 	rn_inithead_internal(&rh->rmhead.head, rh->rmhead.mask_nodes, 0);
108 	rh->head.rnh_masks = &rh->rmhead;
109 
110 	/* Save metadata associated with this routing table. */
111 	rh->rib_family = family;
112 	rh->rib_fibnum = fibnum;
113 #ifdef VIMAGE
114 	rh->rib_vnet = curvnet;
115 #endif
116 
117 	tmproutes_init(rh);
118 
119 	/* Init locks */
120 	RIB_LOCK_INIT(rh);
121 
122 	nhops_init_rib(rh);
123 
124 	/* Init subscription system */
125 	rib_init_subscriptions(rh);
126 
127 	/* Finally, set base callbacks */
128 	rh->rnh_addaddr = rn_addroute;
129 	rh->rnh_deladdr = rn_delete;
130 	rh->rnh_matchaddr = rn_match;
131 	rh->rnh_lookup = rn_lookup;
132 	rh->rnh_walktree = rn_walktree;
133 	rh->rnh_walktree_from = rn_walktree_from;
134 
135 	return (rh);
136 }
137 
138 static int
139 rt_freeentry(struct radix_node *rn, void *arg)
140 {
141 	struct radix_head * const rnh = arg;
142 	struct radix_node *x;
143 
144 	x = (struct radix_node *)rn_delete(rn + 2, NULL, rnh);
145 	if (x != NULL)
146 		R_Free(x);
147 	return (0);
148 }
149 
150 void
151 rt_table_destroy(struct rib_head *rh)
152 {
153 
154 	tmproutes_destroy(rh);
155 
156 	rn_walktree(&rh->rmhead.head, rt_freeentry, &rh->rmhead.head);
157 
158 	nhops_destroy_rib(rh);
159 
160 	rib_destroy_subscriptions(rh);
161 
162 	/* Assume table is already empty */
163 	RIB_LOCK_DESTROY(rh);
164 	free(rh, M_RTABLE);
165 }
166 
167 /*
168  * Adds a temporal redirect entry to the routing table.
169  * @fibnum: fib number
170  * @dst: destination to install redirect to
171  * @gateway: gateway to go via
172  * @author: sockaddr of originating router, can be NULL
173  * @ifp: interface to use for the redirected route
174  * @flags: set of flags to add. Allowed: RTF_GATEWAY
175  * @lifetime_sec: time in seconds to expire this redirect.
176  *
177  * Retuns 0 on success, errno otherwise.
178  */
179 int
180 rib_add_redirect(u_int fibnum, struct sockaddr *dst, struct sockaddr *gateway,
181     struct sockaddr *author, struct ifnet *ifp, int flags, int lifetime_sec)
182 {
183 	struct rib_cmd_info rc;
184 	int error;
185 	struct rt_addrinfo info;
186 	struct rt_metrics rti_rmx;
187 	struct ifaddr *ifa;
188 
189 	NET_EPOCH_ASSERT();
190 
191 	if (rt_tables_get_rnh(fibnum, dst->sa_family) == NULL)
192 		return (EAFNOSUPPORT);
193 
194 	/* Verify the allowed flag mask. */
195 	KASSERT(((flags & ~(RTF_GATEWAY)) == 0),
196 	    ("invalid redirect flags: %x", flags));
197 	flags |= RTF_HOST | RTF_DYNAMIC;
198 
199 	/* Get the best ifa for the given interface and gateway. */
200 	if ((ifa = ifaof_ifpforaddr(gateway, ifp)) == NULL)
201 		return (ENETUNREACH);
202 	ifa_ref(ifa);
203 
204 	bzero(&info, sizeof(info));
205 	info.rti_info[RTAX_DST] = dst;
206 	info.rti_info[RTAX_GATEWAY] = gateway;
207 	info.rti_ifa = ifa;
208 	info.rti_ifp = ifp;
209 	info.rti_flags = flags;
210 
211 	/* Setup route metrics to define expire time. */
212 	bzero(&rti_rmx, sizeof(rti_rmx));
213 	/* Set expire time as absolute. */
214 	rti_rmx.rmx_expire = lifetime_sec + time_second;
215 	info.rti_mflags |= RTV_EXPIRE;
216 	info.rti_rmx = &rti_rmx;
217 
218 	error = rib_action(fibnum, RTM_ADD, &info, &rc);
219 	ifa_free(ifa);
220 
221 	if (error != 0) {
222 		/* TODO: add per-fib redirect stats. */
223 		return (error);
224 	}
225 
226 	RTSTAT_INC(rts_dynamic);
227 
228 	/* Send notification of a route addition to userland. */
229 	bzero(&info, sizeof(info));
230 	info.rti_info[RTAX_DST] = dst;
231 	info.rti_info[RTAX_GATEWAY] = gateway;
232 	info.rti_info[RTAX_AUTHOR] = author;
233 	rt_missmsg_fib(RTM_REDIRECT, &info, flags | RTF_UP, error, fibnum);
234 
235 	return (0);
236 }
237 
238 /*
239  * Routing table ioctl interface.
240  */
241 int
242 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
243 {
244 
245 	/*
246 	 * If more ioctl commands are added here, make sure the proper
247 	 * super-user checks are being performed because it is possible for
248 	 * prison-root to make it this far if raw sockets have been enabled
249 	 * in jails.
250 	 */
251 #ifdef INET
252 	/* Multicast goop, grrr... */
253 	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
254 #else /* INET */
255 	return ENXIO;
256 #endif /* INET */
257 }
258 
259 struct ifaddr *
260 ifa_ifwithroute(int flags, const struct sockaddr *dst,
261     const struct sockaddr *gateway, u_int fibnum)
262 {
263 	struct ifaddr *ifa;
264 
265 	NET_EPOCH_ASSERT();
266 	if ((flags & RTF_GATEWAY) == 0) {
267 		/*
268 		 * If we are adding a route to an interface,
269 		 * and the interface is a pt to pt link
270 		 * we should search for the destination
271 		 * as our clue to the interface.  Otherwise
272 		 * we can use the local address.
273 		 */
274 		ifa = NULL;
275 		if (flags & RTF_HOST)
276 			ifa = ifa_ifwithdstaddr(dst, fibnum);
277 		if (ifa == NULL)
278 			ifa = ifa_ifwithaddr(gateway);
279 	} else {
280 		/*
281 		 * If we are adding a route to a remote net
282 		 * or host, the gateway may still be on the
283 		 * other end of a pt to pt link.
284 		 */
285 		ifa = ifa_ifwithdstaddr(gateway, fibnum);
286 	}
287 	if (ifa == NULL)
288 		ifa = ifa_ifwithnet(gateway, 0, fibnum);
289 	if (ifa == NULL) {
290 		struct nhop_object *nh;
291 
292 		nh = rib_lookup(fibnum, gateway, NHR_NONE, 0);
293 
294 		/*
295 		 * dismiss a gateway that is reachable only
296 		 * through the default router
297 		 */
298 		if ((nh == NULL) || (nh->nh_flags & NHF_DEFAULT))
299 			return (NULL);
300 		ifa = nh->nh_ifa;
301 	}
302 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
303 		struct ifaddr *oifa = ifa;
304 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
305 		if (ifa == NULL)
306 			ifa = oifa;
307 	}
308 
309 	return (ifa);
310 }
311 
312 /*
313  * Copy most of @rt data into @info.
314  *
315  * If @flags contains NHR_COPY, copies dst,netmask and gw to the
316  * pointers specified by @info structure. Assume such pointers
317  * are zeroed sockaddr-like structures with sa_len field initialized
318  * to reflect size of the provided buffer. if no NHR_COPY is specified,
319  * point dst,netmask and gw @info fields to appropriate @rt values.
320  *
321  * if @flags contains NHR_REF, do refcouting on rt_ifp and rt_ifa.
322  *
323  * Returns 0 on success.
324  */
325 int
326 rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info, int flags)
327 {
328 	struct rt_metrics *rmx;
329 	struct sockaddr *src, *dst;
330 	struct nhop_object *nh;
331 	int sa_len;
332 
333 	nh = rt->rt_nhop;
334 	if (flags & NHR_COPY) {
335 		/* Copy destination if dst is non-zero */
336 		src = rt_key(rt);
337 		dst = info->rti_info[RTAX_DST];
338 		sa_len = src->sa_len;
339 		if (dst != NULL) {
340 			if (src->sa_len > dst->sa_len)
341 				return (ENOMEM);
342 			memcpy(dst, src, src->sa_len);
343 			info->rti_addrs |= RTA_DST;
344 		}
345 
346 		/* Copy mask if set && dst is non-zero */
347 		src = rt_mask(rt);
348 		dst = info->rti_info[RTAX_NETMASK];
349 		if (src != NULL && dst != NULL) {
350 			/*
351 			 * Radix stores different value in sa_len,
352 			 * assume rt_mask() to have the same length
353 			 * as rt_key()
354 			 */
355 			if (sa_len > dst->sa_len)
356 				return (ENOMEM);
357 			memcpy(dst, src, src->sa_len);
358 			info->rti_addrs |= RTA_NETMASK;
359 		}
360 
361 		/* Copy gateway is set && dst is non-zero */
362 		src = &nh->gw_sa;
363 		dst = info->rti_info[RTAX_GATEWAY];
364 		if ((nhop_get_rtflags(nh) & RTF_GATEWAY) &&
365 		    src != NULL && dst != NULL) {
366 			if (src->sa_len > dst->sa_len)
367 				return (ENOMEM);
368 			memcpy(dst, src, src->sa_len);
369 			info->rti_addrs |= RTA_GATEWAY;
370 		}
371 	} else {
372 		info->rti_info[RTAX_DST] = rt_key(rt);
373 		info->rti_addrs |= RTA_DST;
374 		if (rt_mask(rt) != NULL) {
375 			info->rti_info[RTAX_NETMASK] = rt_mask(rt);
376 			info->rti_addrs |= RTA_NETMASK;
377 		}
378 		if (nhop_get_rtflags(nh) & RTF_GATEWAY) {
379 			info->rti_info[RTAX_GATEWAY] = &nh->gw_sa;
380 			info->rti_addrs |= RTA_GATEWAY;
381 		}
382 	}
383 
384 	rmx = info->rti_rmx;
385 	if (rmx != NULL) {
386 		info->rti_mflags |= RTV_MTU;
387 		rmx->rmx_mtu = nh->nh_mtu;
388 	}
389 
390 	info->rti_flags = rt->rte_flags | nhop_get_rtflags(nh);
391 	info->rti_ifp = nh->nh_ifp;
392 	info->rti_ifa = nh->nh_ifa;
393 	if (flags & NHR_REF) {
394 		if_ref(info->rti_ifp);
395 		ifa_ref(info->rti_ifa);
396 	}
397 
398 	return (0);
399 }
400 
401 /*
402  * Lookups up route entry for @dst in RIB database for fib @fibnum.
403  * Exports entry data to @info using rt_exportinfo().
404  *
405  * If @flags contains NHR_REF, refcouting is performed on rt_ifp and rt_ifa.
406  * All references can be released later by calling rib_free_info().
407  *
408  * Returns 0 on success.
409  * Returns ENOENT for lookup failure, ENOMEM for export failure.
410  */
411 int
412 rib_lookup_info(uint32_t fibnum, const struct sockaddr *dst, uint32_t flags,
413     uint32_t flowid, struct rt_addrinfo *info)
414 {
415 	RIB_RLOCK_TRACKER;
416 	struct rib_head *rh;
417 	struct radix_node *rn;
418 	struct rtentry *rt;
419 	int error;
420 
421 	KASSERT((fibnum < rt_numfibs), ("rib_lookup_rte: bad fibnum"));
422 	rh = rt_tables_get_rnh(fibnum, dst->sa_family);
423 	if (rh == NULL)
424 		return (ENOENT);
425 
426 	RIB_RLOCK(rh);
427 	rn = rh->rnh_matchaddr(__DECONST(void *, dst), &rh->head);
428 	if (rn != NULL && ((rn->rn_flags & RNF_ROOT) == 0)) {
429 		rt = RNTORT(rn);
430 		/* Ensure route & ifp is UP */
431 		if (RT_LINK_IS_UP(rt->rt_nhop->nh_ifp)) {
432 			flags = (flags & NHR_REF) | NHR_COPY;
433 			error = rt_exportinfo(rt, info, flags);
434 			RIB_RUNLOCK(rh);
435 
436 			return (error);
437 		}
438 	}
439 	RIB_RUNLOCK(rh);
440 
441 	return (ENOENT);
442 }
443 
444 /*
445  * Releases all references acquired by rib_lookup_info() when
446  * called with NHR_REF flags.
447  */
448 void
449 rib_free_info(struct rt_addrinfo *info)
450 {
451 
452 	ifa_free(info->rti_ifa);
453 	if_rele(info->rti_ifp);
454 }
455 
456 /*
457  * Delete Routes for a Network Interface
458  *
459  * Called for each routing entry via the rnh->rnh_walktree() call above
460  * to delete all route entries referencing a detaching network interface.
461  *
462  * Arguments:
463  *	rt	pointer to rtentry
464  *	nh	pointer to nhop
465  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
466  *
467  * Returns:
468  *	0	successful
469  *	errno	failed - reason indicated
470  */
471 static int
472 rt_ifdelroute(const struct rtentry *rt, const struct nhop_object *nh, void *arg)
473 {
474 	struct ifnet	*ifp = arg;
475 
476 	if (nh->nh_ifp != ifp)
477 		return (0);
478 
479 	/*
480 	 * Protect (sorta) against walktree recursion problems
481 	 * with cloned routes
482 	 */
483 	if ((rt->rte_flags & RTF_UP) == 0)
484 		return (0);
485 
486 	return (1);
487 }
488 
489 /*
490  * Delete all remaining routes using this interface
491  * Unfortuneatly the only way to do this is to slog through
492  * the entire routing table looking for routes which point
493  * to this interface...oh well...
494  */
495 void
496 rt_flushifroutes_af(struct ifnet *ifp, int af)
497 {
498 	KASSERT((af >= 1 && af <= AF_MAX), ("%s: af %d not >= 1 and <= %d",
499 	    __func__, af, AF_MAX));
500 
501 	rib_foreach_table_walk_del(af, rt_ifdelroute, ifp);
502 }
503 
504 void
505 rt_flushifroutes(struct ifnet *ifp)
506 {
507 
508 	rib_foreach_table_walk_del(AF_UNSPEC, rt_ifdelroute, ifp);
509 }
510 
511 /*
512  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
513  * it will be referenced so the caller must free it.
514  *
515  * Assume basic consistency checks are executed by callers:
516  * RTAX_DST exists, if RTF_GATEWAY is set, RTAX_GATEWAY exists as well.
517  */
518 int
519 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
520 {
521 	const struct sockaddr *dst, *gateway, *ifpaddr, *ifaaddr;
522 	struct epoch_tracker et;
523 	int needref, error, flags;
524 
525 	dst = info->rti_info[RTAX_DST];
526 	gateway = info->rti_info[RTAX_GATEWAY];
527 	ifpaddr = info->rti_info[RTAX_IFP];
528 	ifaaddr = info->rti_info[RTAX_IFA];
529 	flags = info->rti_flags;
530 
531 	/*
532 	 * ifp may be specified by sockaddr_dl
533 	 * when protocol address is ambiguous.
534 	 */
535 	error = 0;
536 	needref = (info->rti_ifa == NULL);
537 	NET_EPOCH_ENTER(et);
538 
539 	/* If we have interface specified by the ifindex in the address, use it */
540 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
541 	    ifpaddr->sa_family == AF_LINK) {
542 	    const struct sockaddr_dl *sdl = (const struct sockaddr_dl *)ifpaddr;
543 	    if (sdl->sdl_index != 0)
544 		    info->rti_ifp = ifnet_byindex(sdl->sdl_index);
545 	}
546 	/*
547 	 * If we have source address specified, try to find it
548 	 * TODO: avoid enumerating all ifas on all interfaces.
549 	 */
550 	if (info->rti_ifa == NULL && ifaaddr != NULL)
551 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
552 	if (info->rti_ifa == NULL) {
553 		const struct sockaddr *sa;
554 
555 		/*
556 		 * Most common use case for the userland-supplied routes.
557 		 *
558 		 * Choose sockaddr to select ifa.
559 		 * -- if ifp is set --
560 		 * Order of preference:
561 		 * 1) IFA address
562 		 * 2) gateway address
563 		 *   Note: for interface routes link-level gateway address
564 		 *     is specified to indicate the interface index without
565 		 *     specifying RTF_GATEWAY. In this case, ignore gateway
566 		 *   Note: gateway AF may be different from dst AF. In this case,
567 		 *   ignore gateway
568 		 * 3) final destination.
569 		 * 4) if all of these fails, try to get at least link-level ifa.
570 		 * -- else --
571 		 * try to lookup gateway or dst in the routing table to get ifa
572 		 */
573 		if (info->rti_info[RTAX_IFA] != NULL)
574 			sa = info->rti_info[RTAX_IFA];
575 		else if ((info->rti_flags & RTF_GATEWAY) != 0 &&
576 		    gateway->sa_family == dst->sa_family)
577 			sa = gateway;
578 		else
579 			sa = dst;
580 		if (info->rti_ifp != NULL) {
581 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
582 			/* Case 4 */
583 			if (info->rti_ifa == NULL && gateway != NULL)
584 				info->rti_ifa = ifaof_ifpforaddr(gateway, info->rti_ifp);
585 		} else if (dst != NULL && gateway != NULL)
586 			info->rti_ifa = ifa_ifwithroute(flags, dst, gateway,
587 							fibnum);
588 		else if (sa != NULL)
589 			info->rti_ifa = ifa_ifwithroute(flags, sa, sa,
590 							fibnum);
591 	}
592 	if (needref && info->rti_ifa != NULL) {
593 		if (info->rti_ifp == NULL)
594 			info->rti_ifp = info->rti_ifa->ifa_ifp;
595 		ifa_ref(info->rti_ifa);
596 	} else
597 		error = ENETUNREACH;
598 	NET_EPOCH_EXIT(et);
599 	return (error);
600 }
601 
602 void
603 rt_updatemtu(struct ifnet *ifp)
604 {
605 	struct rib_head *rnh;
606 	int mtu;
607 	int i, j;
608 
609 	/*
610 	 * Try to update rt_mtu for all routes using this interface
611 	 * Unfortunately the only way to do this is to traverse all
612 	 * routing tables in all fibs/domains.
613 	 */
614 	for (i = 1; i <= AF_MAX; i++) {
615 		mtu = if_getmtu_family(ifp, i);
616 		for (j = 0; j < rt_numfibs; j++) {
617 			rnh = rt_tables_get_rnh(j, i);
618 			if (rnh == NULL)
619 				continue;
620 			nhops_update_ifmtu(rnh, ifp, mtu);
621 		}
622 	}
623 }
624 
625 #if 0
626 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
627 int rt_print(char *buf, int buflen, struct rtentry *rt);
628 
629 int
630 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
631 {
632 	void *paddr = NULL;
633 
634 	switch (s->sa_family) {
635 	case AF_INET:
636 		paddr = &((struct sockaddr_in *)s)->sin_addr;
637 		break;
638 	case AF_INET6:
639 		paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
640 		break;
641 	}
642 
643 	if (paddr == NULL)
644 		return (0);
645 
646 	if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
647 		return (0);
648 
649 	return (strlen(buf));
650 }
651 
652 int
653 rt_print(char *buf, int buflen, struct rtentry *rt)
654 {
655 	struct sockaddr *addr, *mask;
656 	int i = 0;
657 
658 	addr = rt_key(rt);
659 	mask = rt_mask(rt);
660 
661 	i = p_sockaddr(buf, buflen, addr);
662 	if (!(rt->rt_flags & RTF_HOST)) {
663 		buf[i++] = '/';
664 		i += p_sockaddr(buf + i, buflen - i, mask);
665 	}
666 
667 	if (rt->rt_flags & RTF_GATEWAY) {
668 		buf[i++] = '>';
669 		i += p_sockaddr(buf + i, buflen - i, &rt->rt_nhop->gw_sa);
670 	}
671 
672 	return (i);
673 }
674 #endif
675 
676 void
677 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
678 {
679 	u_char *cp1 = (u_char *)src;
680 	u_char *cp2 = (u_char *)dst;
681 	u_char *cp3 = (u_char *)netmask;
682 	u_char *cplim = cp2 + *cp3;
683 	u_char *cplim2 = cp2 + *cp1;
684 
685 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
686 	cp3 += 2;
687 	if (cplim > cplim2)
688 		cplim = cplim2;
689 	while (cp2 < cplim)
690 		*cp2++ = *cp1++ & *cp3++;
691 	if (cp2 < cplim2)
692 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
693 }
694 
695 /*
696  * Announce interface address arrival/withdraw
697  * Returns 0 on success.
698  */
699 int
700 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
701 {
702 
703 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
704 	    ("unexpected cmd %d", cmd));
705 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
706 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
707 
708 	EVENTHANDLER_DIRECT_INVOKE(rt_addrmsg, ifa, cmd);
709 	return (rtsock_addrmsg(cmd, ifa, fibnum));
710 }
711 
712 /*
713  * Announce kernel-originated route addition/removal to rtsock based on @rt data.
714  * cmd: RTM_ cmd
715  * @rt: valid rtentry
716  * @ifp: target route interface
717  * @fibnum: fib id or RT_ALL_FIBS
718  *
719  * Returns 0 on success.
720  */
721 int
722 rt_routemsg(int cmd, struct rtentry *rt, struct ifnet *ifp, int rti_addrs,
723     int fibnum)
724 {
725 
726 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
727 	    ("unexpected cmd %d", cmd));
728 
729 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
730 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
731 
732 	KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
733 
734 	return (rtsock_routemsg(cmd, rt, ifp, 0, fibnum));
735 }
736 
737 /*
738  * Announce kernel-originated route addition/removal to rtsock based on @rt data.
739  * cmd: RTM_ cmd
740  * @info: addrinfo structure with valid data.
741  * @fibnum: fib id or RT_ALL_FIBS
742  *
743  * Returns 0 on success.
744  */
745 int
746 rt_routemsg_info(int cmd, struct rt_addrinfo *info, int fibnum)
747 {
748 
749 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE || cmd == RTM_CHANGE,
750 	    ("unexpected cmd %d", cmd));
751 
752 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
753 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
754 
755 	KASSERT(info->rti_info[RTAX_DST] != NULL, (":%s: RTAX_DST must be supplied", __func__));
756 
757 	return (rtsock_routemsg_info(cmd, info, fibnum));
758 }
759 
760 /*
761  * This is called to generate messages from the routing socket
762  * indicating a network interface has had addresses associated with it.
763  */
764 void
765 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, struct rtentry *rt, int fibnum)
766 {
767 
768 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
769 		("unexpected cmd %u", cmd));
770 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
771 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
772 
773 	if (cmd == RTM_ADD) {
774 		rt_addrmsg(cmd, ifa, fibnum);
775 		if (rt != NULL)
776 			rt_routemsg(cmd, rt, ifa->ifa_ifp, 0, fibnum);
777 	} else {
778 		if (rt != NULL)
779 			rt_routemsg(cmd, rt, ifa->ifa_ifp, 0, fibnum);
780 		rt_addrmsg(cmd, ifa, fibnum);
781 	}
782 }
783