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