xref: /openbsd-src/sys/net/rtsock.c (revision fc405d53b73a2d73393cb97f684863d17b583e38)
1 /*	$OpenBSD: rtsock.c,v 1.365 2023/04/20 21:43:17 mvs Exp $	*/
2 /*	$NetBSD: rtsock.c,v 1.18 1996/03/29 00:32:10 cgd Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1988, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)rtsock.c	8.6 (Berkeley) 2/11/95
62  */
63 
64 #include <sys/param.h>
65 #include <sys/systm.h>
66 #include <sys/proc.h>
67 #include <sys/sysctl.h>
68 #include <sys/mbuf.h>
69 #include <sys/socket.h>
70 #include <sys/socketvar.h>
71 #include <sys/domain.h>
72 #include <sys/pool.h>
73 #include <sys/protosw.h>
74 #include <sys/srp.h>
75 
76 #include <net/if.h>
77 #include <net/if_dl.h>
78 #include <net/if_var.h>
79 #include <net/route.h>
80 
81 #include <netinet/in.h>
82 
83 #ifdef MPLS
84 #include <netmpls/mpls.h>
85 #endif
86 #ifdef IPSEC
87 #include <netinet/ip_ipsp.h>
88 #include <net/if_enc.h>
89 #endif
90 #ifdef BFD
91 #include <net/bfd.h>
92 #endif
93 
94 #include <sys/stdarg.h>
95 #include <sys/kernel.h>
96 #include <sys/timeout.h>
97 
98 #define	ROUTESNDQ	8192
99 #define	ROUTERCVQ	8192
100 
101 const struct sockaddr route_src = { 2, PF_ROUTE, };
102 
103 struct walkarg {
104 	int	w_op, w_arg, w_tmemsize;
105 	size_t	w_given, w_needed;
106 	caddr_t	w_where, w_tmem;
107 };
108 
109 void	route_prinit(void);
110 void	rcb_ref(void *, void *);
111 void	rcb_unref(void *, void *);
112 int	route_output(struct mbuf *, struct socket *);
113 int	route_ctloutput(int, struct socket *, int, int, struct mbuf *);
114 int	route_attach(struct socket *, int, int);
115 int	route_detach(struct socket *);
116 int	route_disconnect(struct socket *);
117 int	route_shutdown(struct socket *);
118 void	route_rcvd(struct socket *);
119 int	route_send(struct socket *, struct mbuf *, struct mbuf *,
120 	    struct mbuf *);
121 int	route_sockaddr(struct socket *, struct mbuf *);
122 int	route_peeraddr(struct socket *, struct mbuf *);
123 void	route_input(struct mbuf *m0, struct socket *, sa_family_t);
124 int	route_arp_conflict(struct rtentry *, struct rt_addrinfo *);
125 int	route_cleargateway(struct rtentry *, void *, unsigned int);
126 void	rtm_senddesync_timer(void *);
127 void	rtm_senddesync(struct socket *);
128 int	rtm_sendup(struct socket *, struct mbuf *);
129 
130 int	rtm_getifa(struct rt_addrinfo *, unsigned int);
131 int	rtm_output(struct rt_msghdr *, struct rtentry **, struct rt_addrinfo *,
132 	    uint8_t, unsigned int);
133 struct rt_msghdr *rtm_report(struct rtentry *, u_char, int, int);
134 struct mbuf	*rtm_msg1(int, struct rt_addrinfo *);
135 int		 rtm_msg2(int, int, struct rt_addrinfo *, caddr_t,
136 		     struct walkarg *);
137 int		 rtm_xaddrs(caddr_t, caddr_t, struct rt_addrinfo *);
138 int		 rtm_validate_proposal(struct rt_addrinfo *);
139 void		 rtm_setmetrics(u_long, const struct rt_metrics *,
140 		     struct rt_kmetrics *);
141 void		 rtm_getmetrics(const struct rtentry *,
142 		     struct rt_metrics *);
143 
144 int		 sysctl_iflist(int, struct walkarg *);
145 int		 sysctl_ifnames(struct walkarg *);
146 int		 sysctl_rtable_rtstat(void *, size_t *, void *);
147 
148 int		 rt_setsource(unsigned int, struct sockaddr *);
149 
150 /*
151  * Locks used to protect struct members
152  *       I       immutable after creation
153  *       s       solock
154  */
155 struct rtpcb {
156 	struct socket		*rop_socket;		/* [I] */
157 
158 	SRPL_ENTRY(rtpcb)	rop_list;
159 	struct refcnt		rop_refcnt;
160 	struct timeout		rop_timeout;
161 	unsigned int		rop_msgfilter;		/* [s] */
162 	unsigned int		rop_flagfilter;		/* [s] */
163 	unsigned int		rop_flags;		/* [s] */
164 	u_int			rop_rtableid;		/* [s] */
165 	unsigned short		rop_proto;		/* [I] */
166 	u_char			rop_priority;		/* [s] */
167 };
168 #define	sotortpcb(so)	((struct rtpcb *)(so)->so_pcb)
169 
170 struct rtptable {
171 	SRPL_HEAD(, rtpcb)	rtp_list;
172 	struct srpl_rc		rtp_rc;
173 	struct rwlock		rtp_lk;
174 	unsigned int		rtp_count;
175 };
176 
177 struct pool rtpcb_pool;
178 struct rtptable rtptable;
179 
180 /*
181  * These flags and timeout are used for indicating to userland (via a
182  * RTM_DESYNC msg) when the route socket has overflowed and messages
183  * have been lost.
184  */
185 #define ROUTECB_FLAG_DESYNC	0x1	/* Route socket out of memory */
186 #define ROUTECB_FLAG_FLUSH	0x2	/* Wait until socket is empty before
187 					   queueing more packets */
188 
189 #define ROUTE_DESYNC_RESEND_TIMEOUT	200	/* In ms */
190 
191 void
192 route_prinit(void)
193 {
194 	srpl_rc_init(&rtptable.rtp_rc, rcb_ref, rcb_unref, NULL);
195 	rw_init(&rtptable.rtp_lk, "rtsock");
196 	SRPL_INIT(&rtptable.rtp_list);
197 	pool_init(&rtpcb_pool, sizeof(struct rtpcb), 0,
198 	    IPL_SOFTNET, PR_WAITOK, "rtpcb", NULL);
199 }
200 
201 void
202 rcb_ref(void *null, void *v)
203 {
204 	struct rtpcb *rop = v;
205 
206 	refcnt_take(&rop->rop_refcnt);
207 }
208 
209 void
210 rcb_unref(void *null, void *v)
211 {
212 	struct rtpcb *rop = v;
213 
214 	refcnt_rele_wake(&rop->rop_refcnt);
215 }
216 
217 int
218 route_attach(struct socket *so, int proto, int wait)
219 {
220 	struct rtpcb	*rop;
221 	int		 error;
222 
223 	error = soreserve(so, ROUTESNDQ, ROUTERCVQ);
224 	if (error)
225 		return (error);
226 	/*
227 	 * use the rawcb but allocate a rtpcb, this
228 	 * code does not care about the additional fields
229 	 * and works directly on the raw socket.
230 	 */
231 	rop = pool_get(&rtpcb_pool, (wait == M_WAIT ? PR_WAITOK : PR_NOWAIT) |
232 	    PR_ZERO);
233 	if (rop == NULL)
234 		return (ENOBUFS);
235 	so->so_pcb = rop;
236 	/* Init the timeout structure */
237 	timeout_set_proc(&rop->rop_timeout, rtm_senddesync_timer, so);
238 	refcnt_init(&rop->rop_refcnt);
239 
240 	rop->rop_socket = so;
241 	rop->rop_proto = proto;
242 
243 	rop->rop_rtableid = curproc->p_p->ps_rtableid;
244 
245 	soisconnected(so);
246 	so->so_options |= SO_USELOOPBACK;
247 
248 	rw_enter(&rtptable.rtp_lk, RW_WRITE);
249 	SRPL_INSERT_HEAD_LOCKED(&rtptable.rtp_rc, &rtptable.rtp_list, rop,
250 	    rop_list);
251 	rtptable.rtp_count++;
252 	rw_exit(&rtptable.rtp_lk);
253 
254 	return (0);
255 }
256 
257 int
258 route_detach(struct socket *so)
259 {
260 	struct rtpcb	*rop;
261 
262 	soassertlocked(so);
263 
264 	rop = sotortpcb(so);
265 	if (rop == NULL)
266 		return (EINVAL);
267 
268 	rw_enter(&rtptable.rtp_lk, RW_WRITE);
269 
270 	rtptable.rtp_count--;
271 	SRPL_REMOVE_LOCKED(&rtptable.rtp_rc, &rtptable.rtp_list, rop, rtpcb,
272 	    rop_list);
273 	rw_exit(&rtptable.rtp_lk);
274 
275 	sounlock(so);
276 
277 	/* wait for all references to drop */
278 	refcnt_finalize(&rop->rop_refcnt, "rtsockrefs");
279 	timeout_del_barrier(&rop->rop_timeout);
280 
281 	solock(so);
282 
283 	so->so_pcb = NULL;
284 	KASSERT((so->so_state & SS_NOFDREF) == 0);
285 	pool_put(&rtpcb_pool, rop);
286 
287 	return (0);
288 }
289 
290 int
291 route_disconnect(struct socket *so)
292 {
293 	soisdisconnected(so);
294 	return (0);
295 }
296 
297 int
298 route_shutdown(struct socket *so)
299 {
300 	socantsendmore(so);
301 	return (0);
302 }
303 
304 void
305 route_rcvd(struct socket *so)
306 {
307 	struct rtpcb *rop = sotortpcb(so);
308 
309 	soassertlocked(so);
310 
311 	/*
312 	 * If we are in a FLUSH state, check if the buffer is
313 	 * empty so that we can clear the flag.
314 	 */
315 	if (((rop->rop_flags & ROUTECB_FLAG_FLUSH) != 0) &&
316 	    ((sbspace(rop->rop_socket, &rop->rop_socket->so_rcv) ==
317 	    rop->rop_socket->so_rcv.sb_hiwat)))
318 		rop->rop_flags &= ~ROUTECB_FLAG_FLUSH;
319 }
320 
321 int
322 route_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
323     struct mbuf *control)
324 {
325 	int error;
326 
327 	soassertlocked(so);
328 
329 	if (control && control->m_len) {
330 		error = EOPNOTSUPP;
331 		goto out;
332 	}
333 
334 	if (nam) {
335 		error = EISCONN;
336 		goto out;
337 	}
338 
339 	error = route_output(m, so);
340 	m = NULL;
341 
342 out:
343 	m_freem(control);
344 	m_freem(m);
345 
346 	return (error);
347 }
348 
349 int
350 route_sockaddr(struct socket *so, struct mbuf *nam)
351 {
352 	return (EINVAL);
353 }
354 
355 int
356 route_peeraddr(struct socket *so, struct mbuf *nam)
357 {
358 	/* minimal support, just implement a fake peer address */
359 	bcopy(&route_src, mtod(nam, caddr_t), route_src.sa_len);
360 	nam->m_len = route_src.sa_len;
361 	return (0);
362 }
363 
364 int
365 route_ctloutput(int op, struct socket *so, int level, int optname,
366     struct mbuf *m)
367 {
368 	struct rtpcb *rop = sotortpcb(so);
369 	int error = 0;
370 	unsigned int tid, prio;
371 
372 	if (level != AF_ROUTE)
373 		return (EINVAL);
374 
375 	switch (op) {
376 	case PRCO_SETOPT:
377 		switch (optname) {
378 		case ROUTE_MSGFILTER:
379 			if (m == NULL || m->m_len != sizeof(unsigned int))
380 				error = EINVAL;
381 			else
382 				rop->rop_msgfilter = *mtod(m, unsigned int *);
383 			break;
384 		case ROUTE_TABLEFILTER:
385 			if (m == NULL || m->m_len != sizeof(unsigned int)) {
386 				error = EINVAL;
387 				break;
388 			}
389 			tid = *mtod(m, unsigned int *);
390 			if (tid != RTABLE_ANY && !rtable_exists(tid))
391 				error = ENOENT;
392 			else
393 				rop->rop_rtableid = tid;
394 			break;
395 		case ROUTE_PRIOFILTER:
396 			if (m == NULL || m->m_len != sizeof(unsigned int)) {
397 				error = EINVAL;
398 				break;
399 			}
400 			prio = *mtod(m, unsigned int *);
401 			if (prio > RTP_MAX)
402 				error = EINVAL;
403 			else
404 				rop->rop_priority = prio;
405 			break;
406 		case ROUTE_FLAGFILTER:
407 			if (m == NULL || m->m_len != sizeof(unsigned int))
408 				error = EINVAL;
409 			else
410 				rop->rop_flagfilter = *mtod(m, unsigned int *);
411 			break;
412 		default:
413 			error = ENOPROTOOPT;
414 			break;
415 		}
416 		break;
417 	case PRCO_GETOPT:
418 		switch (optname) {
419 		case ROUTE_MSGFILTER:
420 			m->m_len = sizeof(unsigned int);
421 			*mtod(m, unsigned int *) = rop->rop_msgfilter;
422 			break;
423 		case ROUTE_TABLEFILTER:
424 			m->m_len = sizeof(unsigned int);
425 			*mtod(m, unsigned int *) = rop->rop_rtableid;
426 			break;
427 		case ROUTE_PRIOFILTER:
428 			m->m_len = sizeof(unsigned int);
429 			*mtod(m, unsigned int *) = rop->rop_priority;
430 			break;
431 		case ROUTE_FLAGFILTER:
432 			m->m_len = sizeof(unsigned int);
433 			*mtod(m, unsigned int *) = rop->rop_flagfilter;
434 			break;
435 		default:
436 			error = ENOPROTOOPT;
437 			break;
438 		}
439 	}
440 	return (error);
441 }
442 
443 void
444 rtm_senddesync_timer(void *xso)
445 {
446 	struct socket	*so = xso;
447 
448 	solock(so);
449 	rtm_senddesync(so);
450 	sounlock(so);
451 }
452 
453 void
454 rtm_senddesync(struct socket *so)
455 {
456 	struct rtpcb	*rop = sotortpcb(so);
457 	struct mbuf	*desync_mbuf;
458 
459 	soassertlocked(so);
460 
461 	/*
462 	 * Dying socket is disconnected by upper layer and there is
463 	 * no reason to send packet. Also we shouldn't reschedule
464 	 * timeout(9), otherwise timeout_del_barrier(9) can't help us.
465 	 */
466 	if ((so->so_state & SS_ISCONNECTED) == 0 ||
467 	    (so->so_rcv.sb_state & SS_CANTRCVMORE))
468 		return;
469 
470 	/* If we are in a DESYNC state, try to send a RTM_DESYNC packet */
471 	if ((rop->rop_flags & ROUTECB_FLAG_DESYNC) == 0)
472 		return;
473 
474 	/*
475 	 * If we fail to alloc memory or if sbappendaddr()
476 	 * fails, re-add timeout and try again.
477 	 */
478 	desync_mbuf = rtm_msg1(RTM_DESYNC, NULL);
479 	if (desync_mbuf != NULL) {
480 		if (sbappendaddr(so, &so->so_rcv, &route_src,
481 		    desync_mbuf, NULL) != 0) {
482 			rop->rop_flags &= ~ROUTECB_FLAG_DESYNC;
483 			sorwakeup(rop->rop_socket);
484 			return;
485 		}
486 		m_freem(desync_mbuf);
487 	}
488 	/* Re-add timeout to try sending msg again */
489 	timeout_add_msec(&rop->rop_timeout, ROUTE_DESYNC_RESEND_TIMEOUT);
490 }
491 
492 void
493 route_input(struct mbuf *m0, struct socket *so0, sa_family_t sa_family)
494 {
495 	struct socket *so;
496 	struct rtpcb *rop;
497 	struct rt_msghdr *rtm;
498 	struct mbuf *m = m0;
499 	struct srp_ref sr;
500 
501 	/* ensure that we can access the rtm_type via mtod() */
502 	if (m->m_len < offsetof(struct rt_msghdr, rtm_type) + 1) {
503 		m_freem(m);
504 		return;
505 	}
506 
507 	SRPL_FOREACH(rop, &sr, &rtptable.rtp_list, rop_list) {
508 		/*
509 		 * If route socket is bound to an address family only send
510 		 * messages that match the address family. Address family
511 		 * agnostic messages are always sent.
512 		 */
513 		if (sa_family != AF_UNSPEC && rop->rop_proto != AF_UNSPEC &&
514 		    rop->rop_proto != sa_family)
515 			continue;
516 
517 
518 		so = rop->rop_socket;
519 		solock(so);
520 
521 		/*
522 		 * Check to see if we don't want our own messages and
523 		 * if we can receive anything.
524 		 */
525 		if ((so0 == so && !(so0->so_options & SO_USELOOPBACK)) ||
526 		    !(so->so_state & SS_ISCONNECTED) ||
527 		    (so->so_rcv.sb_state & SS_CANTRCVMORE))
528 			goto next;
529 
530 		/* filter messages that the process does not want */
531 		rtm = mtod(m, struct rt_msghdr *);
532 		/* but RTM_DESYNC can't be filtered */
533 		if (rtm->rtm_type != RTM_DESYNC) {
534 			if (rop->rop_msgfilter != 0 &&
535 			    !(rop->rop_msgfilter & (1U << rtm->rtm_type)))
536 				goto next;
537 			if (ISSET(rop->rop_flagfilter, rtm->rtm_flags))
538 				goto next;
539 		}
540 		switch (rtm->rtm_type) {
541 		case RTM_IFANNOUNCE:
542 		case RTM_DESYNC:
543 			/* no tableid */
544 			break;
545 		case RTM_RESOLVE:
546 		case RTM_NEWADDR:
547 		case RTM_DELADDR:
548 		case RTM_IFINFO:
549 		case RTM_80211INFO:
550 		case RTM_BFD:
551 			/* check against rdomain id */
552 			if (rop->rop_rtableid != RTABLE_ANY &&
553 			    rtable_l2(rop->rop_rtableid) != rtm->rtm_tableid)
554 				goto next;
555 			break;
556 		default:
557 			if (rop->rop_priority != 0 &&
558 			    rop->rop_priority < rtm->rtm_priority)
559 				goto next;
560 			/* check against rtable id */
561 			if (rop->rop_rtableid != RTABLE_ANY &&
562 			    rop->rop_rtableid != rtm->rtm_tableid)
563 				goto next;
564 			break;
565 		}
566 
567 		/*
568 		 * Check to see if the flush flag is set. If so, don't queue
569 		 * any more messages until the flag is cleared.
570 		 */
571 		if ((rop->rop_flags & ROUTECB_FLAG_FLUSH) != 0)
572 			goto next;
573 
574 		rtm_sendup(so, m);
575 next:
576 		sounlock(so);
577 	}
578 	SRPL_LEAVE(&sr);
579 
580 	m_freem(m);
581 }
582 
583 int
584 rtm_sendup(struct socket *so, struct mbuf *m0)
585 {
586 	struct rtpcb *rop = sotortpcb(so);
587 	struct mbuf *m;
588 
589 	soassertlocked(so);
590 
591 	m = m_copym(m0, 0, M_COPYALL, M_NOWAIT);
592 	if (m == NULL)
593 		return (ENOMEM);
594 
595 	if (sbspace(so, &so->so_rcv) < (2 * MSIZE) ||
596 	    sbappendaddr(so, &so->so_rcv, &route_src, m, NULL) == 0) {
597 		/* Flag socket as desync'ed and flush required */
598 		rop->rop_flags |= ROUTECB_FLAG_DESYNC | ROUTECB_FLAG_FLUSH;
599 		rtm_senddesync(so);
600 		m_freem(m);
601 		return (ENOBUFS);
602 	}
603 
604 	sorwakeup(so);
605 	return (0);
606 }
607 
608 struct rt_msghdr *
609 rtm_report(struct rtentry *rt, u_char type, int seq, int tableid)
610 {
611 	struct rt_msghdr	*rtm;
612 	struct rt_addrinfo	 info;
613 	struct sockaddr_rtlabel	 sa_rl;
614 	struct sockaddr_in6	 sa_mask;
615 #ifdef BFD
616 	struct sockaddr_bfd	 sa_bfd;
617 #endif
618 	struct ifnet		*ifp = NULL;
619 	int			 len;
620 
621 	bzero(&info, sizeof(info));
622 	info.rti_info[RTAX_DST] = rt_key(rt);
623 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
624 	info.rti_info[RTAX_NETMASK] = rt_plen2mask(rt, &sa_mask);
625 	info.rti_info[RTAX_LABEL] = rtlabel_id2sa(rt->rt_labelid, &sa_rl);
626 #ifdef BFD
627 	if (rt->rt_flags & RTF_BFD) {
628 		KERNEL_LOCK();
629 		info.rti_info[RTAX_BFD] = bfd2sa(rt, &sa_bfd);
630 		KERNEL_UNLOCK();
631 	}
632 #endif
633 #ifdef MPLS
634 	if (rt->rt_flags & RTF_MPLS) {
635 		struct sockaddr_mpls	 sa_mpls;
636 
637 		bzero(&sa_mpls, sizeof(sa_mpls));
638 		sa_mpls.smpls_family = AF_MPLS;
639 		sa_mpls.smpls_len = sizeof(sa_mpls);
640 		sa_mpls.smpls_label = ((struct rt_mpls *)
641 		    rt->rt_llinfo)->mpls_label;
642 		info.rti_info[RTAX_SRC] = (struct sockaddr *)&sa_mpls;
643 		info.rti_mpls = ((struct rt_mpls *)
644 		    rt->rt_llinfo)->mpls_operation;
645 	}
646 #endif
647 	ifp = if_get(rt->rt_ifidx);
648 	if (ifp != NULL) {
649 		info.rti_info[RTAX_IFP] = sdltosa(ifp->if_sadl);
650 		info.rti_info[RTAX_IFA] = rtable_getsource(tableid,
651 		    info.rti_info[RTAX_DST]->sa_family);
652 		if (info.rti_info[RTAX_IFA] == NULL)
653 			info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
654 		if (ifp->if_flags & IFF_POINTOPOINT)
655 			info.rti_info[RTAX_BRD] = rt->rt_ifa->ifa_dstaddr;
656 	}
657 	if_put(ifp);
658 	/* RTAX_GENMASK, RTAX_AUTHOR, RTAX_SRCMASK ignored */
659 
660 	/* build new route message */
661 	len = rtm_msg2(type, RTM_VERSION, &info, NULL, NULL);
662 	rtm = malloc(len, M_RTABLE, M_WAITOK | M_ZERO);
663 
664 	rtm_msg2(type, RTM_VERSION, &info, (caddr_t)rtm, NULL);
665 	rtm->rtm_type = type;
666 	rtm->rtm_index = rt->rt_ifidx;
667 	rtm->rtm_tableid = tableid;
668 	rtm->rtm_priority = rt->rt_priority & RTP_MASK;
669 	rtm->rtm_flags = rt->rt_flags;
670 	rtm->rtm_pid = curproc->p_p->ps_pid;
671 	rtm->rtm_seq = seq;
672 	rtm_getmetrics(rt, &rtm->rtm_rmx);
673 	rtm->rtm_addrs = info.rti_addrs;
674 #ifdef MPLS
675 	rtm->rtm_mpls = info.rti_mpls;
676 #endif
677 	return rtm;
678 }
679 
680 int
681 route_output(struct mbuf *m, struct socket *so)
682 {
683 	struct rt_msghdr	*rtm = NULL;
684 	struct rtentry		*rt = NULL;
685 	struct rt_addrinfo	 info;
686 	struct ifnet		*ifp;
687 	int			 len, seq, useloopback, error = 0;
688 	u_int			 tableid;
689 	u_int8_t		 prio;
690 	u_char			 vers, type;
691 
692 	if (m == NULL || ((m->m_len < sizeof(int32_t)) &&
693 	    (m = m_pullup(m, sizeof(int32_t))) == 0))
694 		return (ENOBUFS);
695 	if ((m->m_flags & M_PKTHDR) == 0)
696 		panic("route_output");
697 
698 	useloopback = so->so_options & SO_USELOOPBACK;
699 
700 	/*
701 	 * The socket can't be closed concurrently because the file
702 	 * descriptor reference is still held.
703 	 */
704 
705 	sounlock(so);
706 
707 	len = m->m_pkthdr.len;
708 	if (len < offsetof(struct rt_msghdr, rtm_hdrlen) + 1 ||
709 	    len != mtod(m, struct rt_msghdr *)->rtm_msglen) {
710 		error = EINVAL;
711 		goto fail;
712 	}
713 	vers = mtod(m, struct rt_msghdr *)->rtm_version;
714 	switch (vers) {
715 	case RTM_VERSION:
716 		if (len < sizeof(struct rt_msghdr)) {
717 			error = EINVAL;
718 			goto fail;
719 		}
720 		if (len > RTM_MAXSIZE) {
721 			error = EMSGSIZE;
722 			goto fail;
723 		}
724 		rtm = malloc(len, M_RTABLE, M_WAITOK);
725 		m_copydata(m, 0, len, rtm);
726 		break;
727 	default:
728 		error = EPROTONOSUPPORT;
729 		goto fail;
730 	}
731 
732 	/* Verify that the caller is sending an appropriate message early */
733 	switch (rtm->rtm_type) {
734 	case RTM_ADD:
735 	case RTM_DELETE:
736 	case RTM_GET:
737 	case RTM_CHANGE:
738 	case RTM_PROPOSAL:
739 	case RTM_SOURCE:
740 		break;
741 	default:
742 		error = EOPNOTSUPP;
743 		goto fail;
744 	}
745 	/*
746 	 * Verify that the header length is valid.
747 	 * All messages from userland start with a struct rt_msghdr.
748 	 */
749 	if (rtm->rtm_hdrlen == 0)	/* old client */
750 		rtm->rtm_hdrlen = sizeof(struct rt_msghdr);
751 	if (rtm->rtm_hdrlen < sizeof(struct rt_msghdr) ||
752 	    len < rtm->rtm_hdrlen) {
753 		error = EINVAL;
754 		goto fail;
755 	}
756 
757 	rtm->rtm_pid = curproc->p_p->ps_pid;
758 
759 	/*
760 	 * Verify that the caller has the appropriate privilege; RTM_GET
761 	 * is the only operation the non-superuser is allowed.
762 	 */
763 	if (rtm->rtm_type != RTM_GET && suser(curproc) != 0) {
764 		error = EACCES;
765 		goto fail;
766 	}
767 	tableid = rtm->rtm_tableid;
768 	if (!rtable_exists(tableid)) {
769 		if (rtm->rtm_type == RTM_ADD) {
770 			if ((error = rtable_add(tableid)) != 0)
771 				goto fail;
772 		} else {
773 			error = EINVAL;
774 			goto fail;
775 		}
776 	}
777 
778 	/* Do not let userland play with kernel-only flags. */
779 	if ((rtm->rtm_flags & (RTF_LOCAL|RTF_BROADCAST)) != 0) {
780 		error = EINVAL;
781 		goto fail;
782 	}
783 
784 	/* make sure that kernel-only bits are not set */
785 	rtm->rtm_priority &= RTP_MASK;
786 	rtm->rtm_flags &= ~(RTF_DONE|RTF_CLONED|RTF_CACHED);
787 	rtm->rtm_fmask &= RTF_FMASK;
788 
789 	if (rtm->rtm_priority != 0) {
790 		if (rtm->rtm_priority > RTP_MAX ||
791 		    rtm->rtm_priority == RTP_LOCAL) {
792 			error = EINVAL;
793 			goto fail;
794 		}
795 		prio = rtm->rtm_priority;
796 	} else if (rtm->rtm_type != RTM_ADD)
797 		prio = RTP_ANY;
798 	else if (rtm->rtm_flags & RTF_STATIC)
799 		prio = 0;
800 	else
801 		prio = RTP_DEFAULT;
802 
803 	bzero(&info, sizeof(info));
804 	info.rti_addrs = rtm->rtm_addrs;
805 	if ((error = rtm_xaddrs(rtm->rtm_hdrlen + (caddr_t)rtm,
806 	    len + (caddr_t)rtm, &info)) != 0)
807 		goto fail;
808 
809 	info.rti_flags = rtm->rtm_flags;
810 
811 	if (rtm->rtm_type != RTM_SOURCE &&
812 	    rtm->rtm_type != RTM_PROPOSAL &&
813 	    (info.rti_info[RTAX_DST] == NULL ||
814 	    info.rti_info[RTAX_DST]->sa_family >= AF_MAX ||
815 	    (info.rti_info[RTAX_GATEWAY] != NULL &&
816 	    info.rti_info[RTAX_GATEWAY]->sa_family >= AF_MAX) ||
817 	    info.rti_info[RTAX_GENMASK] != NULL)) {
818 		error = EINVAL;
819 		goto fail;
820 	}
821 #ifdef MPLS
822 	info.rti_mpls = rtm->rtm_mpls;
823 #endif
824 
825 	if (info.rti_info[RTAX_GATEWAY] != NULL &&
826 	    info.rti_info[RTAX_GATEWAY]->sa_family == AF_LINK &&
827 	    (info.rti_flags & RTF_CLONING) == 0) {
828 		info.rti_flags |= RTF_LLINFO;
829 	}
830 
831 	/*
832 	 * Validate RTM_PROPOSAL and pass it along or error out.
833 	 */
834 	if (rtm->rtm_type == RTM_PROPOSAL) {
835 		if (rtm_validate_proposal(&info) == -1) {
836 			error = EINVAL;
837 			goto fail;
838 		}
839 		/*
840 		 * If this is a solicitation proposal forward request to
841 		 * all interfaces. Most handlers will ignore it but at least
842 		 * umb(4) will send a response to this event.
843 		 */
844 		if (rtm->rtm_priority == RTP_PROPOSAL_SOLICIT) {
845 			NET_LOCK();
846 			TAILQ_FOREACH(ifp, &ifnetlist, if_list) {
847 				ifp->if_rtrequest(ifp, RTM_PROPOSAL, NULL);
848 			}
849 			NET_UNLOCK();
850 		}
851 	} else if (rtm->rtm_type == RTM_SOURCE) {
852 		if (info.rti_info[RTAX_IFA] == NULL) {
853 			error = EINVAL;
854 			goto fail;
855 		}
856 		NET_LOCK();
857 		error = rt_setsource(tableid, info.rti_info[RTAX_IFA]);
858 		NET_UNLOCK();
859 		if (error)
860 			goto fail;
861 	} else {
862 		error = rtm_output(rtm, &rt, &info, prio, tableid);
863 		if (!error) {
864 			type = rtm->rtm_type;
865 			seq = rtm->rtm_seq;
866 			free(rtm, M_RTABLE, len);
867 			NET_LOCK_SHARED();
868 			rtm = rtm_report(rt, type, seq, tableid);
869 			NET_UNLOCK_SHARED();
870 			len = rtm->rtm_msglen;
871 		}
872 	}
873 
874 	rtfree(rt);
875 	if (error) {
876 		rtm->rtm_errno = error;
877 	} else {
878 		rtm->rtm_flags |= RTF_DONE;
879 	}
880 
881 	/*
882 	 * Check to see if we don't want our own messages.
883 	 */
884 	if (!useloopback) {
885 		if (rtptable.rtp_count == 0) {
886 			/* no other listener and no loopback of messages */
887 			goto fail;
888 		}
889 	}
890 	if (m_copyback(m, 0, len, rtm, M_NOWAIT)) {
891 		m_freem(m);
892 		m = NULL;
893 	} else if (m->m_pkthdr.len > len)
894 		m_adj(m, len - m->m_pkthdr.len);
895 	free(rtm, M_RTABLE, len);
896 	if (m)
897 		route_input(m, so, info.rti_info[RTAX_DST] ?
898 		    info.rti_info[RTAX_DST]->sa_family : AF_UNSPEC);
899 	solock(so);
900 
901 	return (error);
902 fail:
903 	free(rtm, M_RTABLE, len);
904 	m_freem(m);
905 	solock(so);
906 
907 	return (error);
908 }
909 
910 int
911 rtm_output(struct rt_msghdr *rtm, struct rtentry **prt,
912     struct rt_addrinfo *info, uint8_t prio, unsigned int tableid)
913 {
914 	struct rtentry		*rt = *prt;
915 	struct ifnet		*ifp = NULL;
916 	int			 plen, newgate = 0, error = 0;
917 
918 	switch (rtm->rtm_type) {
919 	case RTM_ADD:
920 		if (info->rti_info[RTAX_GATEWAY] == NULL) {
921 			error = EINVAL;
922 			break;
923 		}
924 
925 		rt = rtable_match(tableid, info->rti_info[RTAX_DST], NULL);
926 		if ((error = route_arp_conflict(rt, info))) {
927 			rtfree(rt);
928 			rt = NULL;
929 			break;
930 		}
931 
932 		/*
933 		 * We cannot go through a delete/create/insert cycle for
934 		 * cached route because this can lead to races in the
935 		 * receive path.  Instead we update the L2 cache.
936 		 */
937 		if ((rt != NULL) && ISSET(rt->rt_flags, RTF_CACHED)) {
938 			ifp = if_get(rt->rt_ifidx);
939 			if (ifp == NULL) {
940 				rtfree(rt);
941 				rt = NULL;
942 				error = ESRCH;
943 				break;
944 			}
945 
946 			goto change;
947 		}
948 
949 		rtfree(rt);
950 		rt = NULL;
951 
952 		NET_LOCK();
953 		if ((error = rtm_getifa(info, tableid)) != 0) {
954 			NET_UNLOCK();
955 			break;
956 		}
957 		error = rtrequest(RTM_ADD, info, prio, &rt, tableid);
958 		NET_UNLOCK();
959 		if (error == 0)
960 			rtm_setmetrics(rtm->rtm_inits, &rtm->rtm_rmx,
961 			    &rt->rt_rmx);
962 		break;
963 	case RTM_DELETE:
964 		rt = rtable_lookup(tableid, info->rti_info[RTAX_DST],
965 		    info->rti_info[RTAX_NETMASK], info->rti_info[RTAX_GATEWAY],
966 		    prio);
967 		if (rt == NULL) {
968 			error = ESRCH;
969 			break;
970 		}
971 
972 		/*
973 		 * If we got multipath routes, we require users to specify
974 		 * a matching gateway.
975 		 */
976 		if (ISSET(rt->rt_flags, RTF_MPATH) &&
977 		    info->rti_info[RTAX_GATEWAY] == NULL) {
978 			error = ESRCH;
979 			break;
980 		}
981 
982 		ifp = if_get(rt->rt_ifidx);
983 		if (ifp == NULL) {
984 			rtfree(rt);
985 			rt = NULL;
986 			error = ESRCH;
987 			break;
988 		}
989 
990 		/*
991 		 * Invalidate the cache of automagically created and
992 		 * referenced L2 entries to make sure that ``rt_gwroute''
993 		 * pointer stays valid for other CPUs.
994 		 */
995 		if ((ISSET(rt->rt_flags, RTF_CACHED))) {
996 			NET_LOCK();
997 			ifp->if_rtrequest(ifp, RTM_INVALIDATE, rt);
998 			/* Reset the MTU of the gateway route. */
999 			rtable_walk(tableid, rt_key(rt)->sa_family, NULL,
1000 			    route_cleargateway, rt);
1001 			NET_UNLOCK();
1002 			break;
1003 		}
1004 
1005 		/*
1006 		 * Make sure that local routes are only modified by the
1007 		 * kernel.
1008 		 */
1009 		if (ISSET(rt->rt_flags, RTF_LOCAL|RTF_BROADCAST)) {
1010 			error = EINVAL;
1011 			break;
1012 		}
1013 
1014 		rtfree(rt);
1015 		rt = NULL;
1016 
1017 		NET_LOCK();
1018 		error = rtrequest_delete(info, prio, ifp, &rt, tableid);
1019 		NET_UNLOCK();
1020 		break;
1021 	case RTM_CHANGE:
1022 		rt = rtable_lookup(tableid, info->rti_info[RTAX_DST],
1023 		    info->rti_info[RTAX_NETMASK], info->rti_info[RTAX_GATEWAY],
1024 		    prio);
1025 		/*
1026 		 * If we got multipath routes, we require users to specify
1027 		 * a matching gateway.
1028 		 */
1029 		if ((rt != NULL) && ISSET(rt->rt_flags, RTF_MPATH) &&
1030 		    (info->rti_info[RTAX_GATEWAY] == NULL)) {
1031 			rtfree(rt);
1032 			rt = NULL;
1033 		}
1034 
1035 		/*
1036 		 * If RTAX_GATEWAY is the argument we're trying to
1037 		 * change, try to find a compatible route.
1038 		 */
1039 		if ((rt == NULL) && (info->rti_info[RTAX_GATEWAY] != NULL)) {
1040 			rt = rtable_lookup(tableid, info->rti_info[RTAX_DST],
1041 			    info->rti_info[RTAX_NETMASK], NULL, prio);
1042 			/* Ensure we don't pick a multipath one. */
1043 			if ((rt != NULL) && ISSET(rt->rt_flags, RTF_MPATH)) {
1044 				rtfree(rt);
1045 				rt = NULL;
1046 			}
1047 		}
1048 
1049 		if (rt == NULL) {
1050 			error = ESRCH;
1051 			break;
1052 		}
1053 
1054 		/*
1055 		 * Make sure that local routes are only modified by the
1056 		 * kernel.
1057 		 */
1058 		if (ISSET(rt->rt_flags, RTF_LOCAL|RTF_BROADCAST)) {
1059 			error = EINVAL;
1060 			break;
1061 		}
1062 
1063 		ifp = if_get(rt->rt_ifidx);
1064 		if (ifp == NULL) {
1065 			rtfree(rt);
1066 			rt = NULL;
1067 			error = ESRCH;
1068 			break;
1069 		}
1070 
1071 		/*
1072 		 * RTM_CHANGE needs a perfect match.
1073 		 */
1074 		plen = rtable_satoplen(info->rti_info[RTAX_DST]->sa_family,
1075 		    info->rti_info[RTAX_NETMASK]);
1076 		if (rt_plen(rt) != plen) {
1077 			error = ESRCH;
1078 			break;
1079 		}
1080 
1081 		if (info->rti_info[RTAX_GATEWAY] != NULL)
1082 			if (rt->rt_gateway == NULL ||
1083 			    bcmp(rt->rt_gateway,
1084 			    info->rti_info[RTAX_GATEWAY],
1085 			    info->rti_info[RTAX_GATEWAY]->sa_len)) {
1086 				newgate = 1;
1087 			}
1088 		/*
1089 		 * Check reachable gateway before changing the route.
1090 		 * New gateway could require new ifaddr, ifp;
1091 		 * flags may also be different; ifp may be specified
1092 		 * by ll sockaddr when protocol address is ambiguous.
1093 		 */
1094 		if (newgate || info->rti_info[RTAX_IFP] != NULL ||
1095 		    info->rti_info[RTAX_IFA] != NULL) {
1096 			struct ifaddr	*ifa = NULL;
1097 
1098 			NET_LOCK();
1099 			if ((error = rtm_getifa(info, tableid)) != 0) {
1100 				NET_UNLOCK();
1101 				break;
1102 			}
1103 			ifa = info->rti_ifa;
1104 			if (rt->rt_ifa != ifa) {
1105 				ifp->if_rtrequest(ifp, RTM_DELETE, rt);
1106 				ifafree(rt->rt_ifa);
1107 
1108 				rt->rt_ifa = ifaref(ifa);
1109 				rt->rt_ifidx = ifa->ifa_ifp->if_index;
1110 				/* recheck link state after ifp change */
1111 				rt_if_linkstate_change(rt, ifa->ifa_ifp,
1112 				    tableid);
1113 			}
1114 			NET_UNLOCK();
1115 		}
1116 change:
1117 		if (info->rti_info[RTAX_GATEWAY] != NULL) {
1118 			/* When updating the gateway, make sure it is valid. */
1119 			if (!newgate && rt->rt_gateway->sa_family !=
1120 			    info->rti_info[RTAX_GATEWAY]->sa_family) {
1121 				error = EINVAL;
1122 				break;
1123 			}
1124 
1125 			NET_LOCK();
1126 			error = rt_setgate(rt,
1127 			    info->rti_info[RTAX_GATEWAY], tableid);
1128 			NET_UNLOCK();
1129 			if (error)
1130 				break;
1131 		}
1132 #ifdef MPLS
1133 		if (rtm->rtm_flags & RTF_MPLS) {
1134 			NET_LOCK();
1135 			error = rt_mpls_set(rt,
1136 			    info->rti_info[RTAX_SRC], info->rti_mpls);
1137 			NET_UNLOCK();
1138 			if (error)
1139 				break;
1140 		} else if (newgate || (rtm->rtm_fmask & RTF_MPLS)) {
1141 			NET_LOCK();
1142 			/* if gateway changed remove MPLS information */
1143 			rt_mpls_clear(rt);
1144 			NET_UNLOCK();
1145 		}
1146 #endif
1147 
1148 #ifdef BFD
1149 		if (ISSET(rtm->rtm_flags, RTF_BFD)) {
1150 			KERNEL_LOCK();
1151 			error = bfdset(rt);
1152 			KERNEL_UNLOCK();
1153 			if (error)
1154 				break;
1155 		} else if (!ISSET(rtm->rtm_flags, RTF_BFD) &&
1156 		    ISSET(rtm->rtm_fmask, RTF_BFD)) {
1157 			KERNEL_LOCK();
1158 			bfdclear(rt);
1159 			KERNEL_UNLOCK();
1160 		}
1161 #endif
1162 
1163 		NET_LOCK();
1164 		/* Hack to allow some flags to be toggled */
1165 		if (rtm->rtm_fmask) {
1166 			/* MPLS flag it is set by rt_mpls_set() */
1167 			rtm->rtm_fmask &= ~RTF_MPLS;
1168 			rtm->rtm_flags &= ~RTF_MPLS;
1169 			rt->rt_flags =
1170 			    (rt->rt_flags & ~rtm->rtm_fmask) |
1171 			    (rtm->rtm_flags & rtm->rtm_fmask);
1172 		}
1173 		rtm_setmetrics(rtm->rtm_inits, &rtm->rtm_rmx, &rt->rt_rmx);
1174 
1175 		ifp->if_rtrequest(ifp, RTM_ADD, rt);
1176 
1177 		if (info->rti_info[RTAX_LABEL] != NULL) {
1178 			char *rtlabel = ((struct sockaddr_rtlabel *)
1179 			    info->rti_info[RTAX_LABEL])->sr_label;
1180 			rtlabel_unref(rt->rt_labelid);
1181 			rt->rt_labelid = rtlabel_name2id(rtlabel);
1182 		}
1183 		if_group_routechange(info->rti_info[RTAX_DST],
1184 		    info->rti_info[RTAX_NETMASK]);
1185 		rt->rt_locks &= ~(rtm->rtm_inits);
1186 		rt->rt_locks |= (rtm->rtm_inits & rtm->rtm_rmx.rmx_locks);
1187 		NET_UNLOCK();
1188 		break;
1189 	case RTM_GET:
1190 		rt = rtable_lookup(tableid, info->rti_info[RTAX_DST],
1191 		    info->rti_info[RTAX_NETMASK], info->rti_info[RTAX_GATEWAY],
1192 		    prio);
1193 		if (rt == NULL)
1194 			error = ESRCH;
1195 		break;
1196 	}
1197 
1198 	if_put(ifp);
1199 	*prt = rt;
1200 	return (error);
1201 }
1202 
1203 struct ifaddr *
1204 ifa_ifwithroute(int flags, struct sockaddr *dst, struct sockaddr *gateway,
1205     unsigned int rtableid)
1206 {
1207 	struct ifaddr	*ifa;
1208 
1209 	if ((flags & RTF_GATEWAY) == 0) {
1210 		/*
1211 		 * If we are adding a route to an interface,
1212 		 * and the interface is a pt to pt link
1213 		 * we should search for the destination
1214 		 * as our clue to the interface.  Otherwise
1215 		 * we can use the local address.
1216 		 */
1217 		ifa = NULL;
1218 		if (flags & RTF_HOST)
1219 			ifa = ifa_ifwithdstaddr(dst, rtableid);
1220 		if (ifa == NULL)
1221 			ifa = ifa_ifwithaddr(gateway, rtableid);
1222 	} else {
1223 		/*
1224 		 * If we are adding a route to a remote net
1225 		 * or host, the gateway may still be on the
1226 		 * other end of a pt to pt link.
1227 		 */
1228 		ifa = ifa_ifwithdstaddr(gateway, rtableid);
1229 	}
1230 	if (ifa == NULL) {
1231 		if (gateway->sa_family == AF_LINK) {
1232 			struct sockaddr_dl *sdl = satosdl(gateway);
1233 			struct ifnet *ifp = if_get(sdl->sdl_index);
1234 
1235 			if (ifp != NULL)
1236 				ifa = ifaof_ifpforaddr(dst, ifp);
1237 			if_put(ifp);
1238 		} else {
1239 			struct rtentry *rt;
1240 
1241 			rt = rtalloc(gateway, RT_RESOLVE, rtable_l2(rtableid));
1242 			if (rt != NULL)
1243 				ifa = rt->rt_ifa;
1244 			rtfree(rt);
1245 		}
1246 	}
1247 	if (ifa == NULL)
1248 		return (NULL);
1249 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
1250 		struct ifaddr	*oifa = ifa;
1251 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
1252 		if (ifa == NULL)
1253 			ifa = oifa;
1254 	}
1255 	return (ifa);
1256 }
1257 
1258 int
1259 rtm_getifa(struct rt_addrinfo *info, unsigned int rtid)
1260 {
1261 	struct ifnet	*ifp = NULL;
1262 
1263 	/*
1264 	 * The "returned" `ifa' is guaranteed to be alive only if
1265 	 * the NET_LOCK() is held.
1266 	 */
1267 	NET_ASSERT_LOCKED();
1268 
1269 	/*
1270 	 * ifp may be specified by sockaddr_dl when protocol address
1271 	 * is ambiguous
1272 	 */
1273 	if (info->rti_info[RTAX_IFP] != NULL) {
1274 		struct sockaddr_dl *sdl;
1275 
1276 		sdl = satosdl(info->rti_info[RTAX_IFP]);
1277 		ifp = if_get(sdl->sdl_index);
1278 	}
1279 
1280 #ifdef IPSEC
1281 	/*
1282 	 * If the destination is a PF_KEY address, we'll look
1283 	 * for the existence of a encap interface number or address
1284 	 * in the options list of the gateway. By default, we'll return
1285 	 * enc0.
1286 	 */
1287 	if (info->rti_info[RTAX_DST] &&
1288 	    info->rti_info[RTAX_DST]->sa_family == PF_KEY)
1289 		info->rti_ifa = enc_getifa(rtid, 0);
1290 #endif
1291 
1292 	if (info->rti_ifa == NULL && info->rti_info[RTAX_IFA] != NULL)
1293 		info->rti_ifa = ifa_ifwithaddr(info->rti_info[RTAX_IFA], rtid);
1294 
1295 	if (info->rti_ifa == NULL) {
1296 		struct sockaddr	*sa;
1297 
1298 		if ((sa = info->rti_info[RTAX_IFA]) == NULL)
1299 			if ((sa = info->rti_info[RTAX_GATEWAY]) == NULL)
1300 				sa = info->rti_info[RTAX_DST];
1301 
1302 		if (sa != NULL && ifp != NULL)
1303 			info->rti_ifa = ifaof_ifpforaddr(sa, ifp);
1304 		else if (info->rti_info[RTAX_DST] != NULL &&
1305 		    info->rti_info[RTAX_GATEWAY] != NULL)
1306 			info->rti_ifa = ifa_ifwithroute(info->rti_flags,
1307 			    info->rti_info[RTAX_DST],
1308 			    info->rti_info[RTAX_GATEWAY],
1309 			    rtid);
1310 		else if (sa != NULL)
1311 			info->rti_ifa = ifa_ifwithroute(info->rti_flags,
1312 			    sa, sa, rtid);
1313 	}
1314 
1315 	if_put(ifp);
1316 
1317 	if (info->rti_ifa == NULL)
1318 		return (ENETUNREACH);
1319 
1320 	return (0);
1321 }
1322 
1323 int
1324 route_cleargateway(struct rtentry *rt, void *arg, unsigned int rtableid)
1325 {
1326 	struct rtentry *nhrt = arg;
1327 
1328 	if (ISSET(rt->rt_flags, RTF_GATEWAY) && rt->rt_gwroute == nhrt &&
1329 	    !ISSET(rt->rt_locks, RTV_MTU))
1330 		rt->rt_mtu = 0;
1331 
1332 	return (0);
1333 }
1334 
1335 /*
1336  * Check if the user request to insert an ARP entry does not conflict
1337  * with existing ones.
1338  *
1339  * Only two entries are allowed for a given IP address: a private one
1340  * (priv) and a public one (pub).
1341  */
1342 int
1343 route_arp_conflict(struct rtentry *rt, struct rt_addrinfo *info)
1344 {
1345 	int		 proxy = (info->rti_flags & RTF_ANNOUNCE);
1346 
1347 	if ((info->rti_flags & RTF_LLINFO) == 0 ||
1348 	    (info->rti_info[RTAX_DST]->sa_family != AF_INET))
1349 		return (0);
1350 
1351 	if (rt == NULL || !ISSET(rt->rt_flags, RTF_LLINFO))
1352 		return (0);
1353 
1354 	/* If the entry is cached, it can be updated. */
1355 	if (ISSET(rt->rt_flags, RTF_CACHED))
1356 		return (0);
1357 
1358 	/*
1359 	 * Same destination, not cached and both "priv" or "pub" conflict.
1360 	 * If a second entry exists, it always conflict.
1361 	 */
1362 	if ((ISSET(rt->rt_flags, RTF_ANNOUNCE) == proxy) ||
1363 	    ISSET(rt->rt_flags, RTF_MPATH))
1364 		return (EEXIST);
1365 
1366 	/* No conflict but an entry exist so we need to force mpath. */
1367 	info->rti_flags |= RTF_MPATH;
1368 	return (0);
1369 }
1370 
1371 void
1372 rtm_setmetrics(u_long which, const struct rt_metrics *in,
1373     struct rt_kmetrics *out)
1374 {
1375 	int64_t expire;
1376 
1377 	if (which & RTV_MTU)
1378 		out->rmx_mtu = in->rmx_mtu;
1379 	if (which & RTV_EXPIRE) {
1380 		expire = in->rmx_expire;
1381 		if (expire != 0) {
1382 			expire -= gettime();
1383 			expire += getuptime();
1384 		}
1385 
1386 		out->rmx_expire = expire;
1387 	}
1388 }
1389 
1390 void
1391 rtm_getmetrics(const struct rtentry *rt, struct rt_metrics *out)
1392 {
1393 	const struct rt_kmetrics *in = &rt->rt_rmx;
1394 	int64_t expire;
1395 
1396 	expire = in->rmx_expire;
1397 	if (expire == 0)
1398 		expire = rt_timer_get_expire(rt);
1399 	if (expire != 0) {
1400 		expire -= getuptime();
1401 		expire += gettime();
1402 	}
1403 
1404 	bzero(out, sizeof(*out));
1405 	out->rmx_locks = in->rmx_locks;
1406 	out->rmx_mtu = in->rmx_mtu;
1407 	out->rmx_expire = expire;
1408 	out->rmx_pksent = in->rmx_pksent;
1409 }
1410 
1411 #define ROUNDUP(a) \
1412 	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
1413 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
1414 
1415 int
1416 rtm_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
1417 {
1418 	struct sockaddr	*sa;
1419 	int		 i;
1420 
1421 	/*
1422 	 * Parse address bits, split address storage in chunks, and
1423 	 * set info pointers.  Use sa_len for traversing the memory
1424 	 * and check that we stay within in the limit.
1425 	 */
1426 	bzero(rtinfo->rti_info, sizeof(rtinfo->rti_info));
1427 	for (i = 0; i < sizeof(rtinfo->rti_addrs) * 8; i++) {
1428 		if ((rtinfo->rti_addrs & (1U << i)) == 0)
1429 			continue;
1430 		if (i >= RTAX_MAX || cp + sizeof(socklen_t) > cplim)
1431 			return (EINVAL);
1432 		sa = (struct sockaddr *)cp;
1433 		if (cp + sa->sa_len > cplim)
1434 			return (EINVAL);
1435 		rtinfo->rti_info[i] = sa;
1436 		ADVANCE(cp, sa);
1437 	}
1438 	/*
1439 	 * Check that the address family is suitable for the route address
1440 	 * type.  Check that each address has a size that fits its family
1441 	 * and its length is within the size.  Strings within addresses must
1442 	 * be NUL terminated.
1443 	 */
1444 	for (i = 0; i < RTAX_MAX; i++) {
1445 		size_t len, maxlen, size;
1446 
1447 		sa = rtinfo->rti_info[i];
1448 		if (sa == NULL)
1449 			continue;
1450 		maxlen = size = 0;
1451 		switch (i) {
1452 		case RTAX_DST:
1453 		case RTAX_GATEWAY:
1454 		case RTAX_SRC:
1455 			switch (sa->sa_family) {
1456 			case AF_INET:
1457 				size = sizeof(struct sockaddr_in);
1458 				break;
1459 			case AF_LINK:
1460 				size = sizeof(struct sockaddr_dl);
1461 				break;
1462 #ifdef INET6
1463 			case AF_INET6:
1464 				size = sizeof(struct sockaddr_in6);
1465 				break;
1466 #endif
1467 #ifdef MPLS
1468 			case AF_MPLS:
1469 				size = sizeof(struct sockaddr_mpls);
1470 				break;
1471 #endif
1472 			}
1473 			break;
1474 		case RTAX_IFP:
1475 			if (sa->sa_family != AF_LINK)
1476 				return (EAFNOSUPPORT);
1477 			/*
1478 			 * XXX Should be sizeof(struct sockaddr_dl), but
1479 			 * route(8) has a bug and provides less memory.
1480 			 * arp(8) has another bug and uses sizeof pointer.
1481 			 */
1482 			size = 4;
1483 			break;
1484 		case RTAX_IFA:
1485 			switch (sa->sa_family) {
1486 			case AF_INET:
1487 				size = sizeof(struct sockaddr_in);
1488 				break;
1489 #ifdef INET6
1490 			case AF_INET6:
1491 				size = sizeof(struct sockaddr_in6);
1492 				break;
1493 #endif
1494 			default:
1495 				return (EAFNOSUPPORT);
1496 			}
1497 			break;
1498 		case RTAX_LABEL:
1499 			sa->sa_family = AF_UNSPEC;
1500 			maxlen = RTLABEL_LEN;
1501 			size = sizeof(struct sockaddr_rtlabel);
1502 			break;
1503 #ifdef BFD
1504 		case RTAX_BFD:
1505 			sa->sa_family = AF_UNSPEC;
1506 			size = sizeof(struct sockaddr_bfd);
1507 			break;
1508 #endif
1509 		case RTAX_DNS:
1510 			/* more validation in rtm_validate_proposal */
1511 			if (sa->sa_len > sizeof(struct sockaddr_rtdns))
1512 				return (EINVAL);
1513 			if (sa->sa_len < offsetof(struct sockaddr_rtdns,
1514 			    sr_dns))
1515 				return (EINVAL);
1516 			switch (sa->sa_family) {
1517 			case AF_INET:
1518 #ifdef INET6
1519 			case AF_INET6:
1520 #endif
1521 				break;
1522 			default:
1523 				return (EAFNOSUPPORT);
1524 			}
1525 			break;
1526 		case RTAX_STATIC:
1527 			sa->sa_family = AF_UNSPEC;
1528 			maxlen = RTSTATIC_LEN;
1529 			size = sizeof(struct sockaddr_rtstatic);
1530 			break;
1531 		case RTAX_SEARCH:
1532 			sa->sa_family = AF_UNSPEC;
1533 			maxlen = RTSEARCH_LEN;
1534 			size = sizeof(struct sockaddr_rtsearch);
1535 			break;
1536 		}
1537 		if (size) {
1538 			/* memory for the full struct must be provided */
1539 			if (sa->sa_len < size)
1540 				return (EINVAL);
1541 		}
1542 		if (maxlen) {
1543 			/* this should not happen */
1544 			if (2 + maxlen > size)
1545 				return (EINVAL);
1546 			/* strings must be NUL terminated within the struct */
1547 			len = strnlen(sa->sa_data, maxlen);
1548 			if (len >= maxlen || 2 + len >= sa->sa_len)
1549 				return (EINVAL);
1550 			break;
1551 		}
1552 	}
1553 	return (0);
1554 }
1555 
1556 struct mbuf *
1557 rtm_msg1(int type, struct rt_addrinfo *rtinfo)
1558 {
1559 	struct rt_msghdr	*rtm;
1560 	struct mbuf		*m;
1561 	int			 i;
1562 	struct sockaddr		*sa;
1563 	int			 len, dlen, hlen;
1564 
1565 	switch (type) {
1566 	case RTM_DELADDR:
1567 	case RTM_NEWADDR:
1568 		hlen = sizeof(struct ifa_msghdr);
1569 		break;
1570 	case RTM_IFINFO:
1571 		hlen = sizeof(struct if_msghdr);
1572 		break;
1573 	case RTM_IFANNOUNCE:
1574 		hlen = sizeof(struct if_announcemsghdr);
1575 		break;
1576 #ifdef BFD
1577 	case RTM_BFD:
1578 		hlen = sizeof(struct bfd_msghdr);
1579 		break;
1580 #endif
1581 	case RTM_80211INFO:
1582 		hlen = sizeof(struct if_ieee80211_msghdr);
1583 		break;
1584 	default:
1585 		hlen = sizeof(struct rt_msghdr);
1586 		break;
1587 	}
1588 	len = hlen;
1589 	for (i = 0; i < RTAX_MAX; i++) {
1590 		if (rtinfo == NULL || (sa = rtinfo->rti_info[i]) == NULL)
1591 			continue;
1592 		len += ROUNDUP(sa->sa_len);
1593 	}
1594 	if (len > MCLBYTES)
1595 		panic("rtm_msg1");
1596 	m = m_gethdr(M_DONTWAIT, MT_DATA);
1597 	if (m && len > MHLEN) {
1598 		MCLGET(m, M_DONTWAIT);
1599 		if ((m->m_flags & M_EXT) == 0) {
1600 			m_free(m);
1601 			m = NULL;
1602 		}
1603 	}
1604 	if (m == NULL)
1605 		return (m);
1606 	m->m_pkthdr.len = m->m_len = len;
1607 	m->m_pkthdr.ph_ifidx = 0;
1608 	rtm = mtod(m, struct rt_msghdr *);
1609 	bzero(rtm, len);
1610 	len = hlen;
1611 	for (i = 0; i < RTAX_MAX; i++) {
1612 		if (rtinfo == NULL || (sa = rtinfo->rti_info[i]) == NULL)
1613 			continue;
1614 		rtinfo->rti_addrs |= (1U << i);
1615 		dlen = ROUNDUP(sa->sa_len);
1616 		if (m_copyback(m, len, sa->sa_len, sa, M_NOWAIT)) {
1617 			m_freem(m);
1618 			return (NULL);
1619 		}
1620 		len += dlen;
1621 	}
1622 	rtm->rtm_msglen = len;
1623 	rtm->rtm_hdrlen = hlen;
1624 	rtm->rtm_version = RTM_VERSION;
1625 	rtm->rtm_type = type;
1626 	return (m);
1627 }
1628 
1629 int
1630 rtm_msg2(int type, int vers, struct rt_addrinfo *rtinfo, caddr_t cp,
1631     struct walkarg *w)
1632 {
1633 	int		i;
1634 	int		len, dlen, hlen, second_time = 0;
1635 	caddr_t		cp0;
1636 
1637 	rtinfo->rti_addrs = 0;
1638 again:
1639 	switch (type) {
1640 	case RTM_DELADDR:
1641 	case RTM_NEWADDR:
1642 		len = sizeof(struct ifa_msghdr);
1643 		break;
1644 	case RTM_IFINFO:
1645 		len = sizeof(struct if_msghdr);
1646 		break;
1647 	default:
1648 		len = sizeof(struct rt_msghdr);
1649 		break;
1650 	}
1651 	hlen = len;
1652 	if ((cp0 = cp) != NULL)
1653 		cp += len;
1654 	for (i = 0; i < RTAX_MAX; i++) {
1655 		struct sockaddr *sa;
1656 
1657 		if ((sa = rtinfo->rti_info[i]) == NULL)
1658 			continue;
1659 		rtinfo->rti_addrs |= (1U << i);
1660 		dlen = ROUNDUP(sa->sa_len);
1661 		if (cp) {
1662 			bcopy(sa, cp, sa->sa_len);
1663 			bzero(cp + sa->sa_len, dlen - sa->sa_len);
1664 			cp += dlen;
1665 		}
1666 		len += dlen;
1667 	}
1668 	/* align message length to the next natural boundary */
1669 	len = ALIGN(len);
1670 	if (cp == 0 && w != NULL && !second_time) {
1671 		w->w_needed += len;
1672 		if (w->w_needed <= w->w_given && w->w_where) {
1673 			if (w->w_tmemsize < len) {
1674 				free(w->w_tmem, M_RTABLE, w->w_tmemsize);
1675 				w->w_tmem = malloc(len, M_RTABLE,
1676 				    M_NOWAIT | M_ZERO);
1677 				if (w->w_tmem)
1678 					w->w_tmemsize = len;
1679 			}
1680 			if (w->w_tmem) {
1681 				cp = w->w_tmem;
1682 				second_time = 1;
1683 				goto again;
1684 			} else
1685 				w->w_where = 0;
1686 		}
1687 	}
1688 	if (cp && w)		/* clear the message header */
1689 		bzero(cp0, hlen);
1690 
1691 	if (cp) {
1692 		struct rt_msghdr *rtm = (struct rt_msghdr *)cp0;
1693 
1694 		rtm->rtm_version = RTM_VERSION;
1695 		rtm->rtm_type = type;
1696 		rtm->rtm_msglen = len;
1697 		rtm->rtm_hdrlen = hlen;
1698 	}
1699 	return (len);
1700 }
1701 
1702 void
1703 rtm_send(struct rtentry *rt, int cmd, int error, unsigned int rtableid)
1704 {
1705 	struct rt_addrinfo	 info;
1706 	struct ifnet		*ifp;
1707 	struct sockaddr_rtlabel	 sa_rl;
1708 	struct sockaddr_in6	 sa_mask;
1709 
1710 	memset(&info, 0, sizeof(info));
1711 	info.rti_info[RTAX_DST] = rt_key(rt);
1712 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1713 	if (!ISSET(rt->rt_flags, RTF_HOST))
1714 		info.rti_info[RTAX_NETMASK] = rt_plen2mask(rt, &sa_mask);
1715 	info.rti_info[RTAX_LABEL] = rtlabel_id2sa(rt->rt_labelid, &sa_rl);
1716 	ifp = if_get(rt->rt_ifidx);
1717 	if (ifp != NULL) {
1718 		info.rti_info[RTAX_IFP] = sdltosa(ifp->if_sadl);
1719 		info.rti_info[RTAX_IFA] = rtable_getsource(rtableid,
1720 		    info.rti_info[RTAX_DST]->sa_family);
1721 		if (info.rti_info[RTAX_IFA] == NULL)
1722 			info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
1723 	}
1724 
1725 	rtm_miss(cmd, &info, rt->rt_flags, rt->rt_priority, rt->rt_ifidx, error,
1726 	    rtableid);
1727 	if_put(ifp);
1728 }
1729 
1730 /*
1731  * This routine is called to generate a message from the routing
1732  * socket indicating that a redirect has occurred, a routing lookup
1733  * has failed, or that a protocol has detected timeouts to a particular
1734  * destination.
1735  */
1736 void
1737 rtm_miss(int type, struct rt_addrinfo *rtinfo, int flags, uint8_t prio,
1738     u_int ifidx, int error, u_int tableid)
1739 {
1740 	struct rt_msghdr	*rtm;
1741 	struct mbuf		*m;
1742 	struct sockaddr		*sa = rtinfo->rti_info[RTAX_DST];
1743 
1744 	if (rtptable.rtp_count == 0)
1745 		return;
1746 	m = rtm_msg1(type, rtinfo);
1747 	if (m == NULL)
1748 		return;
1749 	rtm = mtod(m, struct rt_msghdr *);
1750 	rtm->rtm_flags = RTF_DONE | flags;
1751 	rtm->rtm_priority = prio;
1752 	rtm->rtm_errno = error;
1753 	rtm->rtm_tableid = tableid;
1754 	rtm->rtm_addrs = rtinfo->rti_addrs;
1755 	rtm->rtm_index = ifidx;
1756 	route_input(m, NULL, sa ? sa->sa_family : AF_UNSPEC);
1757 }
1758 
1759 /*
1760  * This routine is called to generate a message from the routing
1761  * socket indicating that the status of a network interface has changed.
1762  */
1763 void
1764 rtm_ifchg(struct ifnet *ifp)
1765 {
1766 	struct rt_addrinfo	 info;
1767 	struct if_msghdr	*ifm;
1768 	struct mbuf		*m;
1769 
1770 	if (rtptable.rtp_count == 0)
1771 		return;
1772 	memset(&info, 0, sizeof(info));
1773 	info.rti_info[RTAX_IFP] = sdltosa(ifp->if_sadl);
1774 	m = rtm_msg1(RTM_IFINFO, &info);
1775 	if (m == NULL)
1776 		return;
1777 	ifm = mtod(m, struct if_msghdr *);
1778 	ifm->ifm_index = ifp->if_index;
1779 	ifm->ifm_tableid = ifp->if_rdomain;
1780 	ifm->ifm_flags = ifp->if_flags;
1781 	ifm->ifm_xflags = ifp->if_xflags;
1782 	if_getdata(ifp, &ifm->ifm_data);
1783 	ifm->ifm_addrs = info.rti_addrs;
1784 	route_input(m, NULL, AF_UNSPEC);
1785 }
1786 
1787 /*
1788  * This is called to generate messages from the routing socket
1789  * indicating a network interface has had addresses associated with it.
1790  * if we ever reverse the logic and replace messages TO the routing
1791  * socket indicate a request to configure interfaces, then it will
1792  * be unnecessary as the routing socket will automatically generate
1793  * copies of it.
1794  */
1795 void
1796 rtm_addr(int cmd, struct ifaddr *ifa)
1797 {
1798 	struct ifnet		*ifp = ifa->ifa_ifp;
1799 	struct mbuf		*m;
1800 	struct rt_addrinfo	 info;
1801 	struct ifa_msghdr	*ifam;
1802 
1803 	if (rtptable.rtp_count == 0)
1804 		return;
1805 
1806 	memset(&info, 0, sizeof(info));
1807 	info.rti_info[RTAX_IFA] = ifa->ifa_addr;
1808 	info.rti_info[RTAX_IFP] = sdltosa(ifp->if_sadl);
1809 	info.rti_info[RTAX_NETMASK] = ifa->ifa_netmask;
1810 	info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
1811 	if ((m = rtm_msg1(cmd, &info)) == NULL)
1812 		return;
1813 	ifam = mtod(m, struct ifa_msghdr *);
1814 	ifam->ifam_index = ifp->if_index;
1815 	ifam->ifam_metric = ifa->ifa_metric;
1816 	ifam->ifam_flags = ifa->ifa_flags;
1817 	ifam->ifam_addrs = info.rti_addrs;
1818 	ifam->ifam_tableid = ifp->if_rdomain;
1819 
1820 	route_input(m, NULL,
1821 	    ifa->ifa_addr ? ifa->ifa_addr->sa_family : AF_UNSPEC);
1822 }
1823 
1824 /*
1825  * This is called to generate routing socket messages indicating
1826  * network interface arrival and departure.
1827  */
1828 void
1829 rtm_ifannounce(struct ifnet *ifp, int what)
1830 {
1831 	struct if_announcemsghdr	*ifan;
1832 	struct mbuf			*m;
1833 
1834 	if (rtptable.rtp_count == 0)
1835 		return;
1836 	m = rtm_msg1(RTM_IFANNOUNCE, NULL);
1837 	if (m == NULL)
1838 		return;
1839 	ifan = mtod(m, struct if_announcemsghdr *);
1840 	ifan->ifan_index = ifp->if_index;
1841 	strlcpy(ifan->ifan_name, ifp->if_xname, sizeof(ifan->ifan_name));
1842 	ifan->ifan_what = what;
1843 	route_input(m, NULL, AF_UNSPEC);
1844 }
1845 
1846 #ifdef BFD
1847 /*
1848  * This is used to generate routing socket messages indicating
1849  * the state of a BFD session.
1850  */
1851 void
1852 rtm_bfd(struct bfd_config *bfd)
1853 {
1854 	struct bfd_msghdr	*bfdm;
1855 	struct sockaddr_bfd	 sa_bfd;
1856 	struct mbuf		*m;
1857 	struct rt_addrinfo	 info;
1858 
1859 	if (rtptable.rtp_count == 0)
1860 		return;
1861 	memset(&info, 0, sizeof(info));
1862 	info.rti_info[RTAX_DST] = rt_key(bfd->bc_rt);
1863 	info.rti_info[RTAX_IFA] = bfd->bc_rt->rt_ifa->ifa_addr;
1864 
1865 	m = rtm_msg1(RTM_BFD, &info);
1866 	if (m == NULL)
1867 		return;
1868 	bfdm = mtod(m, struct bfd_msghdr *);
1869 	bfdm->bm_addrs = info.rti_addrs;
1870 
1871 	KERNEL_ASSERT_LOCKED();
1872 	bfd2sa(bfd->bc_rt, &sa_bfd);
1873 	memcpy(&bfdm->bm_sa, &sa_bfd, sizeof(sa_bfd));
1874 
1875 	route_input(m, NULL, info.rti_info[RTAX_DST]->sa_family);
1876 }
1877 #endif /* BFD */
1878 
1879 /*
1880  * This is used to generate routing socket messages indicating
1881  * the state of an ieee80211 interface.
1882  */
1883 void
1884 rtm_80211info(struct ifnet *ifp, struct if_ieee80211_data *ifie)
1885 {
1886 	struct if_ieee80211_msghdr	*ifim;
1887 	struct mbuf			*m;
1888 
1889 	if (rtptable.rtp_count == 0)
1890 		return;
1891 	m = rtm_msg1(RTM_80211INFO, NULL);
1892 	if (m == NULL)
1893 		return;
1894 	ifim = mtod(m, struct if_ieee80211_msghdr *);
1895 	ifim->ifim_index = ifp->if_index;
1896 	ifim->ifim_tableid = ifp->if_rdomain;
1897 
1898 	memcpy(&ifim->ifim_ifie, ifie, sizeof(ifim->ifim_ifie));
1899 	route_input(m, NULL, AF_UNSPEC);
1900 }
1901 
1902 /*
1903  * This is used to generate routing socket messages indicating
1904  * the address selection proposal from an interface.
1905  */
1906 void
1907 rtm_proposal(struct ifnet *ifp, struct rt_addrinfo *rtinfo, int flags,
1908     uint8_t prio)
1909 {
1910 	struct rt_msghdr	*rtm;
1911 	struct mbuf		*m;
1912 
1913 	m = rtm_msg1(RTM_PROPOSAL, rtinfo);
1914 	if (m == NULL)
1915 		return;
1916 	rtm = mtod(m, struct rt_msghdr *);
1917 	rtm->rtm_flags = RTF_DONE | flags;
1918 	rtm->rtm_priority = prio;
1919 	rtm->rtm_tableid = ifp->if_rdomain;
1920 	rtm->rtm_index = ifp->if_index;
1921 	rtm->rtm_addrs = rtinfo->rti_addrs;
1922 
1923 	route_input(m, NULL, rtinfo->rti_info[RTAX_DNS]->sa_family);
1924 }
1925 
1926 /*
1927  * This is used in dumping the kernel table via sysctl().
1928  */
1929 int
1930 sysctl_dumpentry(struct rtentry *rt, void *v, unsigned int id)
1931 {
1932 	struct walkarg		*w = v;
1933 	int			 error = 0, size;
1934 	struct rt_addrinfo	 info;
1935 	struct ifnet		*ifp;
1936 #ifdef BFD
1937 	struct sockaddr_bfd	 sa_bfd;
1938 #endif
1939 	struct sockaddr_rtlabel	 sa_rl;
1940 	struct sockaddr_in6	 sa_mask;
1941 
1942 	if (w->w_op == NET_RT_FLAGS && !(rt->rt_flags & w->w_arg))
1943 		return 0;
1944 	if (w->w_op == NET_RT_DUMP && w->w_arg) {
1945 		u_int8_t prio = w->w_arg & RTP_MASK;
1946 		if (w->w_arg < 0) {
1947 			prio = (-w->w_arg) & RTP_MASK;
1948 			/* Show all routes that are not this priority */
1949 			if (prio == (rt->rt_priority & RTP_MASK))
1950 				return 0;
1951 		} else {
1952 			if (prio != (rt->rt_priority & RTP_MASK) &&
1953 			    prio != RTP_ANY)
1954 				return 0;
1955 		}
1956 	}
1957 	bzero(&info, sizeof(info));
1958 	info.rti_info[RTAX_DST] = rt_key(rt);
1959 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1960 	info.rti_info[RTAX_NETMASK] = rt_plen2mask(rt, &sa_mask);
1961 	ifp = if_get(rt->rt_ifidx);
1962 	if (ifp != NULL) {
1963 		info.rti_info[RTAX_IFP] = sdltosa(ifp->if_sadl);
1964 		info.rti_info[RTAX_IFA] =
1965 		    rtable_getsource(id, info.rti_info[RTAX_DST]->sa_family);
1966 		if (info.rti_info[RTAX_IFA] == NULL)
1967 			info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
1968 		if (ifp->if_flags & IFF_POINTOPOINT)
1969 			info.rti_info[RTAX_BRD] = rt->rt_ifa->ifa_dstaddr;
1970 	}
1971 	if_put(ifp);
1972 	info.rti_info[RTAX_LABEL] = rtlabel_id2sa(rt->rt_labelid, &sa_rl);
1973 #ifdef BFD
1974 	if (rt->rt_flags & RTF_BFD) {
1975 		KERNEL_ASSERT_LOCKED();
1976 		info.rti_info[RTAX_BFD] = bfd2sa(rt, &sa_bfd);
1977 	}
1978 #endif
1979 #ifdef MPLS
1980 	if (rt->rt_flags & RTF_MPLS) {
1981 		struct sockaddr_mpls	 sa_mpls;
1982 
1983 		bzero(&sa_mpls, sizeof(sa_mpls));
1984 		sa_mpls.smpls_family = AF_MPLS;
1985 		sa_mpls.smpls_len = sizeof(sa_mpls);
1986 		sa_mpls.smpls_label = ((struct rt_mpls *)
1987 		    rt->rt_llinfo)->mpls_label;
1988 		info.rti_info[RTAX_SRC] = (struct sockaddr *)&sa_mpls;
1989 		info.rti_mpls = ((struct rt_mpls *)
1990 		    rt->rt_llinfo)->mpls_operation;
1991 	}
1992 #endif
1993 
1994 	size = rtm_msg2(RTM_GET, RTM_VERSION, &info, NULL, w);
1995 	if (w->w_where && w->w_tmem && w->w_needed <= w->w_given) {
1996 		struct rt_msghdr *rtm = (struct rt_msghdr *)w->w_tmem;
1997 
1998 		rtm->rtm_pid = curproc->p_p->ps_pid;
1999 		rtm->rtm_flags = RTF_DONE | rt->rt_flags;
2000 		rtm->rtm_priority = rt->rt_priority & RTP_MASK;
2001 		rtm_getmetrics(rt, &rtm->rtm_rmx);
2002 		/* Do not account the routing table's reference. */
2003 		rtm->rtm_rmx.rmx_refcnt = refcnt_read(&rt->rt_refcnt) - 1;
2004 		rtm->rtm_index = rt->rt_ifidx;
2005 		rtm->rtm_addrs = info.rti_addrs;
2006 		rtm->rtm_tableid = id;
2007 #ifdef MPLS
2008 		rtm->rtm_mpls = info.rti_mpls;
2009 #endif
2010 		if ((error = copyout(rtm, w->w_where, size)) != 0)
2011 			w->w_where = NULL;
2012 		else
2013 			w->w_where += size;
2014 	}
2015 	return (error);
2016 }
2017 
2018 int
2019 sysctl_iflist(int af, struct walkarg *w)
2020 {
2021 	struct ifnet		*ifp;
2022 	struct ifaddr		*ifa;
2023 	struct rt_addrinfo	 info;
2024 	int			 len, error = 0;
2025 
2026 	bzero(&info, sizeof(info));
2027 	TAILQ_FOREACH(ifp, &ifnetlist, if_list) {
2028 		if (w->w_arg && w->w_arg != ifp->if_index)
2029 			continue;
2030 		/* Copy the link-layer address first */
2031 		info.rti_info[RTAX_IFP] = sdltosa(ifp->if_sadl);
2032 		len = rtm_msg2(RTM_IFINFO, RTM_VERSION, &info, 0, w);
2033 		if (w->w_where && w->w_tmem && w->w_needed <= w->w_given) {
2034 			struct if_msghdr *ifm;
2035 
2036 			ifm = (struct if_msghdr *)w->w_tmem;
2037 			ifm->ifm_index = ifp->if_index;
2038 			ifm->ifm_tableid = ifp->if_rdomain;
2039 			ifm->ifm_flags = ifp->if_flags;
2040 			if_getdata(ifp, &ifm->ifm_data);
2041 			ifm->ifm_addrs = info.rti_addrs;
2042 			error = copyout(ifm, w->w_where, len);
2043 			if (error)
2044 				return (error);
2045 			w->w_where += len;
2046 		}
2047 		info.rti_info[RTAX_IFP] = NULL;
2048 		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
2049 			KASSERT(ifa->ifa_addr->sa_family != AF_LINK);
2050 			if (af && af != ifa->ifa_addr->sa_family)
2051 				continue;
2052 			info.rti_info[RTAX_IFA] = ifa->ifa_addr;
2053 			info.rti_info[RTAX_NETMASK] = ifa->ifa_netmask;
2054 			info.rti_info[RTAX_BRD] = ifa->ifa_dstaddr;
2055 			len = rtm_msg2(RTM_NEWADDR, RTM_VERSION, &info, 0, w);
2056 			if (w->w_where && w->w_tmem &&
2057 			    w->w_needed <= w->w_given) {
2058 				struct ifa_msghdr *ifam;
2059 
2060 				ifam = (struct ifa_msghdr *)w->w_tmem;
2061 				ifam->ifam_index = ifa->ifa_ifp->if_index;
2062 				ifam->ifam_flags = ifa->ifa_flags;
2063 				ifam->ifam_metric = ifa->ifa_metric;
2064 				ifam->ifam_addrs = info.rti_addrs;
2065 				error = copyout(w->w_tmem, w->w_where, len);
2066 				if (error)
2067 					return (error);
2068 				w->w_where += len;
2069 			}
2070 		}
2071 		info.rti_info[RTAX_IFA] = info.rti_info[RTAX_NETMASK] =
2072 		    info.rti_info[RTAX_BRD] = NULL;
2073 	}
2074 	return (0);
2075 }
2076 
2077 int
2078 sysctl_ifnames(struct walkarg *w)
2079 {
2080 	struct if_nameindex_msg ifn;
2081 	struct ifnet *ifp;
2082 	int error = 0;
2083 
2084 	/* XXX ignore tableid for now */
2085 	TAILQ_FOREACH(ifp, &ifnetlist, if_list) {
2086 		if (w->w_arg && w->w_arg != ifp->if_index)
2087 			continue;
2088 		w->w_needed += sizeof(ifn);
2089 		if (w->w_where && w->w_needed <= w->w_given) {
2090 
2091 			memset(&ifn, 0, sizeof(ifn));
2092 			ifn.if_index = ifp->if_index;
2093 			strlcpy(ifn.if_name, ifp->if_xname,
2094 			    sizeof(ifn.if_name));
2095 			error = copyout(&ifn, w->w_where, sizeof(ifn));
2096 			if (error)
2097 				return (error);
2098 			w->w_where += sizeof(ifn);
2099 		}
2100 	}
2101 
2102 	return (0);
2103 }
2104 
2105 int
2106 sysctl_source(int af, u_int tableid, struct walkarg *w)
2107 {
2108 	struct sockaddr	*sa;
2109 	int		 size, error = 0;
2110 
2111 	sa = rtable_getsource(tableid, af);
2112 	if (sa) {
2113 		switch (sa->sa_family) {
2114 		case AF_INET:
2115 			size = sizeof(struct sockaddr_in);
2116 			break;
2117 #ifdef INET6
2118 		case AF_INET6:
2119 			size = sizeof(struct sockaddr_in6);
2120 			break;
2121 #endif
2122 		default:
2123 			return (0);
2124 		}
2125 		w->w_needed += size;
2126 		if (w->w_where && w->w_needed <= w->w_given) {
2127 			if ((error = copyout(sa, w->w_where, size)))
2128 				return (error);
2129 			w->w_where += size;
2130 		}
2131 	}
2132 	return (0);
2133 }
2134 
2135 int
2136 sysctl_rtable(int *name, u_int namelen, void *where, size_t *given, void *new,
2137     size_t newlen)
2138 {
2139 	int			 i, error = EINVAL;
2140 	u_char			 af;
2141 	struct walkarg		 w;
2142 	struct rt_tableinfo	 tableinfo;
2143 	u_int			 tableid = 0;
2144 
2145 	if (new)
2146 		return (EPERM);
2147 	if (namelen < 3 || namelen > 4)
2148 		return (EINVAL);
2149 	af = name[0];
2150 	bzero(&w, sizeof(w));
2151 	w.w_where = where;
2152 	w.w_given = *given;
2153 	w.w_op = name[1];
2154 	w.w_arg = name[2];
2155 
2156 	if (namelen == 4) {
2157 		tableid = name[3];
2158 		if (!rtable_exists(tableid))
2159 			return (ENOENT);
2160 	} else
2161 		tableid = curproc->p_p->ps_rtableid;
2162 
2163 	switch (w.w_op) {
2164 	case NET_RT_DUMP:
2165 	case NET_RT_FLAGS:
2166 		NET_LOCK_SHARED();
2167 		for (i = 1; i <= AF_MAX; i++) {
2168 			if (af != 0 && af != i)
2169 				continue;
2170 
2171 			error = rtable_walk(tableid, i, NULL, sysctl_dumpentry,
2172 			    &w);
2173 			if (error == EAFNOSUPPORT)
2174 				error = 0;
2175 			if (error)
2176 				break;
2177 		}
2178 		NET_UNLOCK_SHARED();
2179 		break;
2180 
2181 	case NET_RT_IFLIST:
2182 		NET_LOCK_SHARED();
2183 		error = sysctl_iflist(af, &w);
2184 		NET_UNLOCK_SHARED();
2185 		break;
2186 
2187 	case NET_RT_STATS:
2188 		return (sysctl_rtable_rtstat(where, given, new));
2189 	case NET_RT_TABLE:
2190 		tableid = w.w_arg;
2191 		if (!rtable_exists(tableid))
2192 			return (ENOENT);
2193 		memset(&tableinfo, 0, sizeof tableinfo);
2194 		tableinfo.rti_tableid = tableid;
2195 		tableinfo.rti_domainid = rtable_l2(tableid);
2196 		error = sysctl_rdstruct(where, given, new,
2197 		    &tableinfo, sizeof(tableinfo));
2198 		return (error);
2199 	case NET_RT_IFNAMES:
2200 		NET_LOCK_SHARED();
2201 		error = sysctl_ifnames(&w);
2202 		NET_UNLOCK_SHARED();
2203 		break;
2204 	case NET_RT_SOURCE:
2205 		tableid = w.w_arg;
2206 		if (!rtable_exists(tableid))
2207 			return (ENOENT);
2208 		NET_LOCK_SHARED();
2209 		for (i = 1; i <= AF_MAX; i++) {
2210 			if (af != 0 && af != i)
2211 				continue;
2212 
2213 			error = sysctl_source(i, tableid, &w);
2214 			if (error == EAFNOSUPPORT)
2215 				error = 0;
2216 			if (error)
2217 				break;
2218 		}
2219 		NET_UNLOCK_SHARED();
2220 		break;
2221 	}
2222 	free(w.w_tmem, M_RTABLE, w.w_tmemsize);
2223 	if (where) {
2224 		*given = w.w_where - (caddr_t)where;
2225 		if (w.w_needed > w.w_given)
2226 			return (ENOMEM);
2227 	} else if (w.w_needed == 0) {
2228 		*given = 0;
2229 	} else {
2230 		*given = roundup(w.w_needed + MAX(w.w_needed / 10, 1024),
2231 		    PAGE_SIZE);
2232 	}
2233 	return (error);
2234 }
2235 
2236 int
2237 sysctl_rtable_rtstat(void *oldp, size_t *oldlenp, void *newp)
2238 {
2239 	extern struct cpumem *rtcounters;
2240 	uint64_t counters[rts_ncounters];
2241 	struct rtstat rtstat;
2242 	uint32_t *words = (uint32_t *)&rtstat;
2243 	int i;
2244 
2245 	CTASSERT(sizeof(rtstat) == (nitems(counters) * sizeof(uint32_t)));
2246 	memset(&rtstat, 0, sizeof rtstat);
2247 	counters_read(rtcounters, counters, nitems(counters));
2248 
2249 	for (i = 0; i < nitems(counters); i++)
2250 		words[i] = (uint32_t)counters[i];
2251 
2252 	return (sysctl_rdstruct(oldp, oldlenp, newp, &rtstat, sizeof(rtstat)));
2253 }
2254 
2255 int
2256 rtm_validate_proposal(struct rt_addrinfo *info)
2257 {
2258 	if (info->rti_addrs & ~(RTA_NETMASK | RTA_IFA | RTA_DNS | RTA_STATIC |
2259 	    RTA_SEARCH)) {
2260 		return -1;
2261 	}
2262 
2263 	if (ISSET(info->rti_addrs, RTA_NETMASK)) {
2264 		struct sockaddr *sa = info->rti_info[RTAX_NETMASK];
2265 		if (sa == NULL)
2266 			return -1;
2267 		switch (sa->sa_family) {
2268 		case AF_INET:
2269 			if (sa->sa_len != sizeof(struct sockaddr_in))
2270 				return -1;
2271 			break;
2272 		case AF_INET6:
2273 			if (sa->sa_len != sizeof(struct sockaddr_in6))
2274 				return -1;
2275 			break;
2276 		default:
2277 			return -1;
2278 		}
2279 	}
2280 
2281 	if (ISSET(info->rti_addrs, RTA_IFA)) {
2282 		struct sockaddr *sa = info->rti_info[RTAX_IFA];
2283 		if (sa == NULL)
2284 			return -1;
2285 		switch (sa->sa_family) {
2286 		case AF_INET:
2287 			if (sa->sa_len != sizeof(struct sockaddr_in))
2288 				return -1;
2289 			break;
2290 		case AF_INET6:
2291 			if (sa->sa_len != sizeof(struct sockaddr_in6))
2292 				return -1;
2293 			break;
2294 		default:
2295 			return -1;
2296 		}
2297 	}
2298 
2299 	if (ISSET(info->rti_addrs, RTA_DNS)) {
2300 		struct sockaddr_rtdns *rtdns =
2301 		    (struct sockaddr_rtdns *)info->rti_info[RTAX_DNS];
2302 		if (rtdns == NULL)
2303 			return -1;
2304 		if (rtdns->sr_len > sizeof(*rtdns))
2305 			return -1;
2306 		if (rtdns->sr_len < offsetof(struct sockaddr_rtdns, sr_dns))
2307 			return -1;
2308 		switch (rtdns->sr_family) {
2309 		case AF_INET:
2310 			if ((rtdns->sr_len - offsetof(struct sockaddr_rtdns,
2311 			    sr_dns)) % sizeof(struct in_addr) != 0)
2312 				return -1;
2313 			break;
2314 #ifdef INET6
2315 		case AF_INET6:
2316 			if ((rtdns->sr_len - offsetof(struct sockaddr_rtdns,
2317 			    sr_dns)) % sizeof(struct in6_addr) != 0)
2318 				return -1;
2319 			break;
2320 #endif
2321 		default:
2322 			return -1;
2323 		}
2324 	}
2325 
2326 	if (ISSET(info->rti_addrs, RTA_STATIC)) {
2327 		struct sockaddr_rtstatic *rtstatic =
2328 		    (struct sockaddr_rtstatic *)info->rti_info[RTAX_STATIC];
2329 		if (rtstatic == NULL)
2330 			return -1;
2331 		if (rtstatic->sr_len > sizeof(*rtstatic))
2332 			return -1;
2333 		if (rtstatic->sr_len <=
2334 		    offsetof(struct sockaddr_rtstatic, sr_static))
2335 			return -1;
2336 	}
2337 
2338 	if (ISSET(info->rti_addrs, RTA_SEARCH)) {
2339 		struct sockaddr_rtsearch *rtsearch =
2340 		    (struct sockaddr_rtsearch *)info->rti_info[RTAX_SEARCH];
2341 		if (rtsearch == NULL)
2342 			return -1;
2343 		if (rtsearch->sr_len > sizeof(*rtsearch))
2344 			return -1;
2345 		if (rtsearch->sr_len <=
2346 		    offsetof(struct sockaddr_rtsearch, sr_search))
2347 			return -1;
2348 	}
2349 
2350 	return 0;
2351 }
2352 
2353 int
2354 rt_setsource(unsigned int rtableid, struct sockaddr *src)
2355 {
2356 	struct ifaddr	*ifa;
2357 	/*
2358 	 * If source address is 0.0.0.0 or ::
2359 	 * use automatic source selection
2360 	 */
2361 	switch(src->sa_family) {
2362 	case AF_INET:
2363 		if(satosin(src)->sin_addr.s_addr == INADDR_ANY) {
2364 			rtable_setsource(rtableid, AF_INET, NULL);
2365 			return (0);
2366 		}
2367 		break;
2368 #ifdef INET6
2369 	case AF_INET6:
2370 		if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(src)->sin6_addr)) {
2371 			rtable_setsource(rtableid, AF_INET6, NULL);
2372 			return (0);
2373 		}
2374 		break;
2375 #endif
2376 	default:
2377 		return (EAFNOSUPPORT);
2378 	}
2379 
2380 	/*
2381 	 * Check if source address is assigned to an interface in the
2382 	 * same rdomain
2383 	 */
2384 	if ((ifa = ifa_ifwithaddr(src, rtableid)) == NULL)
2385 		return (EINVAL);
2386 
2387 	return rtable_setsource(rtableid, src->sa_family, ifa->ifa_addr);
2388 }
2389 
2390 /*
2391  * Definitions of protocols supported in the ROUTE domain.
2392  */
2393 
2394 const struct pr_usrreqs route_usrreqs = {
2395 	.pru_attach	= route_attach,
2396 	.pru_detach	= route_detach,
2397 	.pru_disconnect	= route_disconnect,
2398 	.pru_shutdown	= route_shutdown,
2399 	.pru_rcvd	= route_rcvd,
2400 	.pru_send	= route_send,
2401 	.pru_sockaddr	= route_sockaddr,
2402 	.pru_peeraddr	= route_peeraddr,
2403 };
2404 
2405 const struct protosw routesw[] = {
2406 {
2407   .pr_type	= SOCK_RAW,
2408   .pr_domain	= &routedomain,
2409   .pr_flags	= PR_ATOMIC|PR_ADDR|PR_WANTRCVD,
2410   .pr_ctloutput	= route_ctloutput,
2411   .pr_usrreqs	= &route_usrreqs,
2412   .pr_init	= route_prinit,
2413   .pr_sysctl	= sysctl_rtable
2414 }
2415 };
2416 
2417 const struct domain routedomain = {
2418   .dom_family = PF_ROUTE,
2419   .dom_name = "route",
2420   .dom_init = route_init,
2421   .dom_protosw = routesw,
2422   .dom_protoswNPROTOSW = &routesw[nitems(routesw)]
2423 };
2424