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