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