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