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