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