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