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