xref: /freebsd/sys/net/rtsock.c (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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 #include "opt_ddb.h"
32 #include "opt_route.h"
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 
36 #include <sys/param.h>
37 #include <sys/jail.h>
38 #include <sys/kernel.h>
39 #include <sys/eventhandler.h>
40 #include <sys/domain.h>
41 #include <sys/lock.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/priv.h>
45 #include <sys/proc.h>
46 #include <sys/protosw.h>
47 #include <sys/rmlock.h>
48 #include <sys/rwlock.h>
49 #include <sys/signalvar.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/systm.h>
54 
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/if_private.h>
58 #include <net/if_dl.h>
59 #include <net/if_llatbl.h>
60 #include <net/if_types.h>
61 #include <net/netisr.h>
62 #include <net/route.h>
63 #include <net/route/route_ctl.h>
64 #include <net/route/route_var.h>
65 #include <net/vnet.h>
66 
67 #include <netinet/in.h>
68 #include <netinet/if_ether.h>
69 #include <netinet/ip_carp.h>
70 #ifdef INET6
71 #include <netinet6/in6_var.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/scope6_var.h>
74 #endif
75 #include <net/route/nhop.h>
76 
77 #define	DEBUG_MOD_NAME	rtsock
78 #define	DEBUG_MAX_LEVEL	LOG_DEBUG
79 #include <net/route/route_debug.h>
80 _DECLARE_DEBUG(LOG_INFO);
81 
82 #ifdef COMPAT_FREEBSD32
83 #include <sys/mount.h>
84 #include <compat/freebsd32/freebsd32.h>
85 
86 struct if_msghdr32 {
87 	uint16_t ifm_msglen;
88 	uint8_t	ifm_version;
89 	uint8_t	ifm_type;
90 	int32_t	ifm_addrs;
91 	int32_t	ifm_flags;
92 	uint16_t ifm_index;
93 	uint16_t _ifm_spare1;
94 	struct	if_data ifm_data;
95 };
96 
97 struct if_msghdrl32 {
98 	uint16_t ifm_msglen;
99 	uint8_t	ifm_version;
100 	uint8_t	ifm_type;
101 	int32_t	ifm_addrs;
102 	int32_t	ifm_flags;
103 	uint16_t ifm_index;
104 	uint16_t _ifm_spare1;
105 	uint16_t ifm_len;
106 	uint16_t ifm_data_off;
107 	uint32_t _ifm_spare2;
108 	struct	if_data ifm_data;
109 };
110 
111 struct ifa_msghdrl32 {
112 	uint16_t ifam_msglen;
113 	uint8_t	ifam_version;
114 	uint8_t	ifam_type;
115 	int32_t	ifam_addrs;
116 	int32_t	ifam_flags;
117 	uint16_t ifam_index;
118 	uint16_t _ifam_spare1;
119 	uint16_t ifam_len;
120 	uint16_t ifam_data_off;
121 	int32_t	ifam_metric;
122 	struct	if_data ifam_data;
123 };
124 
125 #define SA_SIZE32(sa)						\
126     (  (((struct sockaddr *)(sa))->sa_len == 0) ?		\
127 	sizeof(int)		:				\
128 	1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(int) - 1) ) )
129 
130 #endif /* COMPAT_FREEBSD32 */
131 
132 struct linear_buffer {
133 	char		*base;	/* Base allocated memory pointer */
134 	uint32_t	offset;	/* Currently used offset */
135 	uint32_t	size;	/* Total buffer size */
136 };
137 #define	SCRATCH_BUFFER_SIZE	1024
138 
139 #define	RTS_PID_LOG(_l, _fmt, ...)	RT_LOG_##_l(_l, "PID %d: " _fmt, curproc ? curproc->p_pid : 0, ## __VA_ARGS__)
140 
141 MALLOC_DEFINE(M_RTABLE, "routetbl", "routing tables");
142 
143 /* NB: these are not modified */
144 static struct	sockaddr route_src = { 2, PF_ROUTE, };
145 static struct	sockaddr sa_zero   = { sizeof(sa_zero), AF_INET, };
146 
147 /* These are external hooks for CARP. */
148 int	(*carp_get_vhid_p)(struct ifaddr *);
149 
150 /*
151  * Used by rtsock callback code to decide whether to filter the update
152  * notification to a socket bound to a particular FIB.
153  */
154 #define	RTS_FILTER_FIB	M_PROTO8
155 /*
156  * Used to store address family of the notification.
157  */
158 #define	m_rtsock_family	m_pkthdr.PH_loc.eight[0]
159 
160 struct rcb {
161 	LIST_ENTRY(rcb) list;
162 	struct socket	*rcb_socket;
163 	sa_family_t	rcb_family;
164 };
165 
166 typedef struct {
167 	LIST_HEAD(, rcb)	cblist;
168 	int	ip_count;	/* attached w/ AF_INET */
169 	int	ip6_count;	/* attached w/ AF_INET6 */
170 	int	any_count;	/* total attached */
171 } route_cb_t;
172 VNET_DEFINE_STATIC(route_cb_t, route_cb);
173 #define	V_route_cb VNET(route_cb)
174 
175 struct mtx rtsock_mtx;
176 MTX_SYSINIT(rtsock, &rtsock_mtx, "rtsock route_cb lock", MTX_DEF);
177 
178 #define	RTSOCK_LOCK()	mtx_lock(&rtsock_mtx)
179 #define	RTSOCK_UNLOCK()	mtx_unlock(&rtsock_mtx)
180 #define	RTSOCK_LOCK_ASSERT()	mtx_assert(&rtsock_mtx, MA_OWNED)
181 
182 SYSCTL_NODE(_net, OID_AUTO, route, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
183 
184 struct walkarg {
185 	int	family;
186 	int	w_tmemsize;
187 	int	w_op, w_arg;
188 	caddr_t	w_tmem;
189 	struct sysctl_req *w_req;
190 	struct sockaddr *dst;
191 	struct sockaddr *mask;
192 };
193 
194 static void	rts_input(struct mbuf *m);
195 static struct mbuf *rtsock_msg_mbuf(int type, struct rt_addrinfo *rtinfo);
196 static int	rtsock_msg_buffer(int type, struct rt_addrinfo *rtinfo,
197 			struct walkarg *w, int *plen);
198 static int	rt_xaddrs(caddr_t cp, caddr_t cplim,
199 			struct rt_addrinfo *rtinfo);
200 static int	cleanup_xaddrs(struct rt_addrinfo *info, struct linear_buffer *lb);
201 static int	sysctl_dumpentry(struct rtentry *rt, void *vw);
202 static int	sysctl_dumpnhop(struct rtentry *rt, struct nhop_object *nh,
203 			uint32_t weight, struct walkarg *w);
204 static int	sysctl_iflist(int af, struct walkarg *w);
205 static int	sysctl_ifmalist(int af, struct walkarg *w);
206 static void	rt_getmetrics(const struct rtentry *rt,
207 			const struct nhop_object *nh, struct rt_metrics *out);
208 static void	rt_dispatch(struct mbuf *, sa_family_t);
209 static void	rt_ifannouncemsg(struct ifnet *ifp, int what);
210 static int	handle_rtm_get(struct rt_addrinfo *info, u_int fibnum,
211 			struct rt_msghdr *rtm, struct rib_cmd_info *rc);
212 static int	update_rtm_from_rc(struct rt_addrinfo *info,
213 			struct rt_msghdr **prtm, int alloc_len,
214 			struct rib_cmd_info *rc, struct nhop_object *nh);
215 static void	send_rtm_reply(struct socket *so, struct rt_msghdr *rtm,
216 			struct mbuf *m, sa_family_t saf, u_int fibnum,
217 			int rtm_errno);
218 static void	rtsock_notify_event(uint32_t fibnum, const struct rib_cmd_info *rc);
219 static void	rtsock_ifmsg(struct ifnet *ifp, int if_flags_mask);
220 
221 static struct netisr_handler rtsock_nh = {
222 	.nh_name = "rtsock",
223 	.nh_handler = rts_input,
224 	.nh_proto = NETISR_ROUTE,
225 	.nh_policy = NETISR_POLICY_SOURCE,
226 };
227 
228 static int
229 sysctl_route_netisr_maxqlen(SYSCTL_HANDLER_ARGS)
230 {
231 	int error, qlimit;
232 
233 	netisr_getqlimit(&rtsock_nh, &qlimit);
234 	error = sysctl_handle_int(oidp, &qlimit, 0, req);
235         if (error || !req->newptr)
236                 return (error);
237 	if (qlimit < 1)
238 		return (EINVAL);
239 	return (netisr_setqlimit(&rtsock_nh, qlimit));
240 }
241 SYSCTL_PROC(_net_route, OID_AUTO, netisr_maxqlen,
242     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE,
243     0, 0, sysctl_route_netisr_maxqlen, "I",
244     "maximum routing socket dispatch queue length");
245 
246 static void
247 vnet_rts_init(void)
248 {
249 	int tmp;
250 
251 	if (IS_DEFAULT_VNET(curvnet)) {
252 		if (TUNABLE_INT_FETCH("net.route.netisr_maxqlen", &tmp))
253 			rtsock_nh.nh_qlimit = tmp;
254 		netisr_register(&rtsock_nh);
255 	}
256 #ifdef VIMAGE
257 	 else
258 		netisr_register_vnet(&rtsock_nh);
259 #endif
260 }
261 VNET_SYSINIT(vnet_rtsock, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
262     vnet_rts_init, 0);
263 
264 #ifdef VIMAGE
265 static void
266 vnet_rts_uninit(void)
267 {
268 
269 	netisr_unregister_vnet(&rtsock_nh);
270 }
271 VNET_SYSUNINIT(vnet_rts_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
272     vnet_rts_uninit, 0);
273 #endif
274 
275 static void
276 report_route_event(const struct rib_cmd_info *rc, void *_cbdata)
277 {
278 	uint32_t fibnum = (uint32_t)(uintptr_t)_cbdata;
279 	struct nhop_object *nh;
280 
281 	nh = rc->rc_cmd == RTM_DELETE ? rc->rc_nh_old : rc->rc_nh_new;
282 	rt_routemsg(rc->rc_cmd, rc->rc_rt, nh, fibnum);
283 }
284 
285 static void
286 rts_handle_route_event(uint32_t fibnum, const struct rib_cmd_info *rc)
287 {
288 #ifdef ROUTE_MPATH
289 	if ((rc->rc_nh_new && NH_IS_NHGRP(rc->rc_nh_new)) ||
290 	    (rc->rc_nh_old && NH_IS_NHGRP(rc->rc_nh_old))) {
291 		rib_decompose_notification(rc, report_route_event,
292 		    (void *)(uintptr_t)fibnum);
293 	} else
294 #endif
295 		report_route_event(rc, (void *)(uintptr_t)fibnum);
296 }
297 static struct rtbridge rtsbridge = {
298 	.route_f = rts_handle_route_event,
299 	.ifmsg_f = rtsock_ifmsg,
300 };
301 static struct rtbridge *rtsbridge_orig_p;
302 
303 static void
304 rtsock_notify_event(uint32_t fibnum, const struct rib_cmd_info *rc)
305 {
306 	netlink_callback_p->route_f(fibnum, rc);
307 }
308 
309 static void
310 rtsock_init(void)
311 {
312 	rtsbridge_orig_p = rtsock_callback_p;
313 	rtsock_callback_p = &rtsbridge;
314 }
315 SYSINIT(rtsock_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, rtsock_init, NULL);
316 
317 static void
318 rts_handle_ifnet_arrival(void *arg __unused, struct ifnet *ifp)
319 {
320 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
321 }
322 EVENTHANDLER_DEFINE(ifnet_arrival_event, rts_handle_ifnet_arrival, NULL, 0);
323 
324 static void
325 rts_handle_ifnet_departure(void *arg __unused, struct ifnet *ifp)
326 {
327 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
328 }
329 EVENTHANDLER_DEFINE(ifnet_departure_event, rts_handle_ifnet_departure, NULL, 0);
330 
331 static void
332 rts_append_data(struct socket *so, struct mbuf *m)
333 {
334 
335 	if (sbappendaddr(&so->so_rcv, &route_src, m, NULL) == 0) {
336 		soroverflow(so);
337 		m_freem(m);
338 	} else
339 		sorwakeup(so);
340 }
341 
342 static void
343 rts_input(struct mbuf *m)
344 {
345 	struct rcb *rcb;
346 	struct socket *last;
347 
348 	last = NULL;
349 	RTSOCK_LOCK();
350 	LIST_FOREACH(rcb, &V_route_cb.cblist, list) {
351 		if (rcb->rcb_family != AF_UNSPEC &&
352 		    rcb->rcb_family != m->m_rtsock_family)
353 			continue;
354 		if ((m->m_flags & RTS_FILTER_FIB) &&
355 		    M_GETFIB(m) != rcb->rcb_socket->so_fibnum)
356 			continue;
357 		if (last != NULL) {
358 			struct mbuf *n;
359 
360 			n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
361 			if (n != NULL)
362 				rts_append_data(last, n);
363 		}
364 		last = rcb->rcb_socket;
365 	}
366 	if (last != NULL)
367 		rts_append_data(last, m);
368 	else
369 		m_freem(m);
370 	RTSOCK_UNLOCK();
371 }
372 
373 static void
374 rts_close(struct socket *so)
375 {
376 
377 	soisdisconnected(so);
378 }
379 
380 static SYSCTL_NODE(_net, OID_AUTO, rtsock, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
381     "Routing socket infrastructure");
382 static u_long rts_sendspace = 8192;
383 SYSCTL_ULONG(_net_rtsock, OID_AUTO, sendspace, CTLFLAG_RW, &rts_sendspace, 0,
384     "Default routing socket send space");
385 static u_long rts_recvspace = 8192;
386 SYSCTL_ULONG(_net_rtsock, OID_AUTO, recvspace, CTLFLAG_RW, &rts_recvspace, 0,
387     "Default routing socket receive space");
388 
389 static int
390 rts_attach(struct socket *so, int proto, struct thread *td)
391 {
392 	struct rcb *rcb;
393 	int error;
394 
395 	error = soreserve(so, rts_sendspace, rts_recvspace);
396 	if (error)
397 		return (error);
398 
399 	rcb = malloc(sizeof(*rcb), M_PCB, M_WAITOK);
400 	rcb->rcb_socket = so;
401 	rcb->rcb_family = proto;
402 
403 	so->so_pcb = rcb;
404 	so->so_fibnum = td->td_proc->p_fibnum;
405 	so->so_options |= SO_USELOOPBACK;
406 
407 	RTSOCK_LOCK();
408 	LIST_INSERT_HEAD(&V_route_cb.cblist, rcb, list);
409 	switch (proto) {
410 	case AF_INET:
411 		V_route_cb.ip_count++;
412 		break;
413 	case AF_INET6:
414 		V_route_cb.ip6_count++;
415 		break;
416 	}
417 	V_route_cb.any_count++;
418 	RTSOCK_UNLOCK();
419 	soisconnected(so);
420 
421 	return (0);
422 }
423 
424 static void
425 rts_detach(struct socket *so)
426 {
427 	struct rcb *rcb = so->so_pcb;
428 
429 	RTSOCK_LOCK();
430 	LIST_REMOVE(rcb, list);
431 	switch(rcb->rcb_family) {
432 	case AF_INET:
433 		V_route_cb.ip_count--;
434 		break;
435 	case AF_INET6:
436 		V_route_cb.ip6_count--;
437 		break;
438 	}
439 	V_route_cb.any_count--;
440 	RTSOCK_UNLOCK();
441 	free(rcb, M_PCB);
442 	so->so_pcb = NULL;
443 }
444 
445 static int
446 rts_disconnect(struct socket *so)
447 {
448 
449 	return (ENOTCONN);
450 }
451 
452 static int
453 rts_shutdown(struct socket *so)
454 {
455 
456 	socantsendmore(so);
457 	return (0);
458 }
459 
460 #ifndef _SOCKADDR_UNION_DEFINED
461 #define	_SOCKADDR_UNION_DEFINED
462 /*
463  * The union of all possible address formats we handle.
464  */
465 union sockaddr_union {
466 	struct sockaddr		sa;
467 	struct sockaddr_in	sin;
468 	struct sockaddr_in6	sin6;
469 };
470 #endif /* _SOCKADDR_UNION_DEFINED */
471 
472 static int
473 rtm_get_jailed(struct rt_addrinfo *info, struct ifnet *ifp,
474     struct nhop_object *nh, union sockaddr_union *saun, struct ucred *cred)
475 {
476 #if defined(INET) || defined(INET6)
477 	struct epoch_tracker et;
478 #endif
479 
480 	/* First, see if the returned address is part of the jail. */
481 	if (prison_if(cred, nh->nh_ifa->ifa_addr) == 0) {
482 		info->rti_info[RTAX_IFA] = nh->nh_ifa->ifa_addr;
483 		return (0);
484 	}
485 
486 	switch (info->rti_info[RTAX_DST]->sa_family) {
487 #ifdef INET
488 	case AF_INET:
489 	{
490 		struct in_addr ia;
491 		struct ifaddr *ifa;
492 		int found;
493 
494 		found = 0;
495 		/*
496 		 * Try to find an address on the given outgoing interface
497 		 * that belongs to the jail.
498 		 */
499 		NET_EPOCH_ENTER(et);
500 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
501 			struct sockaddr *sa;
502 			sa = ifa->ifa_addr;
503 			if (sa->sa_family != AF_INET)
504 				continue;
505 			ia = ((struct sockaddr_in *)sa)->sin_addr;
506 			if (prison_check_ip4(cred, &ia) == 0) {
507 				found = 1;
508 				break;
509 			}
510 		}
511 		NET_EPOCH_EXIT(et);
512 		if (!found) {
513 			/*
514 			 * As a last resort return the 'default' jail address.
515 			 */
516 			ia = ((struct sockaddr_in *)nh->nh_ifa->ifa_addr)->
517 			    sin_addr;
518 			if (prison_get_ip4(cred, &ia) != 0)
519 				return (ESRCH);
520 		}
521 		bzero(&saun->sin, sizeof(struct sockaddr_in));
522 		saun->sin.sin_len = sizeof(struct sockaddr_in);
523 		saun->sin.sin_family = AF_INET;
524 		saun->sin.sin_addr.s_addr = ia.s_addr;
525 		info->rti_info[RTAX_IFA] = (struct sockaddr *)&saun->sin;
526 		break;
527 	}
528 #endif
529 #ifdef INET6
530 	case AF_INET6:
531 	{
532 		struct in6_addr ia6;
533 		struct ifaddr *ifa;
534 		int found;
535 
536 		found = 0;
537 		/*
538 		 * Try to find an address on the given outgoing interface
539 		 * that belongs to the jail.
540 		 */
541 		NET_EPOCH_ENTER(et);
542 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
543 			struct sockaddr *sa;
544 			sa = ifa->ifa_addr;
545 			if (sa->sa_family != AF_INET6)
546 				continue;
547 			bcopy(&((struct sockaddr_in6 *)sa)->sin6_addr,
548 			    &ia6, sizeof(struct in6_addr));
549 			if (prison_check_ip6(cred, &ia6) == 0) {
550 				found = 1;
551 				break;
552 			}
553 		}
554 		NET_EPOCH_EXIT(et);
555 		if (!found) {
556 			/*
557 			 * As a last resort return the 'default' jail address.
558 			 */
559 			ia6 = ((struct sockaddr_in6 *)nh->nh_ifa->ifa_addr)->
560 			    sin6_addr;
561 			if (prison_get_ip6(cred, &ia6) != 0)
562 				return (ESRCH);
563 		}
564 		bzero(&saun->sin6, sizeof(struct sockaddr_in6));
565 		saun->sin6.sin6_len = sizeof(struct sockaddr_in6);
566 		saun->sin6.sin6_family = AF_INET6;
567 		bcopy(&ia6, &saun->sin6.sin6_addr, sizeof(struct in6_addr));
568 		if (sa6_recoverscope(&saun->sin6) != 0)
569 			return (ESRCH);
570 		info->rti_info[RTAX_IFA] = (struct sockaddr *)&saun->sin6;
571 		break;
572 	}
573 #endif
574 	default:
575 		return (ESRCH);
576 	}
577 	return (0);
578 }
579 
580 static int
581 fill_blackholeinfo(struct rt_addrinfo *info, union sockaddr_union *saun)
582 {
583 	struct ifaddr *ifa;
584 	sa_family_t saf;
585 
586 	if (V_loif == NULL) {
587 		RTS_PID_LOG(LOG_INFO, "Unable to add blackhole/reject nhop without loopback");
588 		return (ENOTSUP);
589 	}
590 	info->rti_ifp = V_loif;
591 
592 	saf = info->rti_info[RTAX_DST]->sa_family;
593 
594 	CK_STAILQ_FOREACH(ifa, &info->rti_ifp->if_addrhead, ifa_link) {
595 		if (ifa->ifa_addr->sa_family == saf) {
596 			info->rti_ifa = ifa;
597 			break;
598 		}
599 	}
600 	if (info->rti_ifa == NULL) {
601 		RTS_PID_LOG(LOG_INFO, "Unable to find ifa for blackhole/reject nhop");
602 		return (ENOTSUP);
603 	}
604 
605 	bzero(saun, sizeof(union sockaddr_union));
606 	switch (saf) {
607 #ifdef INET
608 	case AF_INET:
609 		saun->sin.sin_family = AF_INET;
610 		saun->sin.sin_len = sizeof(struct sockaddr_in);
611 		saun->sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
612 		break;
613 #endif
614 #ifdef INET6
615 	case AF_INET6:
616 		saun->sin6.sin6_family = AF_INET6;
617 		saun->sin6.sin6_len = sizeof(struct sockaddr_in6);
618 		saun->sin6.sin6_addr = in6addr_loopback;
619 		break;
620 #endif
621 	default:
622 		RTS_PID_LOG(LOG_INFO, "unsupported family: %d", saf);
623 		return (ENOTSUP);
624 	}
625 	info->rti_info[RTAX_GATEWAY] = &saun->sa;
626 	info->rti_flags |= RTF_GATEWAY;
627 
628 	return (0);
629 }
630 
631 /*
632  * Fills in @info based on userland-provided @rtm message.
633  *
634  * Returns 0 on success.
635  */
636 static int
637 fill_addrinfo(struct rt_msghdr *rtm, int len, struct linear_buffer *lb, u_int fibnum,
638     struct rt_addrinfo *info)
639 {
640 	int error;
641 
642 	rtm->rtm_pid = curproc->p_pid;
643 	info->rti_addrs = rtm->rtm_addrs;
644 
645 	info->rti_mflags = rtm->rtm_inits;
646 	info->rti_rmx = &rtm->rtm_rmx;
647 
648 	/*
649 	 * rt_xaddrs() performs s6_addr[2] := sin6_scope_id for AF_INET6
650 	 * link-local address because rtrequest requires addresses with
651 	 * embedded scope id.
652 	 */
653 	if (rt_xaddrs((caddr_t)(rtm + 1), len + (caddr_t)rtm, info))
654 		return (EINVAL);
655 
656 	info->rti_flags = rtm->rtm_flags;
657 	error = cleanup_xaddrs(info, lb);
658 	if (error != 0)
659 		return (error);
660 	/*
661 	 * Verify that the caller has the appropriate privilege; RTM_GET
662 	 * is the only operation the non-superuser is allowed.
663 	 */
664 	if (rtm->rtm_type != RTM_GET) {
665 		error = priv_check(curthread, PRIV_NET_ROUTE);
666 		if (error != 0)
667 			return (error);
668 	}
669 
670 	/*
671 	 * The given gateway address may be an interface address.
672 	 * For example, issuing a "route change" command on a route
673 	 * entry that was created from a tunnel, and the gateway
674 	 * address given is the local end point. In this case the
675 	 * RTF_GATEWAY flag must be cleared or the destination will
676 	 * not be reachable even though there is no error message.
677 	 */
678 	if (info->rti_info[RTAX_GATEWAY] != NULL &&
679 	    info->rti_info[RTAX_GATEWAY]->sa_family != AF_LINK) {
680 		struct nhop_object *nh;
681 
682 		/*
683 		 * A host route through the loopback interface is
684 		 * installed for each interface adddress. In pre 8.0
685 		 * releases the interface address of a PPP link type
686 		 * is not reachable locally. This behavior is fixed as
687 		 * part of the new L2/L3 redesign and rewrite work. The
688 		 * signature of this interface address route is the
689 		 * AF_LINK sa_family type of the gateway, and the
690 		 * rt_ifp has the IFF_LOOPBACK flag set.
691 		 */
692 		nh = rib_lookup(fibnum, info->rti_info[RTAX_GATEWAY], NHR_NONE, 0);
693 		if (nh != NULL && nh->gw_sa.sa_family == AF_LINK &&
694 		    nh->nh_ifp->if_flags & IFF_LOOPBACK) {
695 				info->rti_flags &= ~RTF_GATEWAY;
696 				info->rti_flags |= RTF_GWFLAG_COMPAT;
697 		}
698 	}
699 
700 	return (0);
701 }
702 
703 static struct nhop_object *
704 select_nhop(struct nhop_object *nh, const struct sockaddr *gw)
705 {
706 	if (!NH_IS_NHGRP(nh))
707 		return (nh);
708 #ifdef ROUTE_MPATH
709 	const struct weightened_nhop *wn;
710 	uint32_t num_nhops;
711 	wn = nhgrp_get_nhops((struct nhgrp_object *)nh, &num_nhops);
712 	if (gw == NULL)
713 		return (wn[0].nh);
714 	for (int i = 0; i < num_nhops; i++) {
715 		if (match_nhop_gw(wn[i].nh, gw))
716 			return (wn[i].nh);
717 	}
718 #endif
719 	return (NULL);
720 }
721 
722 /*
723  * Handles RTM_GET message from routing socket, returning matching rt.
724  *
725  * Returns:
726  * 0 on success, with locked and referenced matching rt in @rt_nrt
727  * errno of failure
728  */
729 static int
730 handle_rtm_get(struct rt_addrinfo *info, u_int fibnum,
731     struct rt_msghdr *rtm, struct rib_cmd_info *rc)
732 {
733 	RIB_RLOCK_TRACKER;
734 	struct rib_head *rnh;
735 	struct nhop_object *nh;
736 	sa_family_t saf;
737 
738 	saf = info->rti_info[RTAX_DST]->sa_family;
739 
740 	rnh = rt_tables_get_rnh(fibnum, saf);
741 	if (rnh == NULL)
742 		return (EAFNOSUPPORT);
743 
744 	RIB_RLOCK(rnh);
745 
746 	/*
747 	 * By (implicit) convention host route (one without netmask)
748 	 * means longest-prefix-match request and the route with netmask
749 	 * means exact-match lookup.
750 	 * As cleanup_xaddrs() cleans up info flags&addrs for the /32,/128
751 	 * prefixes, use original data to check for the netmask presence.
752 	 */
753 	if ((rtm->rtm_addrs & RTA_NETMASK) == 0) {
754 		/*
755 		 * Provide longest prefix match for
756 		 * address lookup (no mask).
757 		 * 'route -n get addr'
758 		 */
759 		rc->rc_rt = (struct rtentry *) rnh->rnh_matchaddr(
760 		    info->rti_info[RTAX_DST], &rnh->head);
761 	} else
762 		rc->rc_rt = (struct rtentry *) rnh->rnh_lookup(
763 		    info->rti_info[RTAX_DST],
764 		    info->rti_info[RTAX_NETMASK], &rnh->head);
765 
766 	if (rc->rc_rt == NULL) {
767 		RIB_RUNLOCK(rnh);
768 		return (ESRCH);
769 	}
770 
771 	nh = select_nhop(rt_get_raw_nhop(rc->rc_rt), info->rti_info[RTAX_GATEWAY]);
772 	if (nh == NULL) {
773 		RIB_RUNLOCK(rnh);
774 		return (ESRCH);
775 	}
776 	/*
777 	 * If performing proxied L2 entry insertion, and
778 	 * the actual PPP host entry is found, perform
779 	 * another search to retrieve the prefix route of
780 	 * the local end point of the PPP link.
781 	 * TODO: move this logic to userland.
782 	 */
783 	if (rtm->rtm_flags & RTF_ANNOUNCE) {
784 		struct sockaddr_storage laddr;
785 
786 		if (nh->nh_ifp != NULL &&
787 		    nh->nh_ifp->if_type == IFT_PROPVIRTUAL) {
788 			struct ifaddr *ifa;
789 
790 			ifa = ifa_ifwithnet(info->rti_info[RTAX_DST], 1,
791 					RT_ALL_FIBS);
792 			if (ifa != NULL)
793 				rt_maskedcopy(ifa->ifa_addr,
794 					      (struct sockaddr *)&laddr,
795 					      ifa->ifa_netmask);
796 		} else
797 			rt_maskedcopy(nh->nh_ifa->ifa_addr,
798 				      (struct sockaddr *)&laddr,
799 				      nh->nh_ifa->ifa_netmask);
800 		/*
801 		 * refactor rt and no lock operation necessary
802 		 */
803 		rc->rc_rt = (struct rtentry *)rnh->rnh_matchaddr(
804 		    (struct sockaddr *)&laddr, &rnh->head);
805 		if (rc->rc_rt == NULL) {
806 			RIB_RUNLOCK(rnh);
807 			return (ESRCH);
808 		}
809 		nh = select_nhop(rt_get_raw_nhop(rc->rc_rt), info->rti_info[RTAX_GATEWAY]);
810 		if (nh == NULL) {
811 			RIB_RUNLOCK(rnh);
812 			return (ESRCH);
813 		}
814 	}
815 	rc->rc_nh_new = nh;
816 	rc->rc_nh_weight = rc->rc_rt->rt_weight;
817 	RIB_RUNLOCK(rnh);
818 
819 	return (0);
820 }
821 
822 static void
823 init_sockaddrs_family(int family, struct sockaddr *dst, struct sockaddr *mask)
824 {
825 #ifdef INET
826 	if (family == AF_INET) {
827 		struct sockaddr_in *dst4 = (struct sockaddr_in *)dst;
828 		struct sockaddr_in *mask4 = (struct sockaddr_in *)mask;
829 
830 		bzero(dst4, sizeof(struct sockaddr_in));
831 		bzero(mask4, sizeof(struct sockaddr_in));
832 
833 		dst4->sin_family = AF_INET;
834 		dst4->sin_len = sizeof(struct sockaddr_in);
835 		mask4->sin_family = AF_INET;
836 		mask4->sin_len = sizeof(struct sockaddr_in);
837 	}
838 #endif
839 #ifdef INET6
840 	if (family == AF_INET6) {
841 		struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst;
842 		struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *)mask;
843 
844 		bzero(dst6, sizeof(struct sockaddr_in6));
845 		bzero(mask6, sizeof(struct sockaddr_in6));
846 
847 		dst6->sin6_family = AF_INET6;
848 		dst6->sin6_len = sizeof(struct sockaddr_in6);
849 		mask6->sin6_family = AF_INET6;
850 		mask6->sin6_len = sizeof(struct sockaddr_in6);
851 	}
852 #endif
853 }
854 
855 static void
856 export_rtaddrs(const struct rtentry *rt, struct sockaddr *dst,
857     struct sockaddr *mask)
858 {
859 #ifdef INET
860 	if (dst->sa_family == AF_INET) {
861 		struct sockaddr_in *dst4 = (struct sockaddr_in *)dst;
862 		struct sockaddr_in *mask4 = (struct sockaddr_in *)mask;
863 		uint32_t scopeid = 0;
864 		rt_get_inet_prefix_pmask(rt, &dst4->sin_addr, &mask4->sin_addr,
865 		    &scopeid);
866 		return;
867 	}
868 #endif
869 #ifdef INET6
870 	if (dst->sa_family == AF_INET6) {
871 		struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst;
872 		struct sockaddr_in6 *mask6 = (struct sockaddr_in6 *)mask;
873 		uint32_t scopeid = 0;
874 		rt_get_inet6_prefix_pmask(rt, &dst6->sin6_addr,
875 		    &mask6->sin6_addr, &scopeid);
876 		dst6->sin6_scope_id = scopeid;
877 		return;
878 	}
879 #endif
880 }
881 
882 static int
883 update_rtm_from_info(struct rt_addrinfo *info, struct rt_msghdr **prtm,
884     int alloc_len)
885 {
886 	struct rt_msghdr *rtm, *orig_rtm = NULL;
887 	struct walkarg w;
888 	int len;
889 
890 	rtm = *prtm;
891 	/* Check if we need to realloc storage */
892 	rtsock_msg_buffer(rtm->rtm_type, info, NULL, &len);
893 	if (len > alloc_len) {
894 		struct rt_msghdr *tmp_rtm;
895 
896 		tmp_rtm = malloc(len, M_TEMP, M_NOWAIT);
897 		if (tmp_rtm == NULL)
898 			return (ENOBUFS);
899 		bcopy(rtm, tmp_rtm, rtm->rtm_msglen);
900 		orig_rtm = rtm;
901 		rtm = tmp_rtm;
902 		alloc_len = len;
903 
904 		/*
905 		 * Delay freeing original rtm as info contains
906 		 * data referencing it.
907 		 */
908 	}
909 
910 	w.w_tmem = (caddr_t)rtm;
911 	w.w_tmemsize = alloc_len;
912 	rtsock_msg_buffer(rtm->rtm_type, info, &w, &len);
913 	rtm->rtm_addrs = info->rti_addrs;
914 
915 	if (orig_rtm != NULL)
916 		free(orig_rtm, M_TEMP);
917 	*prtm = rtm;
918 	return (0);
919 }
920 
921 
922 /*
923  * Update sockaddrs, flags, etc in @prtm based on @rc data.
924  * rtm can be reallocated.
925  *
926  * Returns 0 on success, along with pointer to (potentially reallocated)
927  *  rtm.
928  *
929  */
930 static int
931 update_rtm_from_rc(struct rt_addrinfo *info, struct rt_msghdr **prtm,
932     int alloc_len, struct rib_cmd_info *rc, struct nhop_object *nh)
933 {
934 	union sockaddr_union saun;
935 	struct rt_msghdr *rtm;
936 	struct ifnet *ifp;
937 	int error;
938 
939 	rtm = *prtm;
940 	union sockaddr_union sa_dst, sa_mask;
941 	int family = info->rti_info[RTAX_DST]->sa_family;
942 	init_sockaddrs_family(family, &sa_dst.sa, &sa_mask.sa);
943 	export_rtaddrs(rc->rc_rt, &sa_dst.sa, &sa_mask.sa);
944 
945 	info->rti_info[RTAX_DST] = &sa_dst.sa;
946 	info->rti_info[RTAX_NETMASK] = rt_is_host(rc->rc_rt) ? NULL : &sa_mask.sa;
947 	info->rti_info[RTAX_GATEWAY] = &nh->gw_sa;
948 	info->rti_info[RTAX_GENMASK] = 0;
949 	ifp = nh->nh_ifp;
950 	if (rtm->rtm_addrs & (RTA_IFP | RTA_IFA)) {
951 		if (ifp) {
952 			info->rti_info[RTAX_IFP] =
953 			    ifp->if_addr->ifa_addr;
954 			error = rtm_get_jailed(info, ifp, nh,
955 			    &saun, curthread->td_ucred);
956 			if (error != 0)
957 				return (error);
958 			if (ifp->if_flags & IFF_POINTOPOINT)
959 				info->rti_info[RTAX_BRD] =
960 				    nh->nh_ifa->ifa_dstaddr;
961 			rtm->rtm_index = ifp->if_index;
962 		} else {
963 			info->rti_info[RTAX_IFP] = NULL;
964 			info->rti_info[RTAX_IFA] = NULL;
965 		}
966 	} else if (ifp != NULL)
967 		rtm->rtm_index = ifp->if_index;
968 
969 	if ((error = update_rtm_from_info(info, prtm, alloc_len)) != 0)
970 		return (error);
971 
972 	rtm = *prtm;
973 	rtm->rtm_flags = rc->rc_rt->rte_flags | nhop_get_rtflags(nh);
974 	if (rtm->rtm_flags & RTF_GWFLAG_COMPAT)
975 		rtm->rtm_flags = RTF_GATEWAY |
976 			(rtm->rtm_flags & ~RTF_GWFLAG_COMPAT);
977 	rt_getmetrics(rc->rc_rt, nh, &rtm->rtm_rmx);
978 	rtm->rtm_rmx.rmx_weight = rc->rc_nh_weight;
979 
980 	return (0);
981 }
982 
983 #ifdef ROUTE_MPATH
984 static void
985 save_del_notification(const struct rib_cmd_info *rc, void *_cbdata)
986 {
987 	struct rib_cmd_info *rc_new = (struct rib_cmd_info *)_cbdata;
988 
989 	if (rc->rc_cmd == RTM_DELETE)
990 		*rc_new = *rc;
991 }
992 
993 static void
994 save_add_notification(const struct rib_cmd_info *rc, void *_cbdata)
995 {
996 	struct rib_cmd_info *rc_new = (struct rib_cmd_info *)_cbdata;
997 
998 	if (rc->rc_cmd == RTM_ADD)
999 		*rc_new = *rc;
1000 }
1001 #endif
1002 
1003 #if defined(INET6) || defined(INET)
1004 static struct sockaddr *
1005 alloc_sockaddr_aligned(struct linear_buffer *lb, int len)
1006 {
1007 	len = roundup2(len, sizeof(uint64_t));
1008 	if (lb->offset + len > lb->size)
1009 		return (NULL);
1010 	struct sockaddr *sa = (struct sockaddr *)(lb->base + lb->offset);
1011 	lb->offset += len;
1012 	return (sa);
1013 }
1014 #endif
1015 
1016 static int
1017 rts_send(struct socket *so, int flags, struct mbuf *m,
1018     struct sockaddr *nam, struct mbuf *control, struct thread *td)
1019 {
1020 	struct rt_msghdr *rtm = NULL;
1021 	struct rt_addrinfo info;
1022 	struct epoch_tracker et;
1023 #ifdef INET6
1024 	struct sockaddr_storage ss;
1025 	struct sockaddr_in6 *sin6;
1026 	int i, rti_need_deembed = 0;
1027 #endif
1028 	int alloc_len = 0, len, error = 0, fibnum;
1029 	sa_family_t saf = AF_UNSPEC;
1030 	struct rib_cmd_info rc;
1031 	struct nhop_object *nh;
1032 
1033 	if ((flags & PRUS_OOB) || control != NULL) {
1034 		m_freem(m);
1035 		if (control != NULL)
1036 			m_freem(control);
1037 		return (EOPNOTSUPP);
1038 	}
1039 
1040 	fibnum = so->so_fibnum;
1041 #define senderr(e) { error = e; goto flush;}
1042 	if (m == NULL || ((m->m_len < sizeof(long)) &&
1043 		       (m = m_pullup(m, sizeof(long))) == NULL))
1044 		return (ENOBUFS);
1045 	if ((m->m_flags & M_PKTHDR) == 0)
1046 		panic("route_output");
1047 	NET_EPOCH_ENTER(et);
1048 	len = m->m_pkthdr.len;
1049 	if (len < sizeof(*rtm) ||
1050 	    len != mtod(m, struct rt_msghdr *)->rtm_msglen)
1051 		senderr(EINVAL);
1052 
1053 	/*
1054 	 * Most of current messages are in range 200-240 bytes,
1055 	 * minimize possible re-allocation on reply using larger size
1056 	 * buffer aligned on 1k boundaty.
1057 	 */
1058 	alloc_len = roundup2(len, 1024);
1059 	int total_len = alloc_len + SCRATCH_BUFFER_SIZE;
1060 	if ((rtm = malloc(total_len, M_TEMP, M_NOWAIT)) == NULL)
1061 		senderr(ENOBUFS);
1062 
1063 	m_copydata(m, 0, len, (caddr_t)rtm);
1064 	bzero(&info, sizeof(info));
1065 	nh = NULL;
1066 	struct linear_buffer lb = {
1067 		.base = (char *)rtm + alloc_len,
1068 		.size = SCRATCH_BUFFER_SIZE,
1069 	};
1070 
1071 	if (rtm->rtm_version != RTM_VERSION) {
1072 		/* Do not touch message since format is unknown */
1073 		free(rtm, M_TEMP);
1074 		rtm = NULL;
1075 		senderr(EPROTONOSUPPORT);
1076 	}
1077 
1078 	/*
1079 	 * Starting from here, it is possible
1080 	 * to alter original message and insert
1081 	 * caller PID and error value.
1082 	 */
1083 
1084 	if ((error = fill_addrinfo(rtm, len, &lb, fibnum, &info)) != 0) {
1085 		senderr(error);
1086 	}
1087 	/* fill_addringo() embeds scope into IPv6 addresses */
1088 #ifdef INET6
1089 	rti_need_deembed = 1;
1090 #endif
1091 
1092 	saf = info.rti_info[RTAX_DST]->sa_family;
1093 
1094 	/* support for new ARP code */
1095 	if (rtm->rtm_flags & RTF_LLDATA) {
1096 		error = lla_rt_output(rtm, &info);
1097 		goto flush;
1098 	}
1099 
1100 	union sockaddr_union gw_saun;
1101 	int blackhole_flags = rtm->rtm_flags & (RTF_BLACKHOLE|RTF_REJECT);
1102 	if (blackhole_flags != 0) {
1103 		if (blackhole_flags != (RTF_BLACKHOLE | RTF_REJECT))
1104 			error = fill_blackholeinfo(&info, &gw_saun);
1105 		else {
1106 			RTS_PID_LOG(LOG_DEBUG, "both BLACKHOLE and REJECT flags specifiied");
1107 			error = EINVAL;
1108 		}
1109 		if (error != 0)
1110 			senderr(error);
1111 	}
1112 
1113 	switch (rtm->rtm_type) {
1114 	case RTM_ADD:
1115 	case RTM_CHANGE:
1116 		if (rtm->rtm_type == RTM_ADD) {
1117 			if (info.rti_info[RTAX_GATEWAY] == NULL) {
1118 				RTS_PID_LOG(LOG_DEBUG, "RTM_ADD w/o gateway");
1119 				senderr(EINVAL);
1120 			}
1121 		}
1122 		error = rib_action(fibnum, rtm->rtm_type, &info, &rc);
1123 		if (error == 0) {
1124 			rtsock_notify_event(fibnum, &rc);
1125 #ifdef ROUTE_MPATH
1126 			if (NH_IS_NHGRP(rc.rc_nh_new) ||
1127 			    (rc.rc_nh_old && NH_IS_NHGRP(rc.rc_nh_old))) {
1128 				struct rib_cmd_info rc_simple = {};
1129 				rib_decompose_notification(&rc,
1130 				    save_add_notification, (void *)&rc_simple);
1131 				rc = rc_simple;
1132 			}
1133 #endif
1134 			/* nh MAY be empty if RTM_CHANGE request is no-op */
1135 			nh = rc.rc_nh_new;
1136 			if (nh != NULL) {
1137 				rtm->rtm_index = nh->nh_ifp->if_index;
1138 				rtm->rtm_flags = rc.rc_rt->rte_flags | nhop_get_rtflags(nh);
1139 			}
1140 		}
1141 		break;
1142 
1143 	case RTM_DELETE:
1144 		error = rib_action(fibnum, RTM_DELETE, &info, &rc);
1145 		if (error == 0) {
1146 			rtsock_notify_event(fibnum, &rc);
1147 #ifdef ROUTE_MPATH
1148 			if (NH_IS_NHGRP(rc.rc_nh_old) ||
1149 			    (rc.rc_nh_new && NH_IS_NHGRP(rc.rc_nh_new))) {
1150 				struct rib_cmd_info rc_simple = {};
1151 				rib_decompose_notification(&rc,
1152 				    save_del_notification, (void *)&rc_simple);
1153 				rc = rc_simple;
1154 			}
1155 #endif
1156 			nh = rc.rc_nh_old;
1157 		}
1158 		break;
1159 
1160 	case RTM_GET:
1161 		error = handle_rtm_get(&info, fibnum, rtm, &rc);
1162 		if (error != 0)
1163 			senderr(error);
1164 		nh = rc.rc_nh_new;
1165 
1166 		if (!rt_is_exportable(rc.rc_rt, curthread->td_ucred))
1167 			senderr(ESRCH);
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  * This is used in dumping the kernel table via sysctl().
2195  */
2196 static int
2197 sysctl_dumpentry(struct rtentry *rt, void *vw)
2198 {
2199 	struct walkarg *w = vw;
2200 	struct nhop_object *nh;
2201 
2202 	NET_EPOCH_ASSERT();
2203 
2204 	if (!rt_is_exportable(rt, w->w_req->td->td_ucred))
2205 		return (0);
2206 
2207 	export_rtaddrs(rt, w->dst, w->mask);
2208 	nh = rt_get_raw_nhop(rt);
2209 #ifdef ROUTE_MPATH
2210 	if (NH_IS_NHGRP(nh)) {
2211 		const struct weightened_nhop *wn;
2212 		uint32_t num_nhops;
2213 		int error;
2214 		wn = nhgrp_get_nhops((struct nhgrp_object *)nh, &num_nhops);
2215 		for (int i = 0; i < num_nhops; i++) {
2216 			error = sysctl_dumpnhop(rt, wn[i].nh, wn[i].weight, w);
2217 			if (error != 0)
2218 				return (error);
2219 		}
2220 	} else
2221 #endif
2222 		sysctl_dumpnhop(rt, nh, rt->rt_weight, w);
2223 
2224 	return (0);
2225 }
2226 
2227 
2228 static int
2229 sysctl_dumpnhop(struct rtentry *rt, struct nhop_object *nh, uint32_t weight,
2230     struct walkarg *w)
2231 {
2232 	struct rt_addrinfo info;
2233 	int error = 0, size;
2234 	uint32_t rtflags;
2235 
2236 	rtflags = nhop_get_rtflags(nh);
2237 
2238 	if (w->w_op == NET_RT_FLAGS && !(rtflags & w->w_arg))
2239 		return (0);
2240 
2241 	bzero((caddr_t)&info, sizeof(info));
2242 	info.rti_info[RTAX_DST] = w->dst;
2243 	info.rti_info[RTAX_GATEWAY] = &nh->gw_sa;
2244 	info.rti_info[RTAX_NETMASK] = (rtflags & RTF_HOST) ? NULL : w->mask;
2245 	info.rti_info[RTAX_GENMASK] = 0;
2246 	if (nh->nh_ifp && !(nh->nh_ifp->if_flags & IFF_DYING)) {
2247 		info.rti_info[RTAX_IFP] = nh->nh_ifp->if_addr->ifa_addr;
2248 		info.rti_info[RTAX_IFA] = nh->nh_ifa->ifa_addr;
2249 		if (nh->nh_ifp->if_flags & IFF_POINTOPOINT)
2250 			info.rti_info[RTAX_BRD] = nh->nh_ifa->ifa_dstaddr;
2251 	}
2252 	if ((error = rtsock_msg_buffer(RTM_GET, &info, w, &size)) != 0)
2253 		return (error);
2254 	if (w->w_req && w->w_tmem) {
2255 		struct rt_msghdr *rtm = (struct rt_msghdr *)w->w_tmem;
2256 
2257 		bzero(&rtm->rtm_index,
2258 		    sizeof(*rtm) - offsetof(struct rt_msghdr, rtm_index));
2259 
2260 		/*
2261 		 * rte flags may consist of RTF_HOST (duplicated in nhop rtflags)
2262 		 * and RTF_UP (if entry is linked, which is always true here).
2263 		 * Given that, use nhop rtflags & add RTF_UP.
2264 		 */
2265 		rtm->rtm_flags = rtflags | RTF_UP;
2266 		if (rtm->rtm_flags & RTF_GWFLAG_COMPAT)
2267 			rtm->rtm_flags = RTF_GATEWAY |
2268 				(rtm->rtm_flags & ~RTF_GWFLAG_COMPAT);
2269 		rt_getmetrics(rt, nh, &rtm->rtm_rmx);
2270 		rtm->rtm_rmx.rmx_weight = weight;
2271 		rtm->rtm_index = nh->nh_ifp->if_index;
2272 		rtm->rtm_addrs = info.rti_addrs;
2273 		error = SYSCTL_OUT(w->w_req, (caddr_t)rtm, size);
2274 		return (error);
2275 	}
2276 	return (error);
2277 }
2278 
2279 static int
2280 sysctl_iflist_ifml(struct ifnet *ifp, const struct if_data *src_ifd,
2281     struct rt_addrinfo *info, struct walkarg *w, int len)
2282 {
2283 	struct if_msghdrl *ifm;
2284 	struct if_data *ifd;
2285 
2286 	ifm = (struct if_msghdrl *)w->w_tmem;
2287 
2288 #ifdef COMPAT_FREEBSD32
2289 	if (w->w_req->flags & SCTL_MASK32) {
2290 		struct if_msghdrl32 *ifm32;
2291 
2292 		ifm32 = (struct if_msghdrl32 *)ifm;
2293 		ifm32->ifm_addrs = info->rti_addrs;
2294 		ifm32->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2295 		ifm32->ifm_index = ifp->if_index;
2296 		ifm32->_ifm_spare1 = 0;
2297 		ifm32->ifm_len = sizeof(*ifm32);
2298 		ifm32->ifm_data_off = offsetof(struct if_msghdrl32, ifm_data);
2299 		ifm32->_ifm_spare2 = 0;
2300 		ifd = &ifm32->ifm_data;
2301 	} else
2302 #endif
2303 	{
2304 		ifm->ifm_addrs = info->rti_addrs;
2305 		ifm->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2306 		ifm->ifm_index = ifp->if_index;
2307 		ifm->_ifm_spare1 = 0;
2308 		ifm->ifm_len = sizeof(*ifm);
2309 		ifm->ifm_data_off = offsetof(struct if_msghdrl, ifm_data);
2310 		ifm->_ifm_spare2 = 0;
2311 		ifd = &ifm->ifm_data;
2312 	}
2313 
2314 	memcpy(ifd, src_ifd, sizeof(*ifd));
2315 
2316 	return (SYSCTL_OUT(w->w_req, (caddr_t)ifm, len));
2317 }
2318 
2319 static int
2320 sysctl_iflist_ifm(struct ifnet *ifp, const struct if_data *src_ifd,
2321     struct rt_addrinfo *info, struct walkarg *w, int len)
2322 {
2323 	struct if_msghdr *ifm;
2324 	struct if_data *ifd;
2325 
2326 	ifm = (struct if_msghdr *)w->w_tmem;
2327 
2328 #ifdef COMPAT_FREEBSD32
2329 	if (w->w_req->flags & SCTL_MASK32) {
2330 		struct if_msghdr32 *ifm32;
2331 
2332 		ifm32 = (struct if_msghdr32 *)ifm;
2333 		ifm32->ifm_addrs = info->rti_addrs;
2334 		ifm32->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2335 		ifm32->ifm_index = ifp->if_index;
2336 		ifm32->_ifm_spare1 = 0;
2337 		ifd = &ifm32->ifm_data;
2338 	} else
2339 #endif
2340 	{
2341 		ifm->ifm_addrs = info->rti_addrs;
2342 		ifm->ifm_flags = ifp->if_flags | ifp->if_drv_flags;
2343 		ifm->ifm_index = ifp->if_index;
2344 		ifm->_ifm_spare1 = 0;
2345 		ifd = &ifm->ifm_data;
2346 	}
2347 
2348 	memcpy(ifd, src_ifd, sizeof(*ifd));
2349 
2350 	return (SYSCTL_OUT(w->w_req, (caddr_t)ifm, len));
2351 }
2352 
2353 static int
2354 sysctl_iflist_ifaml(struct ifaddr *ifa, struct rt_addrinfo *info,
2355     struct walkarg *w, int len)
2356 {
2357 	struct ifa_msghdrl *ifam;
2358 	struct if_data *ifd;
2359 
2360 	ifam = (struct ifa_msghdrl *)w->w_tmem;
2361 
2362 #ifdef COMPAT_FREEBSD32
2363 	if (w->w_req->flags & SCTL_MASK32) {
2364 		struct ifa_msghdrl32 *ifam32;
2365 
2366 		ifam32 = (struct ifa_msghdrl32 *)ifam;
2367 		ifam32->ifam_addrs = info->rti_addrs;
2368 		ifam32->ifam_flags = ifa->ifa_flags;
2369 		ifam32->ifam_index = ifa->ifa_ifp->if_index;
2370 		ifam32->_ifam_spare1 = 0;
2371 		ifam32->ifam_len = sizeof(*ifam32);
2372 		ifam32->ifam_data_off =
2373 		    offsetof(struct ifa_msghdrl32, ifam_data);
2374 		ifam32->ifam_metric = ifa->ifa_ifp->if_metric;
2375 		ifd = &ifam32->ifam_data;
2376 	} else
2377 #endif
2378 	{
2379 		ifam->ifam_addrs = info->rti_addrs;
2380 		ifam->ifam_flags = ifa->ifa_flags;
2381 		ifam->ifam_index = ifa->ifa_ifp->if_index;
2382 		ifam->_ifam_spare1 = 0;
2383 		ifam->ifam_len = sizeof(*ifam);
2384 		ifam->ifam_data_off = offsetof(struct ifa_msghdrl, ifam_data);
2385 		ifam->ifam_metric = ifa->ifa_ifp->if_metric;
2386 		ifd = &ifam->ifam_data;
2387 	}
2388 
2389 	bzero(ifd, sizeof(*ifd));
2390 	ifd->ifi_datalen = sizeof(struct if_data);
2391 	ifd->ifi_ipackets = counter_u64_fetch(ifa->ifa_ipackets);
2392 	ifd->ifi_opackets = counter_u64_fetch(ifa->ifa_opackets);
2393 	ifd->ifi_ibytes = counter_u64_fetch(ifa->ifa_ibytes);
2394 	ifd->ifi_obytes = counter_u64_fetch(ifa->ifa_obytes);
2395 
2396 	/* Fixup if_data carp(4) vhid. */
2397 	if (carp_get_vhid_p != NULL)
2398 		ifd->ifi_vhid = (*carp_get_vhid_p)(ifa);
2399 
2400 	return (SYSCTL_OUT(w->w_req, w->w_tmem, len));
2401 }
2402 
2403 static int
2404 sysctl_iflist_ifam(struct ifaddr *ifa, struct rt_addrinfo *info,
2405     struct walkarg *w, int len)
2406 {
2407 	struct ifa_msghdr *ifam;
2408 
2409 	ifam = (struct ifa_msghdr *)w->w_tmem;
2410 	ifam->ifam_addrs = info->rti_addrs;
2411 	ifam->ifam_flags = ifa->ifa_flags;
2412 	ifam->ifam_index = ifa->ifa_ifp->if_index;
2413 	ifam->_ifam_spare1 = 0;
2414 	ifam->ifam_metric = ifa->ifa_ifp->if_metric;
2415 
2416 	return (SYSCTL_OUT(w->w_req, w->w_tmem, len));
2417 }
2418 
2419 static int
2420 sysctl_iflist(int af, struct walkarg *w)
2421 {
2422 	struct ifnet *ifp;
2423 	struct ifaddr *ifa;
2424 	struct if_data ifd;
2425 	struct rt_addrinfo info;
2426 	int len, error = 0;
2427 	struct sockaddr_storage ss;
2428 
2429 	bzero((caddr_t)&info, sizeof(info));
2430 	bzero(&ifd, sizeof(ifd));
2431 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2432 		if (w->w_arg && w->w_arg != ifp->if_index)
2433 			continue;
2434 		if_data_copy(ifp, &ifd);
2435 		ifa = ifp->if_addr;
2436 		info.rti_info[RTAX_IFP] = ifa->ifa_addr;
2437 		error = rtsock_msg_buffer(RTM_IFINFO, &info, w, &len);
2438 		if (error != 0)
2439 			goto done;
2440 		info.rti_info[RTAX_IFP] = NULL;
2441 		if (w->w_req && w->w_tmem) {
2442 			if (w->w_op == NET_RT_IFLISTL)
2443 				error = sysctl_iflist_ifml(ifp, &ifd, &info, w,
2444 				    len);
2445 			else
2446 				error = sysctl_iflist_ifm(ifp, &ifd, &info, w,
2447 				    len);
2448 			if (error)
2449 				goto done;
2450 		}
2451 		while ((ifa = CK_STAILQ_NEXT(ifa, ifa_link)) != NULL) {
2452 			if (af && af != ifa->ifa_addr->sa_family)
2453 				continue;
2454 			if (prison_if(w->w_req->td->td_ucred,
2455 			    ifa->ifa_addr) != 0)
2456 				continue;
2457 			info.rti_info[RTAX_IFA] = ifa->ifa_addr;
2458 			info.rti_info[RTAX_NETMASK] = rtsock_fix_netmask(
2459 			    ifa->ifa_addr, ifa->ifa_netmask, &ss);
2460 			info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
2461 			error = rtsock_msg_buffer(RTM_NEWADDR, &info, w, &len);
2462 			if (error != 0)
2463 				goto done;
2464 			if (w->w_req && w->w_tmem) {
2465 				if (w->w_op == NET_RT_IFLISTL)
2466 					error = sysctl_iflist_ifaml(ifa, &info,
2467 					    w, len);
2468 				else
2469 					error = sysctl_iflist_ifam(ifa, &info,
2470 					    w, len);
2471 				if (error)
2472 					goto done;
2473 			}
2474 		}
2475 		info.rti_info[RTAX_IFA] = NULL;
2476 		info.rti_info[RTAX_NETMASK] = NULL;
2477 		info.rti_info[RTAX_BRD] = NULL;
2478 	}
2479 done:
2480 	return (error);
2481 }
2482 
2483 static int
2484 sysctl_ifmalist(int af, struct walkarg *w)
2485 {
2486 	struct rt_addrinfo info;
2487 	struct ifaddr *ifa;
2488 	struct ifmultiaddr *ifma;
2489 	struct ifnet *ifp;
2490 	int error, len;
2491 
2492 	NET_EPOCH_ASSERT();
2493 
2494 	error = 0;
2495 	bzero((caddr_t)&info, sizeof(info));
2496 
2497 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2498 		if (w->w_arg && w->w_arg != ifp->if_index)
2499 			continue;
2500 		ifa = ifp->if_addr;
2501 		info.rti_info[RTAX_IFP] = ifa ? ifa->ifa_addr : NULL;
2502 		CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2503 			if (af && af != ifma->ifma_addr->sa_family)
2504 				continue;
2505 			if (prison_if(w->w_req->td->td_ucred,
2506 			    ifma->ifma_addr) != 0)
2507 				continue;
2508 			info.rti_info[RTAX_IFA] = ifma->ifma_addr;
2509 			info.rti_info[RTAX_GATEWAY] =
2510 			    (ifma->ifma_addr->sa_family != AF_LINK) ?
2511 			    ifma->ifma_lladdr : NULL;
2512 			error = rtsock_msg_buffer(RTM_NEWMADDR, &info, w, &len);
2513 			if (error != 0)
2514 				break;
2515 			if (w->w_req && w->w_tmem) {
2516 				struct ifma_msghdr *ifmam;
2517 
2518 				ifmam = (struct ifma_msghdr *)w->w_tmem;
2519 				ifmam->ifmam_index = ifma->ifma_ifp->if_index;
2520 				ifmam->ifmam_flags = 0;
2521 				ifmam->ifmam_addrs = info.rti_addrs;
2522 				ifmam->_ifmam_spare1 = 0;
2523 				error = SYSCTL_OUT(w->w_req, w->w_tmem, len);
2524 				if (error != 0)
2525 					break;
2526 			}
2527 		}
2528 		if (error != 0)
2529 			break;
2530 	}
2531 	return (error);
2532 }
2533 
2534 static void
2535 rtable_sysctl_dump(uint32_t fibnum, int family, struct walkarg *w)
2536 {
2537 	union sockaddr_union sa_dst, sa_mask;
2538 
2539 	w->family = family;
2540 	w->dst = (struct sockaddr *)&sa_dst;
2541 	w->mask = (struct sockaddr *)&sa_mask;
2542 
2543 	init_sockaddrs_family(family, w->dst, w->mask);
2544 
2545 	rib_walk(fibnum, family, false, sysctl_dumpentry, w);
2546 }
2547 
2548 static int
2549 sysctl_rtsock(SYSCTL_HANDLER_ARGS)
2550 {
2551 	struct epoch_tracker et;
2552 	int	*name = (int *)arg1;
2553 	u_int	namelen = arg2;
2554 	struct rib_head *rnh = NULL; /* silence compiler. */
2555 	int	i, lim, error = EINVAL;
2556 	int	fib = 0;
2557 	u_char	af;
2558 	struct	walkarg w;
2559 
2560 	if (namelen < 3)
2561 		return (EINVAL);
2562 
2563 	name++;
2564 	namelen--;
2565 	if (req->newptr)
2566 		return (EPERM);
2567 	if (name[1] == NET_RT_DUMP || name[1] == NET_RT_NHOP || name[1] == NET_RT_NHGRP) {
2568 		if (namelen == 3)
2569 			fib = req->td->td_proc->p_fibnum;
2570 		else if (namelen == 4)
2571 			fib = (name[3] == RT_ALL_FIBS) ?
2572 			    req->td->td_proc->p_fibnum : name[3];
2573 		else
2574 			return ((namelen < 3) ? EISDIR : ENOTDIR);
2575 		if (fib < 0 || fib >= rt_numfibs)
2576 			return (EINVAL);
2577 	} else if (namelen != 3)
2578 		return ((namelen < 3) ? EISDIR : ENOTDIR);
2579 	af = name[0];
2580 	if (af > AF_MAX)
2581 		return (EINVAL);
2582 	bzero(&w, sizeof(w));
2583 	w.w_op = name[1];
2584 	w.w_arg = name[2];
2585 	w.w_req = req;
2586 
2587 	error = sysctl_wire_old_buffer(req, 0);
2588 	if (error)
2589 		return (error);
2590 
2591 	/*
2592 	 * Allocate reply buffer in advance.
2593 	 * All rtsock messages has maximum length of u_short.
2594 	 */
2595 	w.w_tmemsize = 65536;
2596 	w.w_tmem = malloc(w.w_tmemsize, M_TEMP, M_WAITOK);
2597 
2598 	NET_EPOCH_ENTER(et);
2599 	switch (w.w_op) {
2600 	case NET_RT_DUMP:
2601 	case NET_RT_FLAGS:
2602 		if (af == 0) {			/* dump all tables */
2603 			i = 1;
2604 			lim = AF_MAX;
2605 		} else				/* dump only one table */
2606 			i = lim = af;
2607 
2608 		/*
2609 		 * take care of llinfo entries, the caller must
2610 		 * specify an AF
2611 		 */
2612 		if (w.w_op == NET_RT_FLAGS &&
2613 		    (w.w_arg == 0 || w.w_arg & RTF_LLINFO)) {
2614 			if (af != 0)
2615 				error = lltable_sysctl_dumparp(af, w.w_req);
2616 			else
2617 				error = EINVAL;
2618 			break;
2619 		}
2620 		/*
2621 		 * take care of routing entries
2622 		 */
2623 		for (error = 0; error == 0 && i <= lim; i++) {
2624 			rnh = rt_tables_get_rnh(fib, i);
2625 			if (rnh != NULL) {
2626 				rtable_sysctl_dump(fib, i, &w);
2627 			} else if (af != 0)
2628 				error = EAFNOSUPPORT;
2629 		}
2630 		break;
2631 	case NET_RT_NHOP:
2632 	case NET_RT_NHGRP:
2633 		/* Allow dumping one specific af/fib at a time */
2634 		if (namelen < 4) {
2635 			error = EINVAL;
2636 			break;
2637 		}
2638 		fib = name[3];
2639 		if (fib < 0 || fib > rt_numfibs) {
2640 			error = EINVAL;
2641 			break;
2642 		}
2643 		rnh = rt_tables_get_rnh(fib, af);
2644 		if (rnh == NULL) {
2645 			error = EAFNOSUPPORT;
2646 			break;
2647 		}
2648 		if (w.w_op == NET_RT_NHOP)
2649 			error = nhops_dump_sysctl(rnh, w.w_req);
2650 		else
2651 #ifdef ROUTE_MPATH
2652 			error = nhgrp_dump_sysctl(rnh, w.w_req);
2653 #else
2654 			error = ENOTSUP;
2655 #endif
2656 		break;
2657 	case NET_RT_IFLIST:
2658 	case NET_RT_IFLISTL:
2659 		error = sysctl_iflist(af, &w);
2660 		break;
2661 
2662 	case NET_RT_IFMALIST:
2663 		error = sysctl_ifmalist(af, &w);
2664 		break;
2665 	}
2666 	NET_EPOCH_EXIT(et);
2667 
2668 	free(w.w_tmem, M_TEMP);
2669 	return (error);
2670 }
2671 
2672 static SYSCTL_NODE(_net, PF_ROUTE, routetable, CTLFLAG_RD | CTLFLAG_MPSAFE,
2673     sysctl_rtsock, "Return route tables and interface/address lists");
2674 
2675 /*
2676  * Definitions of protocols supported in the ROUTE domain.
2677  */
2678 
2679 static struct domain routedomain;		/* or at least forward */
2680 
2681 static struct protosw routesw = {
2682 	.pr_type =		SOCK_RAW,
2683 	.pr_flags =		PR_ATOMIC|PR_ADDR,
2684 	.pr_abort =		rts_close,
2685 	.pr_attach =		rts_attach,
2686 	.pr_detach =		rts_detach,
2687 	.pr_send =		rts_send,
2688 	.pr_shutdown =		rts_shutdown,
2689 	.pr_disconnect =	rts_disconnect,
2690 	.pr_close =		rts_close,
2691 };
2692 
2693 static struct domain routedomain = {
2694 	.dom_family =		PF_ROUTE,
2695 	.dom_name =		"route",
2696 	.dom_nprotosw =		1,
2697 	.dom_protosw =		{ &routesw },
2698 };
2699 
2700 DOMAIN_SET(route);
2701