xref: /freebsd/sys/net/rtsock.c (revision 271171e0)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1988, 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  *	@(#)rtsock.c	8.7 (Berkeley) 10/12/95
32  * $FreeBSD$
33  */
34 #include "opt_ddb.h"
35 #include "opt_route.h"
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 
39 #include <sys/param.h>
40 #include <sys/jail.h>
41 #include <sys/kernel.h>
42 #include <sys/eventhandler.h>
43 #include <sys/domain.h>
44 #include <sys/lock.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/protosw.h>
50 #include <sys/rmlock.h>
51 #include <sys/rwlock.h>
52 #include <sys/signalvar.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/sysctl.h>
56 #include <sys/systm.h>
57 
58 #include <net/if.h>
59 #include <net/if_var.h>
60 #include <net/if_dl.h>
61 #include <net/if_llatbl.h>
62 #include <net/if_types.h>
63 #include <net/netisr.h>
64 #include <net/route.h>
65 #include <net/route/route_ctl.h>
66 #include <net/route/route_var.h>
67 #include <net/vnet.h>
68 
69 #include <netinet/in.h>
70 #include <netinet/if_ether.h>
71 #include <netinet/ip_carp.h>
72 #ifdef INET6
73 #include <netinet6/in6_var.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/scope6_var.h>
76 #endif
77 #include <net/route/nhop.h>
78 
79 #define	DEBUG_MOD_NAME	rtsock
80 #define	DEBUG_MAX_LEVEL	LOG_DEBUG
81 #include <net/route/route_debug.h>
82 _DECLARE_DEBUG(LOG_INFO);
83 
84 #ifdef COMPAT_FREEBSD32
85 #include <sys/mount.h>
86 #include <compat/freebsd32/freebsd32.h>
87 
88 struct if_msghdr32 {
89 	uint16_t ifm_msglen;
90 	uint8_t	ifm_version;
91 	uint8_t	ifm_type;
92 	int32_t	ifm_addrs;
93 	int32_t	ifm_flags;
94 	uint16_t ifm_index;
95 	uint16_t _ifm_spare1;
96 	struct	if_data ifm_data;
97 };
98 
99 struct if_msghdrl32 {
100 	uint16_t ifm_msglen;
101 	uint8_t	ifm_version;
102 	uint8_t	ifm_type;
103 	int32_t	ifm_addrs;
104 	int32_t	ifm_flags;
105 	uint16_t ifm_index;
106 	uint16_t _ifm_spare1;
107 	uint16_t ifm_len;
108 	uint16_t ifm_data_off;
109 	uint32_t _ifm_spare2;
110 	struct	if_data ifm_data;
111 };
112 
113 struct ifa_msghdrl32 {
114 	uint16_t ifam_msglen;
115 	uint8_t	ifam_version;
116 	uint8_t	ifam_type;
117 	int32_t	ifam_addrs;
118 	int32_t	ifam_flags;
119 	uint16_t ifam_index;
120 	uint16_t _ifam_spare1;
121 	uint16_t ifam_len;
122 	uint16_t ifam_data_off;
123 	int32_t	ifam_metric;
124 	struct	if_data ifam_data;
125 };
126 
127 #define SA_SIZE32(sa)						\
128     (  (((struct sockaddr *)(sa))->sa_len == 0) ?		\
129 	sizeof(int)		:				\
130 	1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(int) - 1) ) )
131 
132 #endif /* COMPAT_FREEBSD32 */
133 
134 struct linear_buffer {
135 	char		*base;	/* Base allocated memory pointer */
136 	uint32_t	offset;	/* Currently used offset */
137 	uint32_t	size;	/* Total buffer size */
138 };
139 #define	SCRATCH_BUFFER_SIZE	1024
140 
141 #define	RTS_PID_LOG(_l, _fmt, ...)	RT_LOG_##_l(_l, "PID %d: " _fmt, curproc ? curproc->p_pid : 0, ## __VA_ARGS__)
142 
143 MALLOC_DEFINE(M_RTABLE, "routetbl", "routing tables");
144 
145 /* NB: these are not modified */
146 static struct	sockaddr route_src = { 2, PF_ROUTE, };
147 static struct	sockaddr sa_zero   = { sizeof(sa_zero), AF_INET, };
148 
149 /* These are external hooks for CARP. */
150 int	(*carp_get_vhid_p)(struct ifaddr *);
151 
152 /*
153  * Used by rtsock callback code to decide whether to filter the update
154  * notification to a socket bound to a particular FIB.
155  */
156 #define	RTS_FILTER_FIB	M_PROTO8
157 /*
158  * Used to store address family of the notification.
159  */
160 #define	m_rtsock_family	m_pkthdr.PH_loc.eight[0]
161 
162 struct rcb {
163 	LIST_ENTRY(rcb) list;
164 	struct socket	*rcb_socket;
165 	sa_family_t	rcb_family;
166 };
167 
168 typedef struct {
169 	LIST_HEAD(, rcb)	cblist;
170 	int	ip_count;	/* attached w/ AF_INET */
171 	int	ip6_count;	/* attached w/ AF_INET6 */
172 	int	any_count;	/* total attached */
173 } route_cb_t;
174 VNET_DEFINE_STATIC(route_cb_t, route_cb);
175 #define	V_route_cb VNET(route_cb)
176 
177 struct mtx rtsock_mtx;
178 MTX_SYSINIT(rtsock, &rtsock_mtx, "rtsock route_cb lock", MTX_DEF);
179 
180 #define	RTSOCK_LOCK()	mtx_lock(&rtsock_mtx)
181 #define	RTSOCK_UNLOCK()	mtx_unlock(&rtsock_mtx)
182 #define	RTSOCK_LOCK_ASSERT()	mtx_assert(&rtsock_mtx, MA_OWNED)
183 
184 SYSCTL_NODE(_net, OID_AUTO, route, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
185 
186 struct walkarg {
187 	int	family;
188 	int	w_tmemsize;
189 	int	w_op, w_arg;
190 	caddr_t	w_tmem;
191 	struct sysctl_req *w_req;
192 	struct sockaddr *dst;
193 	struct sockaddr *mask;
194 };
195 
196 static void	rts_input(struct mbuf *m);
197 static struct mbuf *rtsock_msg_mbuf(int type, struct rt_addrinfo *rtinfo);
198 static int	rtsock_msg_buffer(int type, struct rt_addrinfo *rtinfo,
199 			struct walkarg *w, int *plen);
200 static int	rt_xaddrs(caddr_t cp, caddr_t cplim,
201 			struct rt_addrinfo *rtinfo);
202 static int	cleanup_xaddrs(struct rt_addrinfo *info, struct linear_buffer *lb);
203 static int	sysctl_dumpentry(struct rtentry *rt, void *vw);
204 static int	sysctl_dumpnhop(struct rtentry *rt, struct nhop_object *nh,
205 			uint32_t weight, struct walkarg *w);
206 static int	sysctl_iflist(int af, struct walkarg *w);
207 static int	sysctl_ifmalist(int af, struct walkarg *w);
208 static void	rt_getmetrics(const struct rtentry *rt,
209 			const struct nhop_object *nh, struct rt_metrics *out);
210 static void	rt_dispatch(struct mbuf *, sa_family_t);
211 static void	rt_ifannouncemsg(struct ifnet *ifp, int what);
212 static int	handle_rtm_get(struct rt_addrinfo *info, u_int fibnum,
213 			struct rt_msghdr *rtm, struct rib_cmd_info *rc);
214 static int	update_rtm_from_rc(struct rt_addrinfo *info,
215 			struct rt_msghdr **prtm, int alloc_len,
216 			struct rib_cmd_info *rc, struct nhop_object *nh);
217 static void	send_rtm_reply(struct socket *so, struct rt_msghdr *rtm,
218 			struct mbuf *m, sa_family_t saf, u_int fibnum,
219 			int rtm_errno);
220 static bool	can_export_rte(struct ucred *td_ucred, bool rt_is_host,
221 			const struct sockaddr *rt_dst);
222 
223 static struct netisr_handler rtsock_nh = {
224 	.nh_name = "rtsock",
225 	.nh_handler = rts_input,
226 	.nh_proto = NETISR_ROUTE,
227 	.nh_policy = NETISR_POLICY_SOURCE,
228 };
229 
230 static int
231 sysctl_route_netisr_maxqlen(SYSCTL_HANDLER_ARGS)
232 {
233 	int error, qlimit;
234 
235 	netisr_getqlimit(&rtsock_nh, &qlimit);
236 	error = sysctl_handle_int(oidp, &qlimit, 0, req);
237         if (error || !req->newptr)
238                 return (error);
239 	if (qlimit < 1)
240 		return (EINVAL);
241 	return (netisr_setqlimit(&rtsock_nh, qlimit));
242 }
243 SYSCTL_PROC(_net_route, OID_AUTO, netisr_maxqlen,
244     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
245     0, 0, sysctl_route_netisr_maxqlen, "I",
246     "maximum routing socket dispatch queue length");
247 
248 static void
249 vnet_rts_init(void)
250 {
251 	int tmp;
252 
253 	if (IS_DEFAULT_VNET(curvnet)) {
254 		if (TUNABLE_INT_FETCH("net.route.netisr_maxqlen", &tmp))
255 			rtsock_nh.nh_qlimit = tmp;
256 		netisr_register(&rtsock_nh);
257 	}
258 #ifdef VIMAGE
259 	 else
260 		netisr_register_vnet(&rtsock_nh);
261 #endif
262 }
263 VNET_SYSINIT(vnet_rtsock, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
264     vnet_rts_init, 0);
265 
266 #ifdef VIMAGE
267 static void
268 vnet_rts_uninit(void)
269 {
270 
271 	netisr_unregister_vnet(&rtsock_nh);
272 }
273 VNET_SYSUNINIT(vnet_rts_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
274     vnet_rts_uninit, 0);
275 #endif
276 
277 static void
278 rts_handle_ifnet_arrival(void *arg __unused, struct ifnet *ifp)
279 {
280 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
281 }
282 EVENTHANDLER_DEFINE(ifnet_arrival_event, rts_handle_ifnet_arrival, NULL, 0);
283 
284 static void
285 rts_handle_ifnet_departure(void *arg __unused, struct ifnet *ifp)
286 {
287 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
288 }
289 EVENTHANDLER_DEFINE(ifnet_departure_event, rts_handle_ifnet_departure, NULL, 0);
290 
291 static void
292 rts_append_data(struct socket *so, struct mbuf *m)
293 {
294 
295 	if (sbappendaddr(&so->so_rcv, &route_src, m, NULL) == 0) {
296 		soroverflow(so);
297 		m_freem(m);
298 	} else
299 		sorwakeup(so);
300 }
301 
302 static void
303 rts_input(struct mbuf *m)
304 {
305 	struct rcb *rcb;
306 	struct socket *last;
307 
308 	last = NULL;
309 	RTSOCK_LOCK();
310 	LIST_FOREACH(rcb, &V_route_cb.cblist, list) {
311 		if (rcb->rcb_family != AF_UNSPEC &&
312 		    rcb->rcb_family != m->m_rtsock_family)
313 			continue;
314 		if ((m->m_flags & RTS_FILTER_FIB) &&
315 		    M_GETFIB(m) != rcb->rcb_socket->so_fibnum)
316 			continue;
317 		if (last != NULL) {
318 			struct mbuf *n;
319 
320 			n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
321 			if (n != NULL)
322 				rts_append_data(last, n);
323 		}
324 		last = rcb->rcb_socket;
325 	}
326 	if (last != NULL)
327 		rts_append_data(last, m);
328 	else
329 		m_freem(m);
330 	RTSOCK_UNLOCK();
331 }
332 
333 static void
334 rts_close(struct socket *so)
335 {
336 
337 	soisdisconnected(so);
338 }
339 
340 static SYSCTL_NODE(_net, OID_AUTO, rtsock, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
341     "Routing socket infrastructure");
342 static u_long rts_sendspace = 8192;
343 SYSCTL_ULONG(_net_rtsock, OID_AUTO, sendspace, CTLFLAG_RW, &rts_sendspace, 0,
344     "Default routing socket send space");
345 static u_long rts_recvspace = 8192;
346 SYSCTL_ULONG(_net_rtsock, OID_AUTO, recvspace, CTLFLAG_RW, &rts_recvspace, 0,
347     "Default routing socket receive space");
348 
349 static int
350 rts_attach(struct socket *so, int proto, struct thread *td)
351 {
352 	struct rcb *rcb;
353 	int error;
354 
355 	error = soreserve(so, rts_sendspace, rts_recvspace);
356 	if (error)
357 		return (error);
358 
359 	rcb = malloc(sizeof(*rcb), M_PCB, M_WAITOK);
360 	rcb->rcb_socket = so;
361 	rcb->rcb_family = proto;
362 
363 	so->so_pcb = rcb;
364 	so->so_fibnum = td->td_proc->p_fibnum;
365 	so->so_options |= SO_USELOOPBACK;
366 
367 	RTSOCK_LOCK();
368 	LIST_INSERT_HEAD(&V_route_cb.cblist, rcb, list);
369 	switch (proto) {
370 	case AF_INET:
371 		V_route_cb.ip_count++;
372 		break;
373 	case AF_INET6:
374 		V_route_cb.ip6_count++;
375 		break;
376 	}
377 	V_route_cb.any_count++;
378 	RTSOCK_UNLOCK();
379 	soisconnected(so);
380 
381 	return (0);
382 }
383 
384 static void
385 rts_detach(struct socket *so)
386 {
387 	struct rcb *rcb = so->so_pcb;
388 
389 	RTSOCK_LOCK();
390 	LIST_REMOVE(rcb, list);
391 	switch(rcb->rcb_family) {
392 	case AF_INET:
393 		V_route_cb.ip_count--;
394 		break;
395 	case AF_INET6:
396 		V_route_cb.ip6_count--;
397 		break;
398 	}
399 	V_route_cb.any_count--;
400 	RTSOCK_UNLOCK();
401 	free(rcb, M_PCB);
402 	so->so_pcb = NULL;
403 }
404 
405 static int
406 rts_shutdown(struct socket *so)
407 {
408 
409 	socantsendmore(so);
410 	return (0);
411 }
412 
413 #ifndef _SOCKADDR_UNION_DEFINED
414 #define	_SOCKADDR_UNION_DEFINED
415 /*
416  * The union of all possible address formats we handle.
417  */
418 union sockaddr_union {
419 	struct sockaddr		sa;
420 	struct sockaddr_in	sin;
421 	struct sockaddr_in6	sin6;
422 };
423 #endif /* _SOCKADDR_UNION_DEFINED */
424 
425 static int
426 rtm_get_jailed(struct rt_addrinfo *info, struct ifnet *ifp,
427     struct nhop_object *nh, union sockaddr_union *saun, struct ucred *cred)
428 {
429 #if defined(INET) || defined(INET6)
430 	struct epoch_tracker et;
431 #endif
432 
433 	/* First, see if the returned address is part of the jail. */
434 	if (prison_if(cred, nh->nh_ifa->ifa_addr) == 0) {
435 		info->rti_info[RTAX_IFA] = nh->nh_ifa->ifa_addr;
436 		return (0);
437 	}
438 
439 	switch (info->rti_info[RTAX_DST]->sa_family) {
440 #ifdef INET
441 	case AF_INET:
442 	{
443 		struct in_addr ia;
444 		struct ifaddr *ifa;
445 		int found;
446 
447 		found = 0;
448 		/*
449 		 * Try to find an address on the given outgoing interface
450 		 * that belongs to the jail.
451 		 */
452 		NET_EPOCH_ENTER(et);
453 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
454 			struct sockaddr *sa;
455 			sa = ifa->ifa_addr;
456 			if (sa->sa_family != AF_INET)
457 				continue;
458 			ia = ((struct sockaddr_in *)sa)->sin_addr;
459 			if (prison_check_ip4(cred, &ia) == 0) {
460 				found = 1;
461 				break;
462 			}
463 		}
464 		NET_EPOCH_EXIT(et);
465 		if (!found) {
466 			/*
467 			 * As a last resort return the 'default' jail address.
468 			 */
469 			ia = ((struct sockaddr_in *)nh->nh_ifa->ifa_addr)->
470 			    sin_addr;
471 			if (prison_get_ip4(cred, &ia) != 0)
472 				return (ESRCH);
473 		}
474 		bzero(&saun->sin, sizeof(struct sockaddr_in));
475 		saun->sin.sin_len = sizeof(struct sockaddr_in);
476 		saun->sin.sin_family = AF_INET;
477 		saun->sin.sin_addr.s_addr = ia.s_addr;
478 		info->rti_info[RTAX_IFA] = (struct sockaddr *)&saun->sin;
479 		break;
480 	}
481 #endif
482 #ifdef INET6
483 	case AF_INET6:
484 	{
485 		struct in6_addr ia6;
486 		struct ifaddr *ifa;
487 		int found;
488 
489 		found = 0;
490 		/*
491 		 * Try to find an address on the given outgoing interface
492 		 * that belongs to the jail.
493 		 */
494 		NET_EPOCH_ENTER(et);
495 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
496 			struct sockaddr *sa;
497 			sa = ifa->ifa_addr;
498 			if (sa->sa_family != AF_INET6)
499 				continue;
500 			bcopy(&((struct sockaddr_in6 *)sa)->sin6_addr,
501 			    &ia6, sizeof(struct in6_addr));
502 			if (prison_check_ip6(cred, &ia6) == 0) {
503 				found = 1;
504 				break;
505 			}
506 		}
507 		NET_EPOCH_EXIT(et);
508 		if (!found) {
509 			/*
510 			 * As a last resort return the 'default' jail address.
511 			 */
512 			ia6 = ((struct sockaddr_in6 *)nh->nh_ifa->ifa_addr)->
513 			    sin6_addr;
514 			if (prison_get_ip6(cred, &ia6) != 0)
515 				return (ESRCH);
516 		}
517 		bzero(&saun->sin6, sizeof(struct sockaddr_in6));
518 		saun->sin6.sin6_len = sizeof(struct sockaddr_in6);
519 		saun->sin6.sin6_family = AF_INET6;
520 		bcopy(&ia6, &saun->sin6.sin6_addr, sizeof(struct in6_addr));
521 		if (sa6_recoverscope(&saun->sin6) != 0)
522 			return (ESRCH);
523 		info->rti_info[RTAX_IFA] = (struct sockaddr *)&saun->sin6;
524 		break;
525 	}
526 #endif
527 	default:
528 		return (ESRCH);
529 	}
530 	return (0);
531 }
532 
533 static int
534 fill_blackholeinfo(struct rt_addrinfo *info, union sockaddr_union *saun)
535 {
536 	struct ifaddr *ifa;
537 	sa_family_t saf;
538 
539 	if (V_loif == NULL) {
540 		RTS_PID_LOG(LOG_INFO, "Unable to add blackhole/reject nhop without loopback");
541 		return (ENOTSUP);
542 	}
543 	info->rti_ifp = V_loif;
544 
545 	saf = info->rti_info[RTAX_DST]->sa_family;
546 
547 	CK_STAILQ_FOREACH(ifa, &info->rti_ifp->if_addrhead, ifa_link) {
548 		if (ifa->ifa_addr->sa_family == saf) {
549 			info->rti_ifa = ifa;
550 			break;
551 		}
552 	}
553 	if (info->rti_ifa == NULL) {
554 		RTS_PID_LOG(LOG_INFO, "Unable to find ifa for blackhole/reject nhop");
555 		return (ENOTSUP);
556 	}
557 
558 	bzero(saun, sizeof(union sockaddr_union));
559 	switch (saf) {
560 #ifdef INET
561 	case AF_INET:
562 		saun->sin.sin_family = AF_INET;
563 		saun->sin.sin_len = sizeof(struct sockaddr_in);
564 		saun->sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
565 		break;
566 #endif
567 #ifdef INET6
568 	case AF_INET6:
569 		saun->sin6.sin6_family = AF_INET6;
570 		saun->sin6.sin6_len = sizeof(struct sockaddr_in6);
571 		saun->sin6.sin6_addr = in6addr_loopback;
572 		break;
573 #endif
574 	default:
575 		RTS_PID_LOG(LOG_INFO, "unsupported family: %d", saf);
576 		return (ENOTSUP);
577 	}
578 	info->rti_info[RTAX_GATEWAY] = &saun->sa;
579 	info->rti_flags |= RTF_GATEWAY;
580 
581 	return (0);
582 }
583 
584 /*
585  * Fills in @info based on userland-provided @rtm message.
586  *
587  * Returns 0 on success.
588  */
589 static int
590 fill_addrinfo(struct rt_msghdr *rtm, int len, struct linear_buffer *lb, u_int fibnum,
591     struct rt_addrinfo *info)
592 {
593 	int error;
594 
595 	rtm->rtm_pid = curproc->p_pid;
596 	info->rti_addrs = rtm->rtm_addrs;
597 
598 	info->rti_mflags = rtm->rtm_inits;
599 	info->rti_rmx = &rtm->rtm_rmx;
600 
601 	/*
602 	 * rt_xaddrs() performs s6_addr[2] := sin6_scope_id for AF_INET6
603 	 * link-local address because rtrequest requires addresses with
604 	 * embedded scope id.
605 	 */
606 	if (rt_xaddrs((caddr_t)(rtm + 1), len + (caddr_t)rtm, info))
607 		return (EINVAL);
608 
609 	info->rti_flags = rtm->rtm_flags;
610 	error = cleanup_xaddrs(info, lb);
611 	if (error != 0)
612 		return (error);
613 	/*
614 	 * Verify that the caller has the appropriate privilege; RTM_GET
615 	 * is the only operation the non-superuser is allowed.
616 	 */
617 	if (rtm->rtm_type != RTM_GET) {
618 		error = priv_check(curthread, PRIV_NET_ROUTE);
619 		if (error != 0)
620 			return (error);
621 	}
622 
623 	/*
624 	 * The given gateway address may be an interface address.
625 	 * For example, issuing a "route change" command on a route
626 	 * entry that was created from a tunnel, and the gateway
627 	 * address given is the local end point. In this case the
628 	 * RTF_GATEWAY flag must be cleared or the destination will
629 	 * not be reachable even though there is no error message.
630 	 */
631 	if (info->rti_info[RTAX_GATEWAY] != NULL &&
632 	    info->rti_info[RTAX_GATEWAY]->sa_family != AF_LINK) {
633 		struct rt_addrinfo ginfo;
634 		struct sockaddr *gdst;
635 		struct sockaddr_storage ss;
636 
637 		bzero(&ginfo, sizeof(ginfo));
638 		bzero(&ss, sizeof(ss));
639 		ss.ss_len = sizeof(ss);
640 
641 		ginfo.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&ss;
642 		gdst = info->rti_info[RTAX_GATEWAY];
643 
644 		/*
645 		 * A host route through the loopback interface is
646 		 * installed for each interface adddress. In pre 8.0
647 		 * releases the interface address of a PPP link type
648 		 * is not reachable locally. This behavior is fixed as
649 		 * part of the new L2/L3 redesign and rewrite work. The
650 		 * signature of this interface address route is the
651 		 * AF_LINK sa_family type of the gateway, and the
652 		 * rt_ifp has the IFF_LOOPBACK flag set.
653 		 */
654 		if (rib_lookup_info(fibnum, gdst, NHR_REF, 0, &ginfo) == 0) {
655 			if (ss.ss_family == AF_LINK &&
656 			    ginfo.rti_ifp->if_flags & IFF_LOOPBACK) {
657 				info->rti_flags &= ~RTF_GATEWAY;
658 				info->rti_flags |= RTF_GWFLAG_COMPAT;
659 			}
660 			rib_free_info(&ginfo);
661 		}
662 	}
663 
664 	return (0);
665 }
666 
667 static struct nhop_object *
668 select_nhop(struct nhop_object *nh, const struct sockaddr *gw)
669 {
670 	if (!NH_IS_NHGRP(nh))
671 		return (nh);
672 #ifdef ROUTE_MPATH
673 	const struct weightened_nhop *wn;
674 	uint32_t num_nhops;
675 	wn = nhgrp_get_nhops((struct nhgrp_object *)nh, &num_nhops);
676 	if (gw == NULL)
677 		return (wn[0].nh);
678 	for (int i = 0; i < num_nhops; i++) {
679 		if (match_nhop_gw(wn[i].nh, gw))
680 			return (wn[i].nh);
681 	}
682 #endif
683 	return (NULL);
684 }
685 
686 /*
687  * Handles RTM_GET message from routing socket, returning matching rt.
688  *
689  * Returns:
690  * 0 on success, with locked and referenced matching rt in @rt_nrt
691  * errno of failure
692  */
693 static int
694 handle_rtm_get(struct rt_addrinfo *info, u_int fibnum,
695     struct rt_msghdr *rtm, struct rib_cmd_info *rc)
696 {
697 	RIB_RLOCK_TRACKER;
698 	struct rib_head *rnh;
699 	struct nhop_object *nh;
700 	sa_family_t saf;
701 
702 	saf = info->rti_info[RTAX_DST]->sa_family;
703 
704 	rnh = rt_tables_get_rnh(fibnum, saf);
705 	if (rnh == NULL)
706 		return (EAFNOSUPPORT);
707 
708 	RIB_RLOCK(rnh);
709 
710 	/*
711 	 * By (implicit) convention host route (one without netmask)
712 	 * means longest-prefix-match request and the route with netmask
713 	 * means exact-match lookup.
714 	 * As cleanup_xaddrs() cleans up info flags&addrs for the /32,/128
715 	 * prefixes, use original data to check for the netmask presence.
716 	 */
717 	if ((rtm->rtm_addrs & RTA_NETMASK) == 0) {
718 		/*
719 		 * Provide longest prefix match for
720 		 * address lookup (no mask).
721 		 * 'route -n get addr'
722 		 */
723 		rc->rc_rt = (struct rtentry *) rnh->rnh_matchaddr(
724 		    info->rti_info[RTAX_DST], &rnh->head);
725 	} else
726 		rc->rc_rt = (struct rtentry *) rnh->rnh_lookup(
727 		    info->rti_info[RTAX_DST],
728 		    info->rti_info[RTAX_NETMASK], &rnh->head);
729 
730 	if (rc->rc_rt == NULL) {
731 		RIB_RUNLOCK(rnh);
732 		return (ESRCH);
733 	}
734 
735 	nh = select_nhop(rt_get_raw_nhop(rc->rc_rt), info->rti_info[RTAX_GATEWAY]);
736 	if (nh == NULL) {
737 		RIB_RUNLOCK(rnh);
738 		return (ESRCH);
739 	}
740 	/*
741 	 * If performing proxied L2 entry insertion, and
742 	 * the actual PPP host entry is found, perform
743 	 * another search to retrieve the prefix route of
744 	 * the local end point of the PPP link.
745 	 * TODO: move this logic to userland.
746 	 */
747 	if (rtm->rtm_flags & RTF_ANNOUNCE) {
748 		struct sockaddr_storage laddr;
749 
750 		if (nh->nh_ifp != NULL &&
751 		    nh->nh_ifp->if_type == IFT_PROPVIRTUAL) {
752 			struct ifaddr *ifa;
753 
754 			ifa = ifa_ifwithnet(info->rti_info[RTAX_DST], 1,
755 					RT_ALL_FIBS);
756 			if (ifa != NULL)
757 				rt_maskedcopy(ifa->ifa_addr,
758 					      (struct sockaddr *)&laddr,
759 					      ifa->ifa_netmask);
760 		} else
761 			rt_maskedcopy(nh->nh_ifa->ifa_addr,
762 				      (struct sockaddr *)&laddr,
763 				      nh->nh_ifa->ifa_netmask);
764 		/*
765 		 * refactor rt and no lock operation necessary
766 		 */
767 		rc->rc_rt = (struct rtentry *)rnh->rnh_matchaddr(
768 		    (struct sockaddr *)&laddr, &rnh->head);
769 		if (rc->rc_rt == NULL) {
770 			RIB_RUNLOCK(rnh);
771 			return (ESRCH);
772 		}
773 		nh = select_nhop(rt_get_raw_nhop(rc->rc_rt), info->rti_info[RTAX_GATEWAY]);
774 		if (nh == NULL) {
775 			RIB_RUNLOCK(rnh);
776 			return (ESRCH);
777 		}
778 	}
779 	rc->rc_nh_new = nh;
780 	rc->rc_nh_weight = rc->rc_rt->rt_weight;
781 	RIB_RUNLOCK(rnh);
782 
783 	return (0);
784 }
785 
786 static void
787 init_sockaddrs_family(int family, struct sockaddr *dst, struct sockaddr *mask)
788 {
789 #ifdef INET
790 	if (family == AF_INET) {
791 		struct sockaddr_in *dst4 = (struct sockaddr_in *)dst;
792 		struct sockaddr_in *mask4 = (struct sockaddr_in *)mask;
793 
794 		bzero(dst4, sizeof(struct sockaddr_in));
795 		bzero(mask4, sizeof(struct sockaddr_in));
796 
797 		dst4->sin_family = AF_INET;
798 		dst4->sin_len = sizeof(struct sockaddr_in);
799 		mask4->sin_family = AF_INET;
800 		mask4->sin_len = sizeof(struct sockaddr_in);
801 	}
802 #endif
803 #ifdef INET6
804 	if (family == AF_INET6) {
805 		struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst;
806 		struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *)mask;
807 
808 		bzero(dst6, sizeof(struct sockaddr_in6));
809 		bzero(mask6, sizeof(struct sockaddr_in6));
810 
811 		dst6->sin6_family = AF_INET6;
812 		dst6->sin6_len = sizeof(struct sockaddr_in6);
813 		mask6->sin6_family = AF_INET6;
814 		mask6->sin6_len = sizeof(struct sockaddr_in6);
815 	}
816 #endif
817 }
818 
819 static void
820 export_rtaddrs(const struct rtentry *rt, struct sockaddr *dst,
821     struct sockaddr *mask)
822 {
823 #ifdef INET
824 	if (dst->sa_family == AF_INET) {
825 		struct sockaddr_in *dst4 = (struct sockaddr_in *)dst;
826 		struct sockaddr_in *mask4 = (struct sockaddr_in *)mask;
827 		uint32_t scopeid = 0;
828 		rt_get_inet_prefix_pmask(rt, &dst4->sin_addr, &mask4->sin_addr,
829 		    &scopeid);
830 		return;
831 	}
832 #endif
833 #ifdef INET6
834 	if (dst->sa_family == AF_INET6) {
835 		struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst;
836 		struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *)mask;
837 		uint32_t scopeid = 0;
838 		rt_get_inet6_prefix_pmask(rt, &dst6->sin6_addr,
839 		    &mask6->sin6_addr, &scopeid);
840 		dst6->sin6_scope_id = scopeid;
841 		return;
842 	}
843 #endif
844 }
845 
846 static int
847 update_rtm_from_info(struct rt_addrinfo *info, struct rt_msghdr **prtm,
848     int alloc_len)
849 {
850 	struct rt_msghdr *rtm, *orig_rtm = NULL;
851 	struct walkarg w;
852 	int len;
853 
854 	rtm = *prtm;
855 	/* Check if we need to realloc storage */
856 	rtsock_msg_buffer(rtm->rtm_type, info, NULL, &len);
857 	if (len > alloc_len) {
858 		struct rt_msghdr *tmp_rtm;
859 
860 		tmp_rtm = malloc(len, M_TEMP, M_NOWAIT);
861 		if (tmp_rtm == NULL)
862 			return (ENOBUFS);
863 		bcopy(rtm, tmp_rtm, rtm->rtm_msglen);
864 		orig_rtm = rtm;
865 		rtm = tmp_rtm;
866 		alloc_len = len;
867 
868 		/*
869 		 * Delay freeing original rtm as info contains
870 		 * data referencing it.
871 		 */
872 	}
873 
874 	w.w_tmem = (caddr_t)rtm;
875 	w.w_tmemsize = alloc_len;
876 	rtsock_msg_buffer(rtm->rtm_type, info, &w, &len);
877 	rtm->rtm_addrs = info->rti_addrs;
878 
879 	if (orig_rtm != NULL)
880 		free(orig_rtm, M_TEMP);
881 	*prtm = rtm;
882 	return (0);
883 }
884 
885 
886 /*
887  * Update sockaddrs, flags, etc in @prtm based on @rc data.
888  * rtm can be reallocated.
889  *
890  * Returns 0 on success, along with pointer to (potentially reallocated)
891  *  rtm.
892  *
893  */
894 static int
895 update_rtm_from_rc(struct rt_addrinfo *info, struct rt_msghdr **prtm,
896     int alloc_len, struct rib_cmd_info *rc, struct nhop_object *nh)
897 {
898 	union sockaddr_union saun;
899 	struct rt_msghdr *rtm;
900 	struct ifnet *ifp;
901 	int error;
902 
903 	rtm = *prtm;
904 	union sockaddr_union sa_dst, sa_mask;
905 	int family = info->rti_info[RTAX_DST]->sa_family;
906 	init_sockaddrs_family(family, &sa_dst.sa, &sa_mask.sa);
907 	export_rtaddrs(rc->rc_rt, &sa_dst.sa, &sa_mask.sa);
908 
909 	info->rti_info[RTAX_DST] = &sa_dst.sa;
910 	info->rti_info[RTAX_NETMASK] = rt_is_host(rc->rc_rt) ? NULL : &sa_mask.sa;
911 	info->rti_info[RTAX_GATEWAY] = &nh->gw_sa;
912 	info->rti_info[RTAX_GENMASK] = 0;
913 	ifp = nh->nh_ifp;
914 	if (rtm->rtm_addrs & (RTA_IFP | RTA_IFA)) {
915 		if (ifp) {
916 			info->rti_info[RTAX_IFP] =
917 			    ifp->if_addr->ifa_addr;
918 			error = rtm_get_jailed(info, ifp, nh,
919 			    &saun, curthread->td_ucred);
920 			if (error != 0)
921 				return (error);
922 			if (ifp->if_flags & IFF_POINTOPOINT)
923 				info->rti_info[RTAX_BRD] =
924 				    nh->nh_ifa->ifa_dstaddr;
925 			rtm->rtm_index = ifp->if_index;
926 		} else {
927 			info->rti_info[RTAX_IFP] = NULL;
928 			info->rti_info[RTAX_IFA] = NULL;
929 		}
930 	} else if (ifp != NULL)
931 		rtm->rtm_index = ifp->if_index;
932 
933 	if ((error = update_rtm_from_info(info, prtm, alloc_len)) != 0)
934 		return (error);
935 
936 	rtm = *prtm;
937 	rtm->rtm_flags = rc->rc_rt->rte_flags | nhop_get_rtflags(nh);
938 	if (rtm->rtm_flags & RTF_GWFLAG_COMPAT)
939 		rtm->rtm_flags = RTF_GATEWAY |
940 			(rtm->rtm_flags & ~RTF_GWFLAG_COMPAT);
941 	rt_getmetrics(rc->rc_rt, nh, &rtm->rtm_rmx);
942 	rtm->rtm_rmx.rmx_weight = rc->rc_nh_weight;
943 
944 	return (0);
945 }
946 
947 #ifdef ROUTE_MPATH
948 static void
949 save_del_notification(struct rib_cmd_info *rc, void *_cbdata)
950 {
951 	struct rib_cmd_info *rc_new = (struct rib_cmd_info *)_cbdata;
952 
953 	if (rc->rc_cmd == RTM_DELETE)
954 		*rc_new = *rc;
955 }
956 
957 static void
958 save_add_notification(struct rib_cmd_info *rc, void *_cbdata)
959 {
960 	struct rib_cmd_info *rc_new = (struct rib_cmd_info *)_cbdata;
961 
962 	if (rc->rc_cmd == RTM_ADD)
963 		*rc_new = *rc;
964 }
965 #endif
966 
967 #if defined(INET6) || defined(INET)
968 static struct sockaddr *
969 alloc_sockaddr_aligned(struct linear_buffer *lb, int len)
970 {
971 	len = roundup2(len, sizeof(uint64_t));
972 	if (lb->offset + len > lb->size)
973 		return (NULL);
974 	struct sockaddr *sa = (struct sockaddr *)(lb->base + lb->offset);
975 	lb->offset += len;
976 	return (sa);
977 }
978 #endif
979 
980 static int
981 rts_send(struct socket *so, int flags, struct mbuf *m,
982     struct sockaddr *nam, struct mbuf *control, struct thread *td)
983 {
984 	struct rt_msghdr *rtm = NULL;
985 	struct rt_addrinfo info;
986 	struct epoch_tracker et;
987 #ifdef INET6
988 	struct sockaddr_storage ss;
989 	struct sockaddr_in6 *sin6;
990 	int i, rti_need_deembed = 0;
991 #endif
992 	int alloc_len = 0, len, error = 0, fibnum;
993 	sa_family_t saf = AF_UNSPEC;
994 	struct rib_cmd_info rc;
995 	struct nhop_object *nh;
996 
997 	if ((flags & PRUS_OOB) || control != NULL) {
998 		m_freem(m);
999 		if (control != NULL)
1000 			m_freem(control);
1001 		return (EOPNOTSUPP);
1002 	}
1003 
1004 	fibnum = so->so_fibnum;
1005 #define senderr(e) { error = e; goto flush;}
1006 	if (m == NULL || ((m->m_len < sizeof(long)) &&
1007 		       (m = m_pullup(m, sizeof(long))) == NULL))
1008 		return (ENOBUFS);
1009 	if ((m->m_flags & M_PKTHDR) == 0)
1010 		panic("route_output");
1011 	NET_EPOCH_ENTER(et);
1012 	len = m->m_pkthdr.len;
1013 	if (len < sizeof(*rtm) ||
1014 	    len != mtod(m, struct rt_msghdr *)->rtm_msglen)
1015 		senderr(EINVAL);
1016 
1017 	/*
1018 	 * Most of current messages are in range 200-240 bytes,
1019 	 * minimize possible re-allocation on reply using larger size
1020 	 * buffer aligned on 1k boundaty.
1021 	 */
1022 	alloc_len = roundup2(len, 1024);
1023 	int total_len = alloc_len + SCRATCH_BUFFER_SIZE;
1024 	if ((rtm = malloc(total_len, M_TEMP, M_NOWAIT)) == NULL)
1025 		senderr(ENOBUFS);
1026 
1027 	m_copydata(m, 0, len, (caddr_t)rtm);
1028 	bzero(&info, sizeof(info));
1029 	nh = NULL;
1030 	struct linear_buffer lb = {
1031 		.base = (char *)rtm + alloc_len,
1032 		.size = SCRATCH_BUFFER_SIZE,
1033 	};
1034 
1035 	if (rtm->rtm_version != RTM_VERSION) {
1036 		/* Do not touch message since format is unknown */
1037 		free(rtm, M_TEMP);
1038 		rtm = NULL;
1039 		senderr(EPROTONOSUPPORT);
1040 	}
1041 
1042 	/*
1043 	 * Starting from here, it is possible
1044 	 * to alter original message and insert
1045 	 * caller PID and error value.
1046 	 */
1047 
1048 	if ((error = fill_addrinfo(rtm, len, &lb, fibnum, &info)) != 0) {
1049 		senderr(error);
1050 	}
1051 	/* fill_addringo() embeds scope into IPv6 addresses */
1052 #ifdef INET6
1053 	rti_need_deembed = 1;
1054 #endif
1055 
1056 	saf = info.rti_info[RTAX_DST]->sa_family;
1057 
1058 	/* support for new ARP code */
1059 	if (rtm->rtm_flags & RTF_LLDATA) {
1060 		error = lla_rt_output(rtm, &info);
1061 		goto flush;
1062 	}
1063 
1064 	union sockaddr_union gw_saun;
1065 	int blackhole_flags = rtm->rtm_flags & (RTF_BLACKHOLE|RTF_REJECT);
1066 	if (blackhole_flags != 0) {
1067 		if (blackhole_flags != (RTF_BLACKHOLE | RTF_REJECT))
1068 			error = fill_blackholeinfo(&info, &gw_saun);
1069 		else {
1070 			RTS_PID_LOG(LOG_DEBUG, "both BLACKHOLE and REJECT flags specifiied");
1071 			error = EINVAL;
1072 		}
1073 		if (error != 0)
1074 			senderr(error);
1075 	}
1076 
1077 	switch (rtm->rtm_type) {
1078 	case RTM_ADD:
1079 	case RTM_CHANGE:
1080 		if (rtm->rtm_type == RTM_ADD) {
1081 			if (info.rti_info[RTAX_GATEWAY] == NULL) {
1082 				RTS_PID_LOG(LOG_DEBUG, "RTM_ADD w/o gateway");
1083 				senderr(EINVAL);
1084 			}
1085 		}
1086 		error = rib_action(fibnum, rtm->rtm_type, &info, &rc);
1087 		if (error == 0) {
1088 #ifdef ROUTE_MPATH
1089 			if (NH_IS_NHGRP(rc.rc_nh_new) ||
1090 			    (rc.rc_nh_old && NH_IS_NHGRP(rc.rc_nh_old))) {
1091 				struct rib_cmd_info rc_simple = {};
1092 				rib_decompose_notification(&rc,
1093 				    save_add_notification, (void *)&rc_simple);
1094 				rc = rc_simple;
1095 			}
1096 #endif
1097 			/* nh MAY be empty if RTM_CHANGE request is no-op */
1098 			nh = rc.rc_nh_new;
1099 			if (nh != NULL) {
1100 				rtm->rtm_index = nh->nh_ifp->if_index;
1101 				rtm->rtm_flags = rc.rc_rt->rte_flags | nhop_get_rtflags(nh);
1102 			}
1103 		}
1104 		break;
1105 
1106 	case RTM_DELETE:
1107 		error = rib_action(fibnum, RTM_DELETE, &info, &rc);
1108 		if (error == 0) {
1109 #ifdef ROUTE_MPATH
1110 			if (NH_IS_NHGRP(rc.rc_nh_old) ||
1111 			    (rc.rc_nh_new && NH_IS_NHGRP(rc.rc_nh_new))) {
1112 				struct rib_cmd_info rc_simple = {};
1113 				rib_decompose_notification(&rc,
1114 				    save_del_notification, (void *)&rc_simple);
1115 				rc = rc_simple;
1116 			}
1117 #endif
1118 			nh = rc.rc_nh_old;
1119 		}
1120 		break;
1121 
1122 	case RTM_GET:
1123 		error = handle_rtm_get(&info, fibnum, rtm, &rc);
1124 		if (error != 0)
1125 			senderr(error);
1126 		nh = rc.rc_nh_new;
1127 
1128 		if (!can_export_rte(curthread->td_ucred,
1129 		    info.rti_info[RTAX_NETMASK] == NULL,
1130 		    info.rti_info[RTAX_DST])) {
1131 			senderr(ESRCH);
1132 		}
1133 		break;
1134 
1135 	default:
1136 		senderr(EOPNOTSUPP);
1137 	}
1138 
1139 	if (error == 0 && nh != NULL) {
1140 		error = update_rtm_from_rc(&info, &rtm, alloc_len, &rc, nh);
1141 		/*
1142 		 * Note that some sockaddr pointers may have changed to
1143 		 * point to memory outsize @rtm. Some may be pointing
1144 		 * to the on-stack variables.
1145 		 * Given that, any pointer in @info CANNOT BE USED.
1146 		 */
1147 
1148 		/*
1149 		 * scopeid deembedding has been performed while
1150 		 * writing updated rtm in rtsock_msg_buffer().
1151 		 * With that in mind, skip deembedding procedure below.
1152 		 */
1153 #ifdef INET6
1154 		rti_need_deembed = 0;
1155 #endif
1156 	}
1157 
1158 flush:
1159 	NET_EPOCH_EXIT(et);
1160 
1161 #ifdef INET6
1162 	if (rtm != NULL) {
1163 		if (rti_need_deembed) {
1164 			/* sin6_scope_id is recovered before sending rtm. */
1165 			sin6 = (struct sockaddr_in6 *)&ss;
1166 			for (i = 0; i < RTAX_MAX; i++) {
1167 				if (info.rti_info[i] == NULL)
1168 					continue;
1169 				if (info.rti_info[i]->sa_family != AF_INET6)
1170 					continue;
1171 				bcopy(info.rti_info[i], sin6, sizeof(*sin6));
1172 				if (sa6_recoverscope(sin6) == 0)
1173 					bcopy(sin6, info.rti_info[i],
1174 						    sizeof(*sin6));
1175 			}
1176 			if (update_rtm_from_info(&info, &rtm, alloc_len) != 0) {
1177 				if (error != 0)
1178 					error = ENOBUFS;
1179 			}
1180 		}
1181 	}
1182 #endif
1183 	send_rtm_reply(so, rtm, m, saf, fibnum, error);
1184 
1185 	return (error);
1186 }
1187 
1188 /*
1189  * Sends the prepared reply message in @rtm to all rtsock clients.
1190  * Frees @m and @rtm.
1191  *
1192  */
1193 static void
1194 send_rtm_reply(struct socket *so, struct rt_msghdr *rtm, struct mbuf *m,
1195     sa_family_t saf, u_int fibnum, int rtm_errno)
1196 {
1197 	struct rcb *rcb = NULL;
1198 
1199 	/*
1200 	 * Check to see if we don't want our own messages.
1201 	 */
1202 	if ((so->so_options & SO_USELOOPBACK) == 0) {
1203 		if (V_route_cb.any_count <= 1) {
1204 			if (rtm != NULL)
1205 				free(rtm, M_TEMP);
1206 			m_freem(m);
1207 			return;
1208 		}
1209 		/* There is another listener, so construct message */
1210 		rcb = so->so_pcb;
1211 	}
1212 
1213 	if (rtm != NULL) {
1214 		if (rtm_errno!= 0)
1215 			rtm->rtm_errno = rtm_errno;
1216 		else
1217 			rtm->rtm_flags |= RTF_DONE;
1218 
1219 		m_copyback(m, 0, rtm->rtm_msglen, (caddr_t)rtm);
1220 		if (m->m_pkthdr.len < rtm->rtm_msglen) {
1221 			m_freem(m);
1222 			m = NULL;
1223 		} else if (m->m_pkthdr.len > rtm->rtm_msglen)
1224 			m_adj(m, rtm->rtm_msglen - m->m_pkthdr.len);
1225 
1226 		free(rtm, M_TEMP);
1227 	}
1228 	if (m != NULL) {
1229 		M_SETFIB(m, fibnum);
1230 		m->m_flags |= RTS_FILTER_FIB;
1231 		if (rcb) {
1232 			/*
1233 			 * XXX insure we don't get a copy by
1234 			 * invalidating our protocol
1235 			 */
1236 			sa_family_t family = rcb->rcb_family;
1237 			rcb->rcb_family = AF_UNSPEC;
1238 			rt_dispatch(m, saf);
1239 			rcb->rcb_family = family;
1240 		} else
1241 			rt_dispatch(m, saf);
1242 	}
1243 }
1244 
1245 static void
1246 rt_getmetrics(const struct rtentry *rt, const struct nhop_object *nh,
1247     struct rt_metrics *out)
1248 {
1249 
1250 	bzero(out, sizeof(*out));
1251 	out->rmx_mtu = nh->nh_mtu;
1252 	out->rmx_weight = rt->rt_weight;
1253 	out->rmx_nhidx = nhop_get_idx(nh);
1254 	/* Kernel -> userland timebase conversion. */
1255 	out->rmx_expire = nhop_get_expire(nh) ?
1256 	    nhop_get_expire(nh) - time_uptime + time_second : 0;
1257 }
1258 
1259 /*
1260  * Extract the addresses of the passed sockaddrs.
1261  * Do a little sanity checking so as to avoid bad memory references.
1262  * This data is derived straight from userland.
1263  */
1264 static int
1265 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
1266 {
1267 	struct sockaddr *sa;
1268 	int i;
1269 
1270 	for (i = 0; i < RTAX_MAX && cp < cplim; i++) {
1271 		if ((rtinfo->rti_addrs & (1 << i)) == 0)
1272 			continue;
1273 		sa = (struct sockaddr *)cp;
1274 		/*
1275 		 * It won't fit.
1276 		 */
1277 		if (cp + sa->sa_len > cplim) {
1278 			RTS_PID_LOG(LOG_DEBUG, "sa_len too big for sa type %d", i);
1279 			return (EINVAL);
1280 		}
1281 		/*
1282 		 * there are no more.. quit now
1283 		 * If there are more bits, they are in error.
1284 		 * I've seen this. route(1) can evidently generate these.
1285 		 * This causes kernel to core dump.
1286 		 * for compatibility, If we see this, point to a safe address.
1287 		 */
1288 		if (sa->sa_len == 0) {
1289 			rtinfo->rti_info[i] = &sa_zero;
1290 			return (0); /* should be EINVAL but for compat */
1291 		}
1292 		/* accept it */
1293 #ifdef INET6
1294 		if (sa->sa_family == AF_INET6)
1295 			sa6_embedscope((struct sockaddr_in6 *)sa,
1296 			    V_ip6_use_defzone);
1297 #endif
1298 		rtinfo->rti_info[i] = sa;
1299 		cp += SA_SIZE(sa);
1300 	}
1301 	return (0);
1302 }
1303 
1304 #ifdef INET
1305 static inline void
1306 fill_sockaddr_inet(struct sockaddr_in *sin, struct in_addr addr)
1307 {
1308 
1309 	const struct sockaddr_in nsin = {
1310 		.sin_family = AF_INET,
1311 		.sin_len = sizeof(struct sockaddr_in),
1312 		.sin_addr = addr,
1313 	};
1314 	*sin = nsin;
1315 }
1316 #endif
1317 
1318 #ifdef INET6
1319 static inline void
1320 fill_sockaddr_inet6(struct sockaddr_in6 *sin6, const struct in6_addr *addr6,
1321     uint32_t scopeid)
1322 {
1323 
1324 	const struct sockaddr_in6 nsin6 = {
1325 		.sin6_family = AF_INET6,
1326 		.sin6_len = sizeof(struct sockaddr_in6),
1327 		.sin6_addr = *addr6,
1328 		.sin6_scope_id = scopeid,
1329 	};
1330 	*sin6 = nsin6;
1331 }
1332 #endif
1333 
1334 #if defined(INET6) || defined(INET)
1335 /*
1336  * Checks if gateway is suitable for lltable operations.
1337  * Lltable code requires AF_LINK gateway with ifindex
1338  *  and mac address specified.
1339  * Returns 0 on success.
1340  */
1341 static int
1342 cleanup_xaddrs_lladdr(struct rt_addrinfo *info)
1343 {
1344 	struct sockaddr_dl *sdl = (struct sockaddr_dl *)info->rti_info[RTAX_GATEWAY];
1345 
1346 	if (sdl->sdl_family != AF_LINK)
1347 		return (EINVAL);
1348 
1349 	if (sdl->sdl_index == 0) {
1350 		RTS_PID_LOG(LOG_DEBUG, "AF_LINK gateway w/o ifindex");
1351 		return (EINVAL);
1352 	}
1353 
1354 	if (offsetof(struct sockaddr_dl, sdl_data) + sdl->sdl_nlen + sdl->sdl_alen > sdl->sdl_len) {
1355 		RTS_PID_LOG(LOG_DEBUG, "AF_LINK gw: sdl_nlen/sdl_alen too large");
1356 		return (EINVAL);
1357 	}
1358 
1359 	return (0);
1360 }
1361 
1362 static int
1363 cleanup_xaddrs_gateway(struct rt_addrinfo *info, struct linear_buffer *lb)
1364 {
1365 	struct sockaddr *gw = info->rti_info[RTAX_GATEWAY];
1366 	struct sockaddr *sa;
1367 
1368 	if (info->rti_flags & RTF_LLDATA)
1369 		return (cleanup_xaddrs_lladdr(info));
1370 
1371 	switch (gw->sa_family) {
1372 #ifdef INET
1373 	case AF_INET:
1374 		{
1375 			struct sockaddr_in *gw_sin = (struct sockaddr_in *)gw;
1376 
1377 			/* Ensure reads do not go beyoud SA boundary */
1378 			if (SA_SIZE(gw) < offsetof(struct sockaddr_in, sin_zero)) {
1379 				RTS_PID_LOG(LOG_DEBUG, "gateway sin_len too small: %d",
1380 				    gw->sa_len);
1381 				return (EINVAL);
1382 			}
1383 			sa = alloc_sockaddr_aligned(lb, sizeof(struct sockaddr_in));
1384 			if (sa == NULL)
1385 				return (ENOBUFS);
1386 			fill_sockaddr_inet((struct sockaddr_in *)sa, gw_sin->sin_addr);
1387 			info->rti_info[RTAX_GATEWAY] = sa;
1388 		}
1389 		break;
1390 #endif
1391 #ifdef INET6
1392 	case AF_INET6:
1393 		{
1394 			struct sockaddr_in6 *gw_sin6 = (struct sockaddr_in6 *)gw;
1395 			if (gw_sin6->sin6_len < sizeof(struct sockaddr_in6)) {
1396 				RTS_PID_LOG(LOG_DEBUG, "gateway sin6_len too small: %d",
1397 				    gw->sa_len);
1398 				return (EINVAL);
1399 			}
1400 			fill_sockaddr_inet6(gw_sin6, &gw_sin6->sin6_addr, 0);
1401 			break;
1402 		}
1403 #endif
1404 	case AF_LINK:
1405 		{
1406 			struct sockaddr_dl *gw_sdl;
1407 
1408 			size_t sdl_min_len = offsetof(struct sockaddr_dl, sdl_data);
1409 			gw_sdl = (struct sockaddr_dl *)gw;
1410 			if (gw_sdl->sdl_len < sdl_min_len) {
1411 				RTS_PID_LOG(LOG_DEBUG, "gateway sdl_len too small: %d",
1412 				    gw_sdl->sdl_len);
1413 				return (EINVAL);
1414 			}
1415 			sa = alloc_sockaddr_aligned(lb, sizeof(struct sockaddr_dl_short));
1416 			if (sa == NULL)
1417 				return (ENOBUFS);
1418 
1419 			const struct sockaddr_dl_short sdl = {
1420 				.sdl_family = AF_LINK,
1421 				.sdl_len = sizeof(struct sockaddr_dl_short),
1422 				.sdl_index = gw_sdl->sdl_index,
1423 			};
1424 			*((struct sockaddr_dl_short *)sa) = sdl;
1425 			info->rti_info[RTAX_GATEWAY] = sa;
1426 			break;
1427 		}
1428 	}
1429 
1430 	return (0);
1431 }
1432 #endif
1433 
1434 static void
1435 remove_netmask(struct rt_addrinfo *info)
1436 {
1437 	info->rti_info[RTAX_NETMASK] = NULL;
1438 	info->rti_flags |= RTF_HOST;
1439 	info->rti_addrs &= ~RTA_NETMASK;
1440 }
1441 
1442 #ifdef INET
1443 static int
1444 cleanup_xaddrs_inet(struct rt_addrinfo *info, struct linear_buffer *lb)
1445 {
1446 	struct sockaddr_in *dst_sa, *mask_sa;
1447 	const int sa_len = sizeof(struct sockaddr_in);
1448 	struct in_addr dst, mask;
1449 
1450 	/* Check & fixup dst/netmask combination first */
1451 	dst_sa = (struct sockaddr_in *)info->rti_info[RTAX_DST];
1452 	mask_sa = (struct sockaddr_in *)info->rti_info[RTAX_NETMASK];
1453 
1454 	/* Ensure reads do not go beyound the buffer size */
1455 	if (SA_SIZE(dst_sa) < offsetof(struct sockaddr_in, sin_zero)) {
1456 		RTS_PID_LOG(LOG_DEBUG, "prefix dst sin_len too small: %d",
1457 		    dst_sa->sin_len);
1458 		return (EINVAL);
1459 	}
1460 
1461 	if ((mask_sa != NULL) && mask_sa->sin_len < sizeof(struct sockaddr_in)) {
1462 		/*
1463 		 * Some older routing software encode mask length into the
1464 		 * sin_len, thus resulting in "truncated" sockaddr.
1465 		 */
1466 		int len = mask_sa->sin_len - offsetof(struct sockaddr_in, sin_addr);
1467 		if (len >= 0) {
1468 			mask.s_addr = 0;
1469 			if (len > sizeof(struct in_addr))
1470 				len = sizeof(struct in_addr);
1471 			memcpy(&mask, &mask_sa->sin_addr, len);
1472 		} else {
1473 			RTS_PID_LOG(LOG_DEBUG, "prefix mask sin_len too small: %d",
1474 			    mask_sa->sin_len);
1475 			return (EINVAL);
1476 		}
1477 	} else
1478 		mask.s_addr = mask_sa ? mask_sa->sin_addr.s_addr : INADDR_BROADCAST;
1479 
1480 	dst.s_addr = htonl(ntohl(dst_sa->sin_addr.s_addr) & ntohl(mask.s_addr));
1481 
1482 	/* Construct new "clean" dst/mask sockaddresses */
1483 	if ((dst_sa = (struct sockaddr_in *)alloc_sockaddr_aligned(lb, sa_len)) == NULL)
1484 		return (ENOBUFS);
1485 	fill_sockaddr_inet(dst_sa, dst);
1486 	info->rti_info[RTAX_DST] = (struct sockaddr *)dst_sa;
1487 
1488 	if (mask.s_addr != INADDR_BROADCAST) {
1489 		if ((mask_sa = (struct sockaddr_in *)alloc_sockaddr_aligned(lb, sa_len)) == NULL)
1490 			return (ENOBUFS);
1491 		fill_sockaddr_inet(mask_sa, mask);
1492 		info->rti_info[RTAX_NETMASK] = (struct sockaddr *)mask_sa;
1493 		info->rti_flags &= ~RTF_HOST;
1494 	} else
1495 		remove_netmask(info);
1496 
1497 	/* Check gateway */
1498 	if (info->rti_info[RTAX_GATEWAY] != NULL)
1499 		return (cleanup_xaddrs_gateway(info, lb));
1500 
1501 	return (0);
1502 }
1503 #endif
1504 
1505 #ifdef INET6
1506 static int
1507 cleanup_xaddrs_inet6(struct rt_addrinfo *info, struct linear_buffer *lb)
1508 {
1509 	struct sockaddr *sa;
1510 	struct sockaddr_in6 *dst_sa, *mask_sa;
1511 	struct in6_addr mask, *dst;
1512 	const int sa_len = sizeof(struct sockaddr_in6);
1513 
1514 	/* Check & fixup dst/netmask combination first */
1515 	dst_sa = (struct sockaddr_in6 *)info->rti_info[RTAX_DST];
1516 	mask_sa = (struct sockaddr_in6 *)info->rti_info[RTAX_NETMASK];
1517 
1518 	if (dst_sa->sin6_len < sizeof(struct sockaddr_in6)) {
1519 		RTS_PID_LOG(LOG_DEBUG, "prefix dst sin6_len too small: %d",
1520 		    dst_sa->sin6_len);
1521 		return (EINVAL);
1522 	}
1523 
1524 	if (mask_sa && mask_sa->sin6_len < sizeof(struct sockaddr_in6)) {
1525 		/*
1526 		 * Some older routing software encode mask length into the
1527 		 * sin6_len, thus resulting in "truncated" sockaddr.
1528 		 */
1529 		int len = mask_sa->sin6_len - offsetof(struct sockaddr_in6, sin6_addr);
1530 		if (len >= 0) {
1531 			bzero(&mask, sizeof(mask));
1532 			if (len > sizeof(struct in6_addr))
1533 				len = sizeof(struct in6_addr);
1534 			memcpy(&mask, &mask_sa->sin6_addr, len);
1535 		} else {
1536 			RTS_PID_LOG(LOG_DEBUG, "rtsock: prefix mask sin6_len too small: %d",
1537 			    mask_sa->sin6_len);
1538 			return (EINVAL);
1539 		}
1540 	} else
1541 		mask = mask_sa ? mask_sa->sin6_addr : in6mask128;
1542 
1543 	dst = &dst_sa->sin6_addr;
1544 	IN6_MASK_ADDR(dst, &mask);
1545 
1546 	if ((sa = alloc_sockaddr_aligned(lb, sa_len)) == NULL)
1547 		return (ENOBUFS);
1548 	fill_sockaddr_inet6((struct sockaddr_in6 *)sa, dst, 0);
1549 	info->rti_info[RTAX_DST] = sa;
1550 
1551 	if (!IN6_ARE_ADDR_EQUAL(&mask, &in6mask128)) {
1552 		if ((sa = alloc_sockaddr_aligned(lb, sa_len)) == NULL)
1553 			return (ENOBUFS);
1554 		fill_sockaddr_inet6((struct sockaddr_in6 *)sa, &mask, 0);
1555 		info->rti_info[RTAX_NETMASK] = sa;
1556 		info->rti_flags &= ~RTF_HOST;
1557 	} else
1558 		remove_netmask(info);
1559 
1560 	/* Check gateway */
1561 	if (info->rti_info[RTAX_GATEWAY] != NULL)
1562 		return (cleanup_xaddrs_gateway(info, lb));
1563 
1564 	return (0);
1565 }
1566 #endif
1567 
1568 static int
1569 cleanup_xaddrs(struct rt_addrinfo *info, struct linear_buffer *lb)
1570 {
1571 	int error = EAFNOSUPPORT;
1572 
1573 	if (info->rti_info[RTAX_DST] == NULL) {
1574 		RTS_PID_LOG(LOG_DEBUG, "prefix dst is not set");
1575 		return (EINVAL);
1576 	}
1577 
1578 	if (info->rti_flags & RTF_LLDATA) {
1579 		/*
1580 		 * arp(8)/ndp(8) sends RTA_NETMASK for the associated
1581 		 * prefix along with the actual address in RTA_DST.
1582 		 * Remove netmask to avoid unnecessary address masking.
1583 		 */
1584 		remove_netmask(info);
1585 	}
1586 
1587 	switch (info->rti_info[RTAX_DST]->sa_family) {
1588 #ifdef INET
1589 	case AF_INET:
1590 		error = cleanup_xaddrs_inet(info, lb);
1591 		break;
1592 #endif
1593 #ifdef INET6
1594 	case AF_INET6:
1595 		error = cleanup_xaddrs_inet6(info, lb);
1596 		break;
1597 #endif
1598 	}
1599 
1600 	return (error);
1601 }
1602 
1603 /*
1604  * Fill in @dmask with valid netmask leaving original @smask
1605  * intact. Mostly used with radix netmasks.
1606  */
1607 struct sockaddr *
1608 rtsock_fix_netmask(const struct sockaddr *dst, const struct sockaddr *smask,
1609     struct sockaddr_storage *dmask)
1610 {
1611 	if (dst == NULL || smask == NULL)
1612 		return (NULL);
1613 
1614 	memset(dmask, 0, dst->sa_len);
1615 	memcpy(dmask, smask, smask->sa_len);
1616 	dmask->ss_len = dst->sa_len;
1617 	dmask->ss_family = dst->sa_family;
1618 
1619 	return ((struct sockaddr *)dmask);
1620 }
1621 
1622 /*
1623  * Writes information related to @rtinfo object to newly-allocated mbuf.
1624  * Assumes MCLBYTES is enough to construct any message.
1625  * Used for OS notifications of vaious events (if/ifa announces,etc)
1626  *
1627  * Returns allocated mbuf or NULL on failure.
1628  */
1629 static struct mbuf *
1630 rtsock_msg_mbuf(int type, struct rt_addrinfo *rtinfo)
1631 {
1632 	struct sockaddr_storage ss;
1633 	struct rt_msghdr *rtm;
1634 	struct mbuf *m;
1635 	int i;
1636 	struct sockaddr *sa;
1637 #ifdef INET6
1638 	struct sockaddr_in6 *sin6;
1639 #endif
1640 	int len, dlen;
1641 
1642 	switch (type) {
1643 	case RTM_DELADDR:
1644 	case RTM_NEWADDR:
1645 		len = sizeof(struct ifa_msghdr);
1646 		break;
1647 
1648 	case RTM_DELMADDR:
1649 	case RTM_NEWMADDR:
1650 		len = sizeof(struct ifma_msghdr);
1651 		break;
1652 
1653 	case RTM_IFINFO:
1654 		len = sizeof(struct if_msghdr);
1655 		break;
1656 
1657 	case RTM_IFANNOUNCE:
1658 	case RTM_IEEE80211:
1659 		len = sizeof(struct if_announcemsghdr);
1660 		break;
1661 
1662 	default:
1663 		len = sizeof(struct rt_msghdr);
1664 	}
1665 
1666 	/* XXXGL: can we use MJUMPAGESIZE cluster here? */
1667 	KASSERT(len <= MCLBYTES, ("%s: message too big", __func__));
1668 	if (len > MHLEN)
1669 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1670 	else
1671 		m = m_gethdr(M_NOWAIT, MT_DATA);
1672 	if (m == NULL)
1673 		return (m);
1674 
1675 	m->m_pkthdr.len = m->m_len = len;
1676 	rtm = mtod(m, struct rt_msghdr *);
1677 	bzero((caddr_t)rtm, len);
1678 	for (i = 0; i < RTAX_MAX; i++) {
1679 		if ((sa = rtinfo->rti_info[i]) == NULL)
1680 			continue;
1681 		rtinfo->rti_addrs |= (1 << i);
1682 
1683 		dlen = SA_SIZE(sa);
1684 		KASSERT(dlen <= sizeof(ss),
1685 		    ("%s: sockaddr size overflow", __func__));
1686 		bzero(&ss, sizeof(ss));
1687 		bcopy(sa, &ss, sa->sa_len);
1688 		sa = (struct sockaddr *)&ss;
1689 #ifdef INET6
1690 		if (sa->sa_family == AF_INET6) {
1691 			sin6 = (struct sockaddr_in6 *)sa;
1692 			(void)sa6_recoverscope(sin6);
1693 		}
1694 #endif
1695 		m_copyback(m, len, dlen, (caddr_t)sa);
1696 		len += dlen;
1697 	}
1698 	if (m->m_pkthdr.len != len) {
1699 		m_freem(m);
1700 		return (NULL);
1701 	}
1702 	rtm->rtm_msglen = len;
1703 	rtm->rtm_version = RTM_VERSION;
1704 	rtm->rtm_type = type;
1705 	return (m);
1706 }
1707 
1708 /*
1709  * Writes information related to @rtinfo object to preallocated buffer.
1710  * Stores needed size in @plen. If @w is NULL, calculates size without
1711  * writing.
1712  * Used for sysctl dumps and rtsock answers (RTM_DEL/RTM_GET) generation.
1713  *
1714  * Returns 0 on success.
1715  *
1716  */
1717 static int
1718 rtsock_msg_buffer(int type, struct rt_addrinfo *rtinfo, struct walkarg *w, int *plen)
1719 {
1720 	struct sockaddr_storage ss;
1721 	int len, buflen = 0, dlen, i;
1722 	caddr_t cp = NULL;
1723 	struct rt_msghdr *rtm = NULL;
1724 #ifdef INET6
1725 	struct sockaddr_in6 *sin6;
1726 #endif
1727 #ifdef COMPAT_FREEBSD32
1728 	bool compat32 = false;
1729 #endif
1730 
1731 	switch (type) {
1732 	case RTM_DELADDR:
1733 	case RTM_NEWADDR:
1734 		if (w != NULL && w->w_op == NET_RT_IFLISTL) {
1735 #ifdef COMPAT_FREEBSD32
1736 			if (w->w_req->flags & SCTL_MASK32) {
1737 				len = sizeof(struct ifa_msghdrl32);
1738 				compat32 = true;
1739 			} else
1740 #endif
1741 				len = sizeof(struct ifa_msghdrl);
1742 		} else
1743 			len = sizeof(struct ifa_msghdr);
1744 		break;
1745 
1746 	case RTM_IFINFO:
1747 #ifdef COMPAT_FREEBSD32
1748 		if (w != NULL && w->w_req->flags & SCTL_MASK32) {
1749 			if (w->w_op == NET_RT_IFLISTL)
1750 				len = sizeof(struct if_msghdrl32);
1751 			else
1752 				len = sizeof(struct if_msghdr32);
1753 			compat32 = true;
1754 			break;
1755 		}
1756 #endif
1757 		if (w != NULL && w->w_op == NET_RT_IFLISTL)
1758 			len = sizeof(struct if_msghdrl);
1759 		else
1760 			len = sizeof(struct if_msghdr);
1761 		break;
1762 
1763 	case RTM_NEWMADDR:
1764 		len = sizeof(struct ifma_msghdr);
1765 		break;
1766 
1767 	default:
1768 		len = sizeof(struct rt_msghdr);
1769 	}
1770 
1771 	if (w != NULL) {
1772 		rtm = (struct rt_msghdr *)w->w_tmem;
1773 		buflen = w->w_tmemsize - len;
1774 		cp = (caddr_t)w->w_tmem + len;
1775 	}
1776 
1777 	rtinfo->rti_addrs = 0;
1778 	for (i = 0; i < RTAX_MAX; i++) {
1779 		struct sockaddr *sa;
1780 
1781 		if ((sa = rtinfo->rti_info[i]) == NULL)
1782 			continue;
1783 		rtinfo->rti_addrs |= (1 << i);
1784 #ifdef COMPAT_FREEBSD32
1785 		if (compat32)
1786 			dlen = SA_SIZE32(sa);
1787 		else
1788 #endif
1789 			dlen = SA_SIZE(sa);
1790 		if (cp != NULL && buflen >= dlen) {
1791 			KASSERT(dlen <= sizeof(ss),
1792 			    ("%s: sockaddr size overflow", __func__));
1793 			bzero(&ss, sizeof(ss));
1794 			bcopy(sa, &ss, sa->sa_len);
1795 			sa = (struct sockaddr *)&ss;
1796 #ifdef INET6
1797 			if (sa->sa_family == AF_INET6) {
1798 				sin6 = (struct sockaddr_in6 *)sa;
1799 				(void)sa6_recoverscope(sin6);
1800 			}
1801 #endif
1802 			bcopy((caddr_t)sa, cp, (unsigned)dlen);
1803 			cp += dlen;
1804 			buflen -= dlen;
1805 		} else if (cp != NULL) {
1806 			/*
1807 			 * Buffer too small. Count needed size
1808 			 * and return with error.
1809 			 */
1810 			cp = NULL;
1811 		}
1812 
1813 		len += dlen;
1814 	}
1815 
1816 	if (cp != NULL) {
1817 		dlen = ALIGN(len) - len;
1818 		if (buflen < dlen)
1819 			cp = NULL;
1820 		else {
1821 			bzero(cp, dlen);
1822 			cp += dlen;
1823 			buflen -= dlen;
1824 		}
1825 	}
1826 	len = ALIGN(len);
1827 
1828 	if (cp != NULL) {
1829 		/* fill header iff buffer is large enough */
1830 		rtm->rtm_version = RTM_VERSION;
1831 		rtm->rtm_type = type;
1832 		rtm->rtm_msglen = len;
1833 	}
1834 
1835 	*plen = len;
1836 
1837 	if (w != NULL && cp == NULL)
1838 		return (ENOBUFS);
1839 
1840 	return (0);
1841 }
1842 
1843 /*
1844  * This routine is called to generate a message from the routing
1845  * socket indicating that a redirect has occurred, a routing lookup
1846  * has failed, or that a protocol has detected timeouts to a particular
1847  * destination.
1848  */
1849 void
1850 rt_missmsg_fib(int type, struct rt_addrinfo *rtinfo, int flags, int error,
1851     int fibnum)
1852 {
1853 	struct rt_msghdr *rtm;
1854 	struct mbuf *m;
1855 	struct sockaddr *sa = rtinfo->rti_info[RTAX_DST];
1856 
1857 	if (V_route_cb.any_count == 0)
1858 		return;
1859 	m = rtsock_msg_mbuf(type, rtinfo);
1860 	if (m == NULL)
1861 		return;
1862 
1863 	if (fibnum != RT_ALL_FIBS) {
1864 		KASSERT(fibnum >= 0 && fibnum < rt_numfibs, ("%s: fibnum out "
1865 		    "of range 0 <= %d < %d", __func__, fibnum, rt_numfibs));
1866 		M_SETFIB(m, fibnum);
1867 		m->m_flags |= RTS_FILTER_FIB;
1868 	}
1869 
1870 	rtm = mtod(m, struct rt_msghdr *);
1871 	rtm->rtm_flags = RTF_DONE | flags;
1872 	rtm->rtm_errno = error;
1873 	rtm->rtm_addrs = rtinfo->rti_addrs;
1874 	rt_dispatch(m, sa ? sa->sa_family : AF_UNSPEC);
1875 }
1876 
1877 void
1878 rt_missmsg(int type, struct rt_addrinfo *rtinfo, int flags, int error)
1879 {
1880 
1881 	rt_missmsg_fib(type, rtinfo, flags, error, RT_ALL_FIBS);
1882 }
1883 
1884 /*
1885  * This routine is called to generate a message from the routing
1886  * socket indicating that the status of a network interface has changed.
1887  */
1888 void
1889 rt_ifmsg(struct ifnet *ifp)
1890 {
1891 	struct if_msghdr *ifm;
1892 	struct mbuf *m;
1893 	struct rt_addrinfo info;
1894 
1895 	if (V_route_cb.any_count == 0)
1896 		return;
1897 	bzero((caddr_t)&info, sizeof(info));
1898 	m = rtsock_msg_mbuf(RTM_IFINFO, &info);
1899 	if (m == NULL)
1900 		return;
1901 	ifm = mtod(m, struct if_msghdr *);
1902 	ifm->ifm_index = ifp->if_index;
1903 	ifm->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
1904 	if_data_copy(ifp, &ifm->ifm_data);
1905 	ifm->ifm_addrs = 0;
1906 	rt_dispatch(m, AF_UNSPEC);
1907 }
1908 
1909 /*
1910  * Announce interface address arrival/withdraw.
1911  * Please do not call directly, use rt_addrmsg().
1912  * Assume input data to be valid.
1913  * Returns 0 on success.
1914  */
1915 int
1916 rtsock_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
1917 {
1918 	struct rt_addrinfo info;
1919 	struct sockaddr *sa;
1920 	int ncmd;
1921 	struct mbuf *m;
1922 	struct ifa_msghdr *ifam;
1923 	struct ifnet *ifp = ifa->ifa_ifp;
1924 	struct sockaddr_storage ss;
1925 
1926 	if (V_route_cb.any_count == 0)
1927 		return (0);
1928 
1929 	ncmd = cmd == RTM_ADD ? RTM_NEWADDR : RTM_DELADDR;
1930 
1931 	bzero((caddr_t)&info, sizeof(info));
1932 	info.rti_info[RTAX_IFA] = sa = ifa->ifa_addr;
1933 	info.rti_info[RTAX_IFP] = ifp->if_addr->ifa_addr;
1934 	info.rti_info[RTAX_NETMASK] = rtsock_fix_netmask(
1935 	    info.rti_info[RTAX_IFA], ifa->ifa_netmask, &ss);
1936 	info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
1937 	if ((m = rtsock_msg_mbuf(ncmd, &info)) == NULL)
1938 		return (ENOBUFS);
1939 	ifam = mtod(m, struct ifa_msghdr *);
1940 	ifam->ifam_index = ifp->if_index;
1941 	ifam->ifam_metric = ifa->ifa_ifp->if_metric;
1942 	ifam->ifam_flags = ifa->ifa_flags;
1943 	ifam->ifam_addrs = info.rti_addrs;
1944 
1945 	if (fibnum != RT_ALL_FIBS) {
1946 		M_SETFIB(m, fibnum);
1947 		m->m_flags |= RTS_FILTER_FIB;
1948 	}
1949 
1950 	rt_dispatch(m, sa ? sa->sa_family : AF_UNSPEC);
1951 
1952 	return (0);
1953 }
1954 
1955 /*
1956  * Announce route addition/removal to rtsock based on @rt data.
1957  * Callers are advives to use rt_routemsg() instead of using this
1958  *  function directly.
1959  * Assume @rt data is consistent.
1960  *
1961  * Returns 0 on success.
1962  */
1963 int
1964 rtsock_routemsg(int cmd, struct rtentry *rt, struct nhop_object *nh,
1965     int fibnum)
1966 {
1967 	union sockaddr_union dst, mask;
1968 	struct rt_addrinfo info;
1969 
1970 	if (V_route_cb.any_count == 0)
1971 		return (0);
1972 
1973 	int family = rt_get_family(rt);
1974 	init_sockaddrs_family(family, &dst.sa, &mask.sa);
1975 	export_rtaddrs(rt, &dst.sa, &mask.sa);
1976 
1977 	bzero((caddr_t)&info, sizeof(info));
1978 	info.rti_info[RTAX_DST] = &dst.sa;
1979 	info.rti_info[RTAX_NETMASK] = &mask.sa;
1980 	info.rti_info[RTAX_GATEWAY] = &nh->gw_sa;
1981 	info.rti_flags = rt->rte_flags | nhop_get_rtflags(nh);
1982 	info.rti_ifp = nh->nh_ifp;
1983 
1984 	return (rtsock_routemsg_info(cmd, &info, fibnum));
1985 }
1986 
1987 int
1988 rtsock_routemsg_info(int cmd, struct rt_addrinfo *info, int fibnum)
1989 {
1990 	struct rt_msghdr *rtm;
1991 	struct sockaddr *sa;
1992 	struct mbuf *m;
1993 
1994 	if (V_route_cb.any_count == 0)
1995 		return (0);
1996 
1997 	if (info->rti_flags & RTF_HOST)
1998 		info->rti_info[RTAX_NETMASK] = NULL;
1999 
2000 	m = rtsock_msg_mbuf(cmd, info);
2001 	if (m == NULL)
2002 		return (ENOBUFS);
2003 
2004 	if (fibnum != RT_ALL_FIBS) {
2005 		KASSERT(fibnum >= 0 && fibnum < rt_numfibs, ("%s: fibnum out "
2006 		    "of range 0 <= %d < %d", __func__, fibnum, rt_numfibs));
2007 		M_SETFIB(m, fibnum);
2008 		m->m_flags |= RTS_FILTER_FIB;
2009 	}
2010 
2011 	rtm = mtod(m, struct rt_msghdr *);
2012 	rtm->rtm_addrs = info->rti_addrs;
2013 	if (info->rti_ifp != NULL)
2014 		rtm->rtm_index = info->rti_ifp->if_index;
2015 	/* Add RTF_DONE to indicate command 'completion' required by API */
2016 	info->rti_flags |= RTF_DONE;
2017 	/* Reported routes has to be up */
2018 	if (cmd == RTM_ADD || cmd == RTM_CHANGE)
2019 		info->rti_flags |= RTF_UP;
2020 	rtm->rtm_flags = info->rti_flags;
2021 
2022 	sa = info->rti_info[RTAX_DST];
2023 	rt_dispatch(m, sa ? sa->sa_family : AF_UNSPEC);
2024 
2025 	return (0);
2026 }
2027 
2028 /*
2029  * This is the analogue to the rt_newaddrmsg which performs the same
2030  * function but for multicast group memberhips.  This is easier since
2031  * there is no route state to worry about.
2032  */
2033 void
2034 rt_newmaddrmsg(int cmd, struct ifmultiaddr *ifma)
2035 {
2036 	struct rt_addrinfo info;
2037 	struct mbuf *m = NULL;
2038 	struct ifnet *ifp = ifma->ifma_ifp;
2039 	struct ifma_msghdr *ifmam;
2040 
2041 	if (V_route_cb.any_count == 0)
2042 		return;
2043 
2044 	bzero((caddr_t)&info, sizeof(info));
2045 	info.rti_info[RTAX_IFA] = ifma->ifma_addr;
2046 	if (ifp && ifp->if_addr)
2047 		info.rti_info[RTAX_IFP] = ifp->if_addr->ifa_addr;
2048 	else
2049 		info.rti_info[RTAX_IFP] = NULL;
2050 	/*
2051 	 * If a link-layer address is present, present it as a ``gateway''
2052 	 * (similarly to how ARP entries, e.g., are presented).
2053 	 */
2054 	info.rti_info[RTAX_GATEWAY] = ifma->ifma_lladdr;
2055 	m = rtsock_msg_mbuf(cmd, &info);
2056 	if (m == NULL)
2057 		return;
2058 	ifmam = mtod(m, struct ifma_msghdr *);
2059 	KASSERT(ifp != NULL, ("%s: link-layer multicast address w/o ifp\n",
2060 	    __func__));
2061 	ifmam->ifmam_index = ifp->if_index;
2062 	ifmam->ifmam_addrs = info.rti_addrs;
2063 	rt_dispatch(m, ifma->ifma_addr ? ifma->ifma_addr->sa_family : AF_UNSPEC);
2064 }
2065 
2066 static struct mbuf *
2067 rt_makeifannouncemsg(struct ifnet *ifp, int type, int what,
2068 	struct rt_addrinfo *info)
2069 {
2070 	struct if_announcemsghdr *ifan;
2071 	struct mbuf *m;
2072 
2073 	if (V_route_cb.any_count == 0)
2074 		return NULL;
2075 	bzero((caddr_t)info, sizeof(*info));
2076 	m = rtsock_msg_mbuf(type, info);
2077 	if (m != NULL) {
2078 		ifan = mtod(m, struct if_announcemsghdr *);
2079 		ifan->ifan_index = ifp->if_index;
2080 		strlcpy(ifan->ifan_name, ifp->if_xname,
2081 			sizeof(ifan->ifan_name));
2082 		ifan->ifan_what = what;
2083 	}
2084 	return m;
2085 }
2086 
2087 /*
2088  * This is called to generate routing socket messages indicating
2089  * IEEE80211 wireless events.
2090  * XXX we piggyback on the RTM_IFANNOUNCE msg format in a clumsy way.
2091  */
2092 void
2093 rt_ieee80211msg(struct ifnet *ifp, int what, void *data, size_t data_len)
2094 {
2095 	struct mbuf *m;
2096 	struct rt_addrinfo info;
2097 
2098 	m = rt_makeifannouncemsg(ifp, RTM_IEEE80211, what, &info);
2099 	if (m != NULL) {
2100 		/*
2101 		 * Append the ieee80211 data.  Try to stick it in the
2102 		 * mbuf containing the ifannounce msg; otherwise allocate
2103 		 * a new mbuf and append.
2104 		 *
2105 		 * NB: we assume m is a single mbuf.
2106 		 */
2107 		if (data_len > M_TRAILINGSPACE(m)) {
2108 			struct mbuf *n = m_get(M_NOWAIT, MT_DATA);
2109 			if (n == NULL) {
2110 				m_freem(m);
2111 				return;
2112 			}
2113 			bcopy(data, mtod(n, void *), data_len);
2114 			n->m_len = data_len;
2115 			m->m_next = n;
2116 		} else if (data_len > 0) {
2117 			bcopy(data, mtod(m, u_int8_t *) + m->m_len, data_len);
2118 			m->m_len += data_len;
2119 		}
2120 		if (m->m_flags & M_PKTHDR)
2121 			m->m_pkthdr.len += data_len;
2122 		mtod(m, struct if_announcemsghdr *)->ifan_msglen += data_len;
2123 		rt_dispatch(m, AF_UNSPEC);
2124 	}
2125 }
2126 
2127 /*
2128  * This is called to generate routing socket messages indicating
2129  * network interface arrival and departure.
2130  */
2131 static void
2132 rt_ifannouncemsg(struct ifnet *ifp, int what)
2133 {
2134 	struct mbuf *m;
2135 	struct rt_addrinfo info;
2136 
2137 	m = rt_makeifannouncemsg(ifp, RTM_IFANNOUNCE, what, &info);
2138 	if (m != NULL)
2139 		rt_dispatch(m, AF_UNSPEC);
2140 }
2141 
2142 static void
2143 rt_dispatch(struct mbuf *m, sa_family_t saf)
2144 {
2145 
2146 	M_ASSERTPKTHDR(m);
2147 
2148 	m->m_rtsock_family = saf;
2149 	if (V_loif)
2150 		m->m_pkthdr.rcvif = V_loif;
2151 	else {
2152 		m_freem(m);
2153 		return;
2154 	}
2155 	netisr_queue(NETISR_ROUTE, m);	/* mbuf is free'd on failure. */
2156 }
2157 
2158 /*
2159  * Checks if rte can be exported w.r.t jails/vnets.
2160  *
2161  * Returns true if it can, false otherwise.
2162  */
2163 static bool
2164 can_export_rte(struct ucred *td_ucred, bool rt_is_host,
2165     const struct sockaddr *rt_dst)
2166 {
2167 
2168 	if ((!rt_is_host) ? jailed_without_vnet(td_ucred)
2169 	    : prison_if(td_ucred, rt_dst) != 0)
2170 		return (false);
2171 	return (true);
2172 }
2173 
2174 
2175 /*
2176  * This is used in dumping the kernel table via sysctl().
2177  */
2178 static int
2179 sysctl_dumpentry(struct rtentry *rt, void *vw)
2180 {
2181 	struct walkarg *w = vw;
2182 	struct nhop_object *nh;
2183 
2184 	NET_EPOCH_ASSERT();
2185 
2186 	export_rtaddrs(rt, w->dst, w->mask);
2187 	if (!can_export_rte(w->w_req->td->td_ucred, rt_is_host(rt), w->dst))
2188 		return (0);
2189 	nh = rt_get_raw_nhop(rt);
2190 #ifdef ROUTE_MPATH
2191 	if (NH_IS_NHGRP(nh)) {
2192 		const struct weightened_nhop *wn;
2193 		uint32_t num_nhops;
2194 		int error;
2195 		wn = nhgrp_get_nhops((struct nhgrp_object *)nh, &num_nhops);
2196 		for (int i = 0; i < num_nhops; i++) {
2197 			error = sysctl_dumpnhop(rt, wn[i].nh, wn[i].weight, w);
2198 			if (error != 0)
2199 				return (error);
2200 		}
2201 	} else
2202 #endif
2203 		sysctl_dumpnhop(rt, nh, rt->rt_weight, w);
2204 
2205 	return (0);
2206 }
2207 
2208 
2209 static int
2210 sysctl_dumpnhop(struct rtentry *rt, struct nhop_object *nh, uint32_t weight,
2211     struct walkarg *w)
2212 {
2213 	struct rt_addrinfo info;
2214 	int error = 0, size;
2215 	uint32_t rtflags;
2216 
2217 	rtflags = nhop_get_rtflags(nh);
2218 
2219 	if (w->w_op == NET_RT_FLAGS && !(rtflags & w->w_arg))
2220 		return (0);
2221 
2222 	bzero((caddr_t)&info, sizeof(info));
2223 	info.rti_info[RTAX_DST] = w->dst;
2224 	info.rti_info[RTAX_GATEWAY] = &nh->gw_sa;
2225 	info.rti_info[RTAX_NETMASK] = (rtflags & RTF_HOST) ? NULL : w->mask;
2226 	info.rti_info[RTAX_GENMASK] = 0;
2227 	if (nh->nh_ifp && !(nh->nh_ifp->if_flags & IFF_DYING)) {
2228 		info.rti_info[RTAX_IFP] = nh->nh_ifp->if_addr->ifa_addr;
2229 		info.rti_info[RTAX_IFA] = nh->nh_ifa->ifa_addr;
2230 		if (nh->nh_ifp->if_flags & IFF_POINTOPOINT)
2231 			info.rti_info[RTAX_BRD] = nh->nh_ifa->ifa_dstaddr;
2232 	}
2233 	if ((error = rtsock_msg_buffer(RTM_GET, &info, w, &size)) != 0)
2234 		return (error);
2235 	if (w->w_req && w->w_tmem) {
2236 		struct rt_msghdr *rtm = (struct rt_msghdr *)w->w_tmem;
2237 
2238 		bzero(&rtm->rtm_index,
2239 		    sizeof(*rtm) - offsetof(struct rt_msghdr, rtm_index));
2240 
2241 		/*
2242 		 * rte flags may consist of RTF_HOST (duplicated in nhop rtflags)
2243 		 * and RTF_UP (if entry is linked, which is always true here).
2244 		 * Given that, use nhop rtflags & add RTF_UP.
2245 		 */
2246 		rtm->rtm_flags = rtflags | RTF_UP;
2247 		if (rtm->rtm_flags & RTF_GWFLAG_COMPAT)
2248 			rtm->rtm_flags = RTF_GATEWAY |
2249 				(rtm->rtm_flags & ~RTF_GWFLAG_COMPAT);
2250 		rt_getmetrics(rt, nh, &rtm->rtm_rmx);
2251 		rtm->rtm_rmx.rmx_weight = weight;
2252 		rtm->rtm_index = nh->nh_ifp->if_index;
2253 		rtm->rtm_addrs = info.rti_addrs;
2254 		error = SYSCTL_OUT(w->w_req, (caddr_t)rtm, size);
2255 		return (error);
2256 	}
2257 	return (error);
2258 }
2259 
2260 static int
2261 sysctl_iflist_ifml(struct ifnet *ifp, const struct if_data *src_ifd,
2262     struct rt_addrinfo *info, struct walkarg *w, int len)
2263 {
2264 	struct if_msghdrl *ifm;
2265 	struct if_data *ifd;
2266 
2267 	ifm = (struct if_msghdrl *)w->w_tmem;
2268 
2269 #ifdef COMPAT_FREEBSD32
2270 	if (w->w_req->flags & SCTL_MASK32) {
2271 		struct if_msghdrl32 *ifm32;
2272 
2273 		ifm32 = (struct if_msghdrl32 *)ifm;
2274 		ifm32->ifm_addrs = info->rti_addrs;
2275 		ifm32->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2276 		ifm32->ifm_index = ifp->if_index;
2277 		ifm32->_ifm_spare1 = 0;
2278 		ifm32->ifm_len = sizeof(*ifm32);
2279 		ifm32->ifm_data_off = offsetof(struct if_msghdrl32, ifm_data);
2280 		ifm32->_ifm_spare2 = 0;
2281 		ifd = &ifm32->ifm_data;
2282 	} else
2283 #endif
2284 	{
2285 		ifm->ifm_addrs = info->rti_addrs;
2286 		ifm->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2287 		ifm->ifm_index = ifp->if_index;
2288 		ifm->_ifm_spare1 = 0;
2289 		ifm->ifm_len = sizeof(*ifm);
2290 		ifm->ifm_data_off = offsetof(struct if_msghdrl, ifm_data);
2291 		ifm->_ifm_spare2 = 0;
2292 		ifd = &ifm->ifm_data;
2293 	}
2294 
2295 	memcpy(ifd, src_ifd, sizeof(*ifd));
2296 
2297 	return (SYSCTL_OUT(w->w_req, (caddr_t)ifm, len));
2298 }
2299 
2300 static int
2301 sysctl_iflist_ifm(struct ifnet *ifp, const struct if_data *src_ifd,
2302     struct rt_addrinfo *info, struct walkarg *w, int len)
2303 {
2304 	struct if_msghdr *ifm;
2305 	struct if_data *ifd;
2306 
2307 	ifm = (struct if_msghdr *)w->w_tmem;
2308 
2309 #ifdef COMPAT_FREEBSD32
2310 	if (w->w_req->flags & SCTL_MASK32) {
2311 		struct if_msghdr32 *ifm32;
2312 
2313 		ifm32 = (struct if_msghdr32 *)ifm;
2314 		ifm32->ifm_addrs = info->rti_addrs;
2315 		ifm32->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2316 		ifm32->ifm_index = ifp->if_index;
2317 		ifm32->_ifm_spare1 = 0;
2318 		ifd = &ifm32->ifm_data;
2319 	} else
2320 #endif
2321 	{
2322 		ifm->ifm_addrs = info->rti_addrs;
2323 		ifm->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2324 		ifm->ifm_index = ifp->if_index;
2325 		ifm->_ifm_spare1 = 0;
2326 		ifd = &ifm->ifm_data;
2327 	}
2328 
2329 	memcpy(ifd, src_ifd, sizeof(*ifd));
2330 
2331 	return (SYSCTL_OUT(w->w_req, (caddr_t)ifm, len));
2332 }
2333 
2334 static int
2335 sysctl_iflist_ifaml(struct ifaddr *ifa, struct rt_addrinfo *info,
2336     struct walkarg *w, int len)
2337 {
2338 	struct ifa_msghdrl *ifam;
2339 	struct if_data *ifd;
2340 
2341 	ifam = (struct ifa_msghdrl *)w->w_tmem;
2342 
2343 #ifdef COMPAT_FREEBSD32
2344 	if (w->w_req->flags & SCTL_MASK32) {
2345 		struct ifa_msghdrl32 *ifam32;
2346 
2347 		ifam32 = (struct ifa_msghdrl32 *)ifam;
2348 		ifam32->ifam_addrs = info->rti_addrs;
2349 		ifam32->ifam_flags = ifa->ifa_flags;
2350 		ifam32->ifam_index = ifa->ifa_ifp->if_index;
2351 		ifam32->_ifam_spare1 = 0;
2352 		ifam32->ifam_len = sizeof(*ifam32);
2353 		ifam32->ifam_data_off =
2354 		    offsetof(struct ifa_msghdrl32, ifam_data);
2355 		ifam32->ifam_metric = ifa->ifa_ifp->if_metric;
2356 		ifd = &ifam32->ifam_data;
2357 	} else
2358 #endif
2359 	{
2360 		ifam->ifam_addrs = info->rti_addrs;
2361 		ifam->ifam_flags = ifa->ifa_flags;
2362 		ifam->ifam_index = ifa->ifa_ifp->if_index;
2363 		ifam->_ifam_spare1 = 0;
2364 		ifam->ifam_len = sizeof(*ifam);
2365 		ifam->ifam_data_off = offsetof(struct ifa_msghdrl, ifam_data);
2366 		ifam->ifam_metric = ifa->ifa_ifp->if_metric;
2367 		ifd = &ifam->ifam_data;
2368 	}
2369 
2370 	bzero(ifd, sizeof(*ifd));
2371 	ifd->ifi_datalen = sizeof(struct if_data);
2372 	ifd->ifi_ipackets = counter_u64_fetch(ifa->ifa_ipackets);
2373 	ifd->ifi_opackets = counter_u64_fetch(ifa->ifa_opackets);
2374 	ifd->ifi_ibytes = counter_u64_fetch(ifa->ifa_ibytes);
2375 	ifd->ifi_obytes = counter_u64_fetch(ifa->ifa_obytes);
2376 
2377 	/* Fixup if_data carp(4) vhid. */
2378 	if (carp_get_vhid_p != NULL)
2379 		ifd->ifi_vhid = (*carp_get_vhid_p)(ifa);
2380 
2381 	return (SYSCTL_OUT(w->w_req, w->w_tmem, len));
2382 }
2383 
2384 static int
2385 sysctl_iflist_ifam(struct ifaddr *ifa, struct rt_addrinfo *info,
2386     struct walkarg *w, int len)
2387 {
2388 	struct ifa_msghdr *ifam;
2389 
2390 	ifam = (struct ifa_msghdr *)w->w_tmem;
2391 	ifam->ifam_addrs = info->rti_addrs;
2392 	ifam->ifam_flags = ifa->ifa_flags;
2393 	ifam->ifam_index = ifa->ifa_ifp->if_index;
2394 	ifam->_ifam_spare1 = 0;
2395 	ifam->ifam_metric = ifa->ifa_ifp->if_metric;
2396 
2397 	return (SYSCTL_OUT(w->w_req, w->w_tmem, len));
2398 }
2399 
2400 static int
2401 sysctl_iflist(int af, struct walkarg *w)
2402 {
2403 	struct ifnet *ifp;
2404 	struct ifaddr *ifa;
2405 	struct if_data ifd;
2406 	struct rt_addrinfo info;
2407 	int len, error = 0;
2408 	struct sockaddr_storage ss;
2409 
2410 	bzero((caddr_t)&info, sizeof(info));
2411 	bzero(&ifd, sizeof(ifd));
2412 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2413 		if (w->w_arg && w->w_arg != ifp->if_index)
2414 			continue;
2415 		if_data_copy(ifp, &ifd);
2416 		ifa = ifp->if_addr;
2417 		info.rti_info[RTAX_IFP] = ifa->ifa_addr;
2418 		error = rtsock_msg_buffer(RTM_IFINFO, &info, w, &len);
2419 		if (error != 0)
2420 			goto done;
2421 		info.rti_info[RTAX_IFP] = NULL;
2422 		if (w->w_req && w->w_tmem) {
2423 			if (w->w_op == NET_RT_IFLISTL)
2424 				error = sysctl_iflist_ifml(ifp, &ifd, &info, w,
2425 				    len);
2426 			else
2427 				error = sysctl_iflist_ifm(ifp, &ifd, &info, w,
2428 				    len);
2429 			if (error)
2430 				goto done;
2431 		}
2432 		while ((ifa = CK_STAILQ_NEXT(ifa, ifa_link)) != NULL) {
2433 			if (af && af != ifa->ifa_addr->sa_family)
2434 				continue;
2435 			if (prison_if(w->w_req->td->td_ucred,
2436 			    ifa->ifa_addr) != 0)
2437 				continue;
2438 			info.rti_info[RTAX_IFA] = ifa->ifa_addr;
2439 			info.rti_info[RTAX_NETMASK] = rtsock_fix_netmask(
2440 			    ifa->ifa_addr, ifa->ifa_netmask, &ss);
2441 			info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
2442 			error = rtsock_msg_buffer(RTM_NEWADDR, &info, w, &len);
2443 			if (error != 0)
2444 				goto done;
2445 			if (w->w_req && w->w_tmem) {
2446 				if (w->w_op == NET_RT_IFLISTL)
2447 					error = sysctl_iflist_ifaml(ifa, &info,
2448 					    w, len);
2449 				else
2450 					error = sysctl_iflist_ifam(ifa, &info,
2451 					    w, len);
2452 				if (error)
2453 					goto done;
2454 			}
2455 		}
2456 		info.rti_info[RTAX_IFA] = NULL;
2457 		info.rti_info[RTAX_NETMASK] = NULL;
2458 		info.rti_info[RTAX_BRD] = NULL;
2459 	}
2460 done:
2461 	return (error);
2462 }
2463 
2464 static int
2465 sysctl_ifmalist(int af, struct walkarg *w)
2466 {
2467 	struct rt_addrinfo info;
2468 	struct ifaddr *ifa;
2469 	struct ifmultiaddr *ifma;
2470 	struct ifnet *ifp;
2471 	int error, len;
2472 
2473 	NET_EPOCH_ASSERT();
2474 
2475 	error = 0;
2476 	bzero((caddr_t)&info, sizeof(info));
2477 
2478 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2479 		if (w->w_arg && w->w_arg != ifp->if_index)
2480 			continue;
2481 		ifa = ifp->if_addr;
2482 		info.rti_info[RTAX_IFP] = ifa ? ifa->ifa_addr : NULL;
2483 		CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2484 			if (af && af != ifma->ifma_addr->sa_family)
2485 				continue;
2486 			if (prison_if(w->w_req->td->td_ucred,
2487 			    ifma->ifma_addr) != 0)
2488 				continue;
2489 			info.rti_info[RTAX_IFA] = ifma->ifma_addr;
2490 			info.rti_info[RTAX_GATEWAY] =
2491 			    (ifma->ifma_addr->sa_family != AF_LINK) ?
2492 			    ifma->ifma_lladdr : NULL;
2493 			error = rtsock_msg_buffer(RTM_NEWMADDR, &info, w, &len);
2494 			if (error != 0)
2495 				break;
2496 			if (w->w_req && w->w_tmem) {
2497 				struct ifma_msghdr *ifmam;
2498 
2499 				ifmam = (struct ifma_msghdr *)w->w_tmem;
2500 				ifmam->ifmam_index = ifma->ifma_ifp->if_index;
2501 				ifmam->ifmam_flags = 0;
2502 				ifmam->ifmam_addrs = info.rti_addrs;
2503 				ifmam->_ifmam_spare1 = 0;
2504 				error = SYSCTL_OUT(w->w_req, w->w_tmem, len);
2505 				if (error != 0)
2506 					break;
2507 			}
2508 		}
2509 		if (error != 0)
2510 			break;
2511 	}
2512 	return (error);
2513 }
2514 
2515 static void
2516 rtable_sysctl_dump(uint32_t fibnum, int family, struct walkarg *w)
2517 {
2518 	union sockaddr_union sa_dst, sa_mask;
2519 
2520 	w->family = family;
2521 	w->dst = (struct sockaddr *)&sa_dst;
2522 	w->mask = (struct sockaddr *)&sa_mask;
2523 
2524 	init_sockaddrs_family(family, w->dst, w->mask);
2525 
2526 	rib_walk(fibnum, family, false, sysctl_dumpentry, w);
2527 }
2528 
2529 static int
2530 sysctl_rtsock(SYSCTL_HANDLER_ARGS)
2531 {
2532 	struct epoch_tracker et;
2533 	int	*name = (int *)arg1;
2534 	u_int	namelen = arg2;
2535 	struct rib_head *rnh = NULL; /* silence compiler. */
2536 	int	i, lim, error = EINVAL;
2537 	int	fib = 0;
2538 	u_char	af;
2539 	struct	walkarg w;
2540 
2541 	if (namelen < 3)
2542 		return (EINVAL);
2543 
2544 	name++;
2545 	namelen--;
2546 	if (req->newptr)
2547 		return (EPERM);
2548 	if (name[1] == NET_RT_DUMP || name[1] == NET_RT_NHOP || name[1] == NET_RT_NHGRP) {
2549 		if (namelen == 3)
2550 			fib = req->td->td_proc->p_fibnum;
2551 		else if (namelen == 4)
2552 			fib = (name[3] == RT_ALL_FIBS) ?
2553 			    req->td->td_proc->p_fibnum : name[3];
2554 		else
2555 			return ((namelen < 3) ? EISDIR : ENOTDIR);
2556 		if (fib < 0 || fib >= rt_numfibs)
2557 			return (EINVAL);
2558 	} else if (namelen != 3)
2559 		return ((namelen < 3) ? EISDIR : ENOTDIR);
2560 	af = name[0];
2561 	if (af > AF_MAX)
2562 		return (EINVAL);
2563 	bzero(&w, sizeof(w));
2564 	w.w_op = name[1];
2565 	w.w_arg = name[2];
2566 	w.w_req = req;
2567 
2568 	error = sysctl_wire_old_buffer(req, 0);
2569 	if (error)
2570 		return (error);
2571 
2572 	/*
2573 	 * Allocate reply buffer in advance.
2574 	 * All rtsock messages has maximum length of u_short.
2575 	 */
2576 	w.w_tmemsize = 65536;
2577 	w.w_tmem = malloc(w.w_tmemsize, M_TEMP, M_WAITOK);
2578 
2579 	NET_EPOCH_ENTER(et);
2580 	switch (w.w_op) {
2581 	case NET_RT_DUMP:
2582 	case NET_RT_FLAGS:
2583 		if (af == 0) {			/* dump all tables */
2584 			i = 1;
2585 			lim = AF_MAX;
2586 		} else				/* dump only one table */
2587 			i = lim = af;
2588 
2589 		/*
2590 		 * take care of llinfo entries, the caller must
2591 		 * specify an AF
2592 		 */
2593 		if (w.w_op == NET_RT_FLAGS &&
2594 		    (w.w_arg == 0 || w.w_arg & RTF_LLINFO)) {
2595 			if (af != 0)
2596 				error = lltable_sysctl_dumparp(af, w.w_req);
2597 			else
2598 				error = EINVAL;
2599 			break;
2600 		}
2601 		/*
2602 		 * take care of routing entries
2603 		 */
2604 		for (error = 0; error == 0 && i <= lim; i++) {
2605 			rnh = rt_tables_get_rnh(fib, i);
2606 			if (rnh != NULL) {
2607 				rtable_sysctl_dump(fib, i, &w);
2608 			} else if (af != 0)
2609 				error = EAFNOSUPPORT;
2610 		}
2611 		break;
2612 	case NET_RT_NHOP:
2613 	case NET_RT_NHGRP:
2614 		/* Allow dumping one specific af/fib at a time */
2615 		if (namelen < 4) {
2616 			error = EINVAL;
2617 			break;
2618 		}
2619 		fib = name[3];
2620 		if (fib < 0 || fib > rt_numfibs) {
2621 			error = EINVAL;
2622 			break;
2623 		}
2624 		rnh = rt_tables_get_rnh(fib, af);
2625 		if (rnh == NULL) {
2626 			error = EAFNOSUPPORT;
2627 			break;
2628 		}
2629 		if (w.w_op == NET_RT_NHOP)
2630 			error = nhops_dump_sysctl(rnh, w.w_req);
2631 		else
2632 #ifdef ROUTE_MPATH
2633 			error = nhgrp_dump_sysctl(rnh, w.w_req);
2634 #else
2635 			error = ENOTSUP;
2636 #endif
2637 		break;
2638 	case NET_RT_IFLIST:
2639 	case NET_RT_IFLISTL:
2640 		error = sysctl_iflist(af, &w);
2641 		break;
2642 
2643 	case NET_RT_IFMALIST:
2644 		error = sysctl_ifmalist(af, &w);
2645 		break;
2646 	}
2647 	NET_EPOCH_EXIT(et);
2648 
2649 	free(w.w_tmem, M_TEMP);
2650 	return (error);
2651 }
2652 
2653 static SYSCTL_NODE(_net, PF_ROUTE, routetable, CTLFLAG_RD | CTLFLAG_MPSAFE,
2654     sysctl_rtsock, "Return route tables and interface/address lists");
2655 
2656 /*
2657  * Definitions of protocols supported in the ROUTE domain.
2658  */
2659 
2660 static struct domain routedomain;		/* or at least forward */
2661 
2662 static struct pr_usrreqs route_usrreqs = {
2663 	.pru_abort =		rts_close,
2664 	.pru_attach =		rts_attach,
2665 	.pru_detach =		rts_detach,
2666 	.pru_send =		rts_send,
2667 	.pru_shutdown =		rts_shutdown,
2668 	.pru_close =		rts_close,
2669 };
2670 
2671 static struct protosw routesw[] = {
2672 {
2673 	.pr_type =		SOCK_RAW,
2674 	.pr_domain =		&routedomain,
2675 	.pr_flags =		PR_ATOMIC|PR_ADDR,
2676 	.pr_usrreqs =		&route_usrreqs
2677 }
2678 };
2679 
2680 static struct domain routedomain = {
2681 	.dom_family =		PF_ROUTE,
2682 	.dom_name =		"route",
2683 	.dom_protosw =		routesw,
2684 	.dom_protoswNPROTOSW =	&routesw[nitems(routesw)]
2685 };
2686 
2687 DOMAIN_SET(route);
2688