xref: /freebsd/sys/netlink/route/rt.c (revision ddd850aa7720f77b6605599655df898b16ed74cc)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2021 Ng Peng Nam Sean
5  * Copyright (c) 2022 Alexander V. Chernikov <melifaro@FreeBSD.org>
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  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include "opt_inet.h"
31 #include "opt_inet6.h"
32 #include <sys/types.h>
33 #include <sys/malloc.h>
34 #include <sys/rmlock.h>
35 #include <sys/socket.h>
36 
37 #include <net/if.h>
38 #include <net/route.h>
39 #include <net/route/nhop.h>
40 #include <net/route/route_ctl.h>
41 #include <net/route/route_var.h>
42 #include <netinet6/scope6_var.h>
43 #include <netlink/netlink.h>
44 #include <netlink/netlink_ctl.h>
45 #include <netlink/netlink_route.h>
46 #include <netlink/route/route_var.h>
47 
48 #define	DEBUG_MOD_NAME	nl_route
49 #define	DEBUG_MAX_LEVEL	LOG_DEBUG3
50 #include <netlink/netlink_debug.h>
51 _DECLARE_DEBUG(LOG_INFO);
52 
53 static unsigned char
get_rtm_type(const struct nhop_object * nh)54 get_rtm_type(const struct nhop_object *nh)
55 {
56 	int nh_flags = nh->nh_flags;
57 
58 	/* Use the fact that nhg runtime flags are only NHF_MULTIPATH */
59 	if (nh_flags & NHF_BLACKHOLE)
60 		return (RTN_BLACKHOLE);
61 	else if (nh_flags & NHF_REJECT)
62 		return (RTN_PROHIBIT);
63 	return (RTN_UNICAST);
64 }
65 
66 static uint8_t
nl_get_rtm_protocol(const struct nhop_object * nh)67 nl_get_rtm_protocol(const struct nhop_object *nh)
68 {
69 	const struct nhgrp_object *nhg = (const struct nhgrp_object *)nh;
70 	int rt_flags;
71 	uint8_t origin;
72 
73 	if (NH_IS_NHGRP(nh)) {
74 		origin = nhgrp_get_origin(nhg);
75 		if (origin != RTPROT_UNSPEC)
76 			return (origin);
77 		nh = nhg->nhops[0];
78 	}
79 	origin = nhop_get_origin(nh);
80 	if (origin != RTPROT_UNSPEC)
81 		return (origin);
82 	/* TODO: remove guesswork once all kernel users fill in origin */
83 	rt_flags = nhop_get_rtflags(nh);
84 	if (rt_flags & RTF_PROTO1)
85 		return (RTPROT_ZEBRA);
86 	if (rt_flags & RTF_STATIC)
87 		return (RTPROT_STATIC);
88 	return (RTPROT_KERNEL);
89 }
90 
91 static int
get_rtmsg_type_from_rtsock(int cmd)92 get_rtmsg_type_from_rtsock(int cmd)
93 {
94 	switch (cmd) {
95 	case RTM_ADD:
96 	case RTM_CHANGE:
97 	case RTM_GET:
98 		return NL_RTM_NEWROUTE;
99 	case RTM_DELETE:
100 		return NL_RTM_DELROUTE;
101 	}
102 
103 	return (0);
104 }
105 
106 /*
107  * fibnum heuristics
108  *
109  * if (dump && rtm_table == 0 && !rta_table) RT_ALL_FIBS
110  * msg                rtm_table     RTA_TABLE            result
111  * RTM_GETROUTE/dump          0             -       RT_ALL_FIBS
112  * RTM_GETROUTE/dump          1             -                 1
113  * RTM_GETROUTE/get           0             -                 0
114  *
115  */
116 
117 static struct nhop_object *
rc_get_nhop(const struct rib_cmd_info * rc)118 rc_get_nhop(const struct rib_cmd_info *rc)
119 {
120 	return ((rc->rc_cmd == RTM_DELETE) ? rc->rc_nh_old : rc->rc_nh_new);
121 }
122 
123 static void
dump_rc_nhop_gw(struct nl_writer * nw,const struct nhop_object * nh)124 dump_rc_nhop_gw(struct nl_writer *nw, const struct nhop_object *nh)
125 {
126 #ifdef INET6
127 	int upper_family;
128 #endif
129 
130 	switch (nhop_get_neigh_family(nh)) {
131 	case AF_LINK:
132 		/* onlink prefix, skip */
133 		break;
134 	case AF_INET:
135 		nlattr_add(nw, NL_RTA_GATEWAY, 4, &nh->gw4_sa.sin_addr);
136 		break;
137 #ifdef INET6
138 	case AF_INET6:
139 		upper_family = nhop_get_upper_family(nh);
140 		if (upper_family == AF_INET6) {
141 			struct in6_addr gw6 = nh->gw6_sa.sin6_addr;
142 			in6_clearscope(&gw6);
143 
144 			nlattr_add(nw, NL_RTA_GATEWAY, 16, &gw6);
145 		} else if (upper_family == AF_INET) {
146 			/* IPv4 over IPv6 */
147 			struct in6_addr gw6 = nh->gw6_sa.sin6_addr;
148 			in6_clearscope(&gw6);
149 
150 			char buf[20];
151 			struct rtvia *via = (struct rtvia *)&buf[0];
152 			via->rtvia_family = AF_INET6;
153 			memcpy(via->rtvia_addr, &gw6, 16);
154 			nlattr_add(nw, NL_RTA_VIA, 17, via);
155 		}
156 		break;
157 #endif
158 	}
159 }
160 
161 static void
dump_rc_nhop_prefsrc(struct nl_writer * nw,const struct nhop_object * nh)162 dump_rc_nhop_prefsrc(struct nl_writer *nw, const struct nhop_object *nh)
163 {
164 	const struct ifaddr *ifa = nh->nh_ifa;
165 #ifdef INET6
166 	struct in6_addr in6;
167 #endif
168 
169 	if ((nh->nh_flags & NHF_PREFSRC) == 0)
170 		return;
171 
172 	switch (ifa->ifa_addr->sa_family) {
173 #ifdef INET
174 	case AF_INET:
175 		nlattr_add(nw, NL_RTA_PREFSRC, 4,
176 		    &((struct sockaddr_in *)((ifa)->ifa_addr))->sin_addr);
177 		break;
178 #endif
179 #ifdef INET6
180 	case AF_INET6:
181 		in6 = ((struct sockaddr_in6 *)((ifa)->ifa_addr))->sin6_addr;
182 		in6_clearscope(&in6);
183 		nlattr_add(nw, NL_RTA_PREFSRC, 16, &in6);
184 		break;
185 #endif
186 	}
187 }
188 
189 static void
dump_rc_nhop_mtu(struct nl_writer * nw,const struct nhop_object * nh)190 dump_rc_nhop_mtu(struct nl_writer *nw, const struct nhop_object *nh)
191 {
192 	int nla_len = sizeof(struct nlattr) * 2 + sizeof(uint32_t);
193 	struct nlattr *nla = nlmsg_reserve_data(nw, nla_len, struct nlattr);
194 
195 	if (nla == NULL)
196 		return;
197 	nla->nla_type = NL_RTA_METRICS;
198 	nla->nla_len = nla_len;
199 	nla++;
200 	nla->nla_type = NL_RTAX_MTU;
201 	nla->nla_len = sizeof(struct nlattr) + sizeof(uint32_t);
202 	*((uint32_t *)(nla + 1)) = nh->nh_mtu;
203 }
204 
205 static void
dump_rc_nhg(struct nl_writer * nw,const struct route_nhop_data * rnd,struct rtmsg * rtm)206 dump_rc_nhg(struct nl_writer *nw, const struct route_nhop_data *rnd, struct rtmsg *rtm)
207 {
208 	const struct nhgrp_object *nhg = rnd->rnd_nhgrp;
209 	const struct weightened_nhop *wn;
210 	struct nhop_object *nh;
211 	uint32_t uidx, num_nhops, nh_expire;
212 	uint32_t base_rtflags, rtflags, nhop_weight, nhop_metric;
213 
214 	MPASS((NH_IS_NHGRP(rnd->rnd_nhop)));
215 
216 	/* select a nhop from nhgrp to not confuse non-mpath consumers */
217 	nhop_weight = RT_DEFAULT_WEIGHT;
218 	nhop_metric = RT_DEFAULT_METRIC;
219 	nh = nhop_select_func(rnd->rnd_nhop, 0);
220 	rtflags = nhop_get_rtflags(nh);
221 	if (nh->nh_flags & NHF_GATEWAY)
222 		dump_rc_nhop_gw(nw, nh);
223 
224 	dump_rc_nhop_prefsrc(nw, nh);
225 	wn = nhgrp_get_nhops(nhg, &num_nhops);
226 	base_rtflags = nhop_get_rtflags(wn[0].nh);
227 	uidx = nhgrp_get_uidx(nhg);
228 	if (uidx != 0)
229 		nlattr_add_u32(nw, NL_RTA_NH_ID, uidx);
230 	nlattr_add_u32(nw, NL_RTA_KNH_ID, nhgrp_get_idx(nhg));
231 	nlattr_add_u32(nw, NL_RTA_RTFLAGS, base_rtflags);
232 
233 	if (rtflags & RTF_FIXEDMTU)
234 		dump_rc_nhop_mtu(nw, nh);
235 	/* In any case, fill outgoing interface */
236 	nlattr_add_u32(nw, NL_RTA_OIF, if_getindex(nh->nh_ifp));
237 
238 	int off = nlattr_add_nested(nw, NL_RTA_MULTIPATH);
239 	if (off == 0)
240 		return;
241 
242 	for (int i = 0; i < num_nhops; i++) {
243 		int nh_off = nlattr_save_offset(nw);
244 		struct rtnexthop *rtnh = nlmsg_reserve_object(nw, struct rtnexthop);
245 		if (rtnh == NULL)
246 			return;
247 		rtnh->rtnh_flags = 0;
248 		rtnh->rtnh_ifindex = if_getindex(wn[i].nh->nh_ifp);
249 		rtnh->rtnh_hops = MIN(wn[i].weight, UINT8_MAX);
250 		dump_rc_nhop_gw(nw, wn[i].nh);
251 		uint32_t rtflags = nhop_get_rtflags(wn[i].nh);
252 		if (rtflags != base_rtflags)
253 			nlattr_add_u32(nw, NL_RTA_RTFLAGS, rtflags);
254 		if (rtflags & RTF_FIXEDMTU)
255 			dump_rc_nhop_mtu(nw, wn[i].nh);
256 		nlattr_add_u32(nw, NL_RTA_PRIORITY, nhop_get_metric(wn[i].nh));
257 		nh_expire = nhop_get_expire(wn[i].nh);
258 		if (nh_expire > 0)
259 			nlattr_add_u32(nw, NL_RTA_EXPIRES, nh_expire - time_uptime);
260 		rtnh = nlattr_restore_offset(nw, nh_off, struct rtnexthop);
261 
262 		if (nh == wn[i].nh) {
263 			nhop_weight = wn[i].weight;
264 			nhop_metric = nhop_get_metric(wn[i].nh);
265 		}
266 		/*
267 		 * nlattr_add() allocates 4-byte aligned storage, no need to aligh
268 		 * length here
269 		 * */
270 		rtnh->rtnh_len = nlattr_save_offset(nw) - nh_off;
271 	}
272 	nlattr_set_len(nw, off);
273 	nlattr_add_u32(nw, NL_RTA_PRIORITY, nhop_metric);
274 	if (nhop_weight != RT_DEFAULT_WEIGHT)
275 		nlattr_add_u32(nw, NL_RTA_WEIGHT, nhop_weight);
276 }
277 
278 static void
dump_rc_nhop(struct nl_writer * nw,const struct route_nhop_data * rnd,struct rtmsg * rtm)279 dump_rc_nhop(struct nl_writer *nw, const struct route_nhop_data *rnd, struct rtmsg *rtm)
280 {
281 	const struct nhop_object *nh = rnd->rnd_nhop;
282 	uint32_t rtflags, uidx, nh_expire;
283 
284 	if (NH_IS_NHGRP(rnd->rnd_nhop)) {
285 		dump_rc_nhg(nw, rnd, rtm);
286 		return;
287 	}
288 
289 	rtflags = nhop_get_rtflags(nh);
290 	/*
291 	 * IPv4 over IPv6
292 	 *    ('RTA_VIA', {'family': 10, 'addr': 'fe80::20c:29ff:fe67:2dd'}), ('RTA_OIF', 2),
293 	 * IPv4 w/ gw
294 	 *    ('RTA_GATEWAY', '172.16.107.131'), ('RTA_OIF', 2)],
295 	 * Direct route:
296 	 *    ('RTA_OIF', 2)
297 	 */
298 	if (nh->nh_flags & NHF_GATEWAY)
299 		dump_rc_nhop_gw(nw, nh);
300 
301 	dump_rc_nhop_prefsrc(nw, nh);
302 	uidx = nhop_get_uidx(nh);
303 	if (uidx != 0)
304 		nlattr_add_u32(nw, NL_RTA_NH_ID, uidx);
305 	nlattr_add_u32(nw, NL_RTA_KNH_ID, nhop_get_idx(nh));
306 	nlattr_add_u32(nw, NL_RTA_RTFLAGS, rtflags);
307 
308 	if (rtflags & RTF_FIXEDMTU)
309 		dump_rc_nhop_mtu(nw, nh);
310 	nh_expire = nhop_get_expire(nh);
311 	if (nh_expire > 0)
312 		nlattr_add_u32(nw, NL_RTA_EXPIRES, nh_expire - time_uptime);
313 
314 	/* In any case, fill outgoing interface */
315 	nlattr_add_u32(nw, NL_RTA_OIF, if_getindex(nh->nh_ifp));
316 
317 	nlattr_add_u32(nw, NL_RTA_PRIORITY, nhop_get_metric(nh));
318 	if (rnd->rnd_weight != RT_DEFAULT_WEIGHT)
319 		nlattr_add_u32(nw, NL_RTA_WEIGHT, rnd->rnd_weight);
320 }
321 
322 /*
323  * Dumps output from a rib command into an rtmsg
324  */
325 
326 static int
dump_px(uint32_t fibnum,const struct nlmsghdr * hdr,const struct rtentry * rt,struct route_nhop_data * rnd,struct nl_writer * nw)327 dump_px(uint32_t fibnum, const struct nlmsghdr *hdr,
328     const struct rtentry *rt, struct route_nhop_data *rnd,
329     struct nl_writer *nw)
330 {
331 	struct rtmsg *rtm;
332 	int error = 0;
333 
334 	NET_EPOCH_ASSERT();
335 
336 	if (!nlmsg_reply(nw, hdr, sizeof(struct rtmsg)))
337 		goto enomem;
338 
339 	int family = rt_get_family(rt);
340 	int rtm_off = nlattr_save_offset(nw);
341 	rtm = nlmsg_reserve_object(nw, struct rtmsg);
342 	rtm->rtm_family = family;
343 	rtm->rtm_dst_len = 0;
344 	rtm->rtm_src_len = 0;
345 	rtm->rtm_tos = 0;
346 	if (fibnum < 255)
347 		rtm->rtm_table = (unsigned char)fibnum;
348 	rtm->rtm_scope = RT_SCOPE_UNIVERSE;
349 	rtm->rtm_protocol = nl_get_rtm_protocol(rnd->rnd_nhop);
350 	rtm->rtm_type = get_rtm_type(rnd->rnd_nhop);
351 
352 	nlattr_add_u32(nw, NL_RTA_TABLE, fibnum);
353 
354 	int plen = 0;
355 #if defined(INET) || defined(INET6)
356 	uint32_t scopeid;
357 #endif
358 	switch (family) {
359 #ifdef INET
360 	case AF_INET:
361 		{
362 			struct in_addr addr;
363 			rt_get_inet_prefix_plen(rt, &addr, &plen, &scopeid);
364 			nlattr_add(nw, NL_RTA_DST, 4, &addr);
365 			break;
366 		}
367 #endif
368 #ifdef INET6
369 	case AF_INET6:
370 		{
371 			struct in6_addr addr;
372 			rt_get_inet6_prefix_plen(rt, &addr, &plen, &scopeid);
373 			nlattr_add(nw, NL_RTA_DST, 16, &addr);
374 			break;
375 		}
376 #endif
377 	default:
378 		FIB_LOG(LOG_NOTICE, fibnum, family, "unsupported rt family: %d", family);
379 		error = EAFNOSUPPORT;
380 		goto flush;
381 	}
382 
383 	rtm = nlattr_restore_offset(nw, rtm_off, struct rtmsg);
384 	if (plen > 0)
385 		rtm->rtm_dst_len = plen;
386 	if (NH_IS_NHGRP(rnd->rnd_nhop))
387 		dump_rc_nhg(nw, rnd, rtm);
388 	else
389 		dump_rc_nhop(nw, rnd, rtm);
390 
391 	if (nlmsg_end(nw))
392 		return (0);
393 enomem:
394 	error = ENOMEM;
395 flush:
396 	nlmsg_abort(nw);
397 	return (error);
398 }
399 
400 static int
family_to_group(int family)401 family_to_group(int family)
402 {
403 	switch (family) {
404 	case AF_INET:
405 		return (RTNLGRP_IPV4_ROUTE);
406 	case AF_INET6:
407 		return (RTNLGRP_IPV6_ROUTE);
408 	}
409 	return (0);
410 }
411 
412 static void
report_operation(uint32_t fibnum,struct rib_cmd_info * rc,struct nlpcb * nlp,struct nlmsghdr * hdr)413 report_operation(uint32_t fibnum, struct rib_cmd_info *rc,
414     struct nlpcb *nlp, struct nlmsghdr *hdr)
415 {
416 	struct nl_writer nw;
417 	uint32_t group_id = family_to_group(rt_get_family(rc->rc_rt));
418 
419 	if (nl_writer_group(&nw, NLMSG_SMALL, NETLINK_ROUTE, group_id, 0,
420 	    false)) {
421 		struct route_nhop_data rnd = {
422 			.rnd_nhop = rc_get_nhop(rc),
423 			.rnd_weight = rc->rc_nh_weight,
424 		};
425 		hdr->nlmsg_flags &= ~(NLM_F_REPLACE | NLM_F_CREATE);
426 		hdr->nlmsg_flags &= ~(NLM_F_EXCL | NLM_F_APPEND);
427 		switch (rc->rc_cmd) {
428 		case RTM_ADD:
429 			hdr->nlmsg_type = NL_RTM_NEWROUTE;
430 			hdr->nlmsg_flags |= NLM_F_CREATE | NLM_F_EXCL;
431 			break;
432 		case RTM_CHANGE:
433 			hdr->nlmsg_type = NL_RTM_NEWROUTE;
434 			hdr->nlmsg_flags |= NLM_F_REPLACE;
435 			break;
436 		case RTM_DELETE:
437 			hdr->nlmsg_type = NL_RTM_DELROUTE;
438 			break;
439 		}
440 		dump_px(fibnum, hdr, rc->rc_rt, &rnd, &nw);
441 		nlmsg_flush(&nw);
442 	}
443 
444 	rtsock_callback_p->route_f(fibnum, rc);
445 }
446 
447 static void
set_scope6(struct sockaddr * sa,struct ifnet * ifp)448 set_scope6(struct sockaddr *sa, struct ifnet *ifp)
449 {
450 #ifdef INET6
451 	if (sa != NULL && sa->sa_family == AF_INET6 && ifp != NULL) {
452 		struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
453 
454 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
455 			in6_set_unicast_scopeid(&sa6->sin6_addr, if_getindex(ifp));
456 	}
457 #endif
458 }
459 
460 struct rta_mpath_nh {
461 	struct sockaddr	*gw;
462 	struct ifnet	*ifp;
463 	uint8_t		rtnh_flags;
464 	uint8_t		rtnh_weight;
465 };
466 
467 #define	_IN(_field)	offsetof(struct rtnexthop, _field)
468 #define	_OUT(_field)	offsetof(struct rta_mpath_nh, _field)
469 const static struct nlattr_parser nla_p_rtnh[] = {
470 	{ .type = NL_RTA_GATEWAY, .off = _OUT(gw), .cb = nlattr_get_ip },
471 	{ .type = NL_RTA_VIA, .off = _OUT(gw), .cb = nlattr_get_ipvia },
472 };
473 const static struct nlfield_parser nlf_p_rtnh[] = {
474 	{ .off_in = _IN(rtnh_flags), .off_out = _OUT(rtnh_flags), .cb = nlf_get_u8 },
475 	{ .off_in = _IN(rtnh_hops), .off_out = _OUT(rtnh_weight), .cb = nlf_get_u8 },
476 	{ .off_in = _IN(rtnh_ifindex), .off_out = _OUT(ifp), .cb = nlf_get_ifpz },
477 };
478 #undef _IN
479 #undef _OUT
480 
481 static bool
post_p_rtnh(void * _attrs,struct nl_pstate * npt __unused)482 post_p_rtnh(void *_attrs, struct nl_pstate *npt __unused)
483 {
484 	struct rta_mpath_nh *attrs = (struct rta_mpath_nh *)_attrs;
485 
486 	set_scope6(attrs->gw, attrs->ifp);
487 	return (true);
488 }
489 NL_DECLARE_PARSER_EXT(mpath_parser, struct rtnexthop, NULL, nlf_p_rtnh, nla_p_rtnh, post_p_rtnh);
490 
491 struct rta_mpath {
492 	u_int num_nhops;
493 	struct rta_mpath_nh nhops[0];
494 };
495 
496 static int
nlattr_get_multipath(struct nlattr * nla,struct nl_pstate * npt,const void * arg,void * target)497 nlattr_get_multipath(struct nlattr *nla, struct nl_pstate *npt,
498     const void *arg, void *target)
499 {
500 	struct rta_mpath *mp;
501 	struct rtnexthop *rtnh;
502 	uint16_t data_len, len;
503 	u_int max_nhops;
504 	int error;
505 
506 	data_len = nla->nla_len - sizeof(struct nlattr);
507 	max_nhops = data_len / sizeof(struct rtnexthop);
508 
509 	mp = npt_alloc(npt, (max_nhops + 2) * sizeof(struct rta_mpath_nh));
510 	if (mp == NULL) {
511 		NLMSG_REPORT_ERR_MSG(npt, "%s: too many RTA_MULTIPATH", __func__);
512 		return (ENOMEM);
513 	}
514 	mp->num_nhops = 0;
515 
516 	for (rtnh = (struct rtnexthop *)(nla + 1); data_len > 0; ) {
517 		struct rta_mpath_nh *mpnh;
518 
519 		len = NL_ITEM_ALIGN(rtnh->rtnh_len);
520 		if (__predict_false(rtnh->rtnh_len <= sizeof(*rtnh) ||
521 		    len < rtnh->rtnh_len || len > data_len)) {
522 			NLMSG_REPORT_ERR_MSG(npt, "%s: bad length %u",
523 			    __func__, rtnh->rtnh_len);
524 			return (EINVAL);
525 		}
526 		mpnh = &mp->nhops[mp->num_nhops++];
527 		error = nl_parse_header(rtnh, rtnh->rtnh_len, &mpath_parser,
528 		    npt, mpnh);
529 		if (error != 0) {
530 			NLMSG_REPORT_ERR_MSG(npt,
531 			    "RTA_MULTIPATH: nexthop %u: parse failed",
532 			    mp->num_nhops - 1);
533 			return (error);
534 		}
535 		data_len -= len;
536 		rtnh = (struct rtnexthop *)((char *)rtnh + len);
537 	}
538 	if (data_len != 0 || mp->num_nhops == 0) {
539 		NLMSG_REPORT_ERR_MSG(npt, "invalid RTA_MULTIPATH attr");
540 		return (EINVAL);
541 	}
542 
543 	*((struct rta_mpath **)target) = mp;
544 	return (0);
545 }
546 
547 
548 struct nl_parsed_route {
549 	struct sockaddr		*rta_dst;
550 	struct sockaddr		*rta_gw;
551 	struct sockaddr		*rta_pref_src;
552 	struct ifnet		*rta_oif;
553 	struct rta_mpath	*rta_multipath;
554 	uint32_t		rta_table;
555 	uint32_t		rta_rtflags;
556 	uint32_t		rta_nh_id;
557 	uint32_t		rta_metric;
558 	uint32_t		rta_weight;
559 	uint32_t		rta_expire;
560 	uint32_t		rtax_mtu;
561 	uint8_t			rtm_table;
562 	uint8_t			rtm_family;
563 	uint8_t			rtm_dst_len;
564 	uint8_t			rtm_protocol;
565 	uint8_t			rtm_type;
566 	uint32_t		rtm_flags;
567 };
568 
569 #define	_IN(_field)	offsetof(struct rtmsg, _field)
570 #define	_OUT(_field)	offsetof(struct nl_parsed_route, _field)
571 static struct nlattr_parser nla_p_rtmetrics[] = {
572 	{ .type = NL_RTAX_MTU, .off = _OUT(rtax_mtu), .cb = nlattr_get_uint32 },
573 };
574 NL_DECLARE_ATTR_PARSER(metrics_parser, nla_p_rtmetrics);
575 
576 static const struct nlattr_parser nla_p_rtmsg[] = {
577 	{ .type = NL_RTA_DST, .off = _OUT(rta_dst), .cb = nlattr_get_ip },
578 	{ .type = NL_RTA_OIF, .off = _OUT(rta_oif), .cb = nlattr_get_ifp },
579 	{ .type = NL_RTA_GATEWAY, .off = _OUT(rta_gw), .cb = nlattr_get_ip },
580 	{ .type = NL_RTA_PRIORITY, .off = _OUT(rta_metric), .cb = nlattr_get_uint32 },
581 	{ .type = NL_RTA_PREFSRC, .off = _OUT(rta_pref_src), .cb = nlattr_get_ip },
582 	{ .type = NL_RTA_METRICS, .arg = &metrics_parser, .cb = nlattr_get_nested },
583 	{ .type = NL_RTA_MULTIPATH, .off = _OUT(rta_multipath), .cb = nlattr_get_multipath },
584 	{ .type = NL_RTA_WEIGHT, .off = _OUT(rta_weight), .cb = nlattr_get_uint32 },
585 	{ .type = NL_RTA_RTFLAGS, .off = _OUT(rta_rtflags), .cb = nlattr_get_uint32 },
586 	{ .type = NL_RTA_TABLE, .off = _OUT(rta_table), .cb = nlattr_get_uint32 },
587 	{ .type = NL_RTA_VIA, .off = _OUT(rta_gw), .cb = nlattr_get_ipvia },
588 	{ .type = NL_RTA_EXPIRES, .off = _OUT(rta_expire), .cb = nlattr_get_uint32 },
589 	{ .type = NL_RTA_NH_ID, .off = _OUT(rta_nh_id), .cb = nlattr_get_uint32 },
590 };
591 
592 static const struct nlfield_parser nlf_p_rtmsg[] = {
593 	{ .off_in = _IN(rtm_family), .off_out = _OUT(rtm_family), .cb = nlf_get_u8 },
594 	{ .off_in = _IN(rtm_dst_len), .off_out = _OUT(rtm_dst_len), .cb = nlf_get_u8 },
595 	{ .off_in = _IN(rtm_protocol), .off_out = _OUT(rtm_protocol), .cb = nlf_get_u8 },
596 	{ .off_in = _IN(rtm_type), .off_out = _OUT(rtm_type), .cb = nlf_get_u8 },
597 	{ .off_in = _IN(rtm_table), .off_out = _OUT(rtm_table), .cb = nlf_get_u8 },
598 	{ .off_in = _IN(rtm_flags), .off_out = _OUT(rtm_flags), .cb = nlf_get_u32 },
599 };
600 #undef _IN
601 #undef _OUT
602 
603 static bool
post_p_rtmsg(void * _attrs,struct nl_pstate * npt __unused)604 post_p_rtmsg(void *_attrs, struct nl_pstate *npt __unused)
605 {
606 	struct nl_parsed_route *attrs = (struct nl_parsed_route *)_attrs;
607 
608 	set_scope6(attrs->rta_dst, attrs->rta_oif);
609 	set_scope6(attrs->rta_gw, attrs->rta_oif);
610 	set_scope6(attrs->rta_pref_src, attrs->rta_oif);
611 	return (true);
612 }
613 NL_DECLARE_PARSER_EXT(rtm_parser, struct rtmsg, NULL, nlf_p_rtmsg, nla_p_rtmsg, post_p_rtmsg);
614 
615 struct netlink_walkargs {
616 	struct nl_writer *nw;
617 	struct route_nhop_data rnd;
618 	struct nlmsghdr hdr;
619 	struct nlpcb *nlp;
620 	uint32_t fibnum;
621 	int family;
622 	int error;
623 	int count;
624 	int dumped;
625 	int dumped_tables;
626 };
627 
628 static int
dump_rtentry(struct rtentry * rt,void * _arg)629 dump_rtentry(struct rtentry *rt, void *_arg)
630 {
631 	struct netlink_walkargs *wa = (struct netlink_walkargs *)_arg;
632 	int error;
633 
634 	wa->count++;
635 	if (wa->error != 0)
636 		return (0);
637 	if (!rt_is_exportable(rt, nlp_get_cred(wa->nlp)))
638 		return (0);
639 	wa->dumped++;
640 
641 	rt_get_rnd(rt, &wa->rnd);
642 
643 	error = dump_px(wa->fibnum, &wa->hdr, rt, &wa->rnd, wa->nw);
644 
645 	IF_DEBUG_LEVEL(LOG_DEBUG3) {
646 		char rtbuf[INET6_ADDRSTRLEN + 5];
647 		FIB_LOG(LOG_DEBUG3, wa->fibnum, wa->family,
648 		    "Dump %s, error %d",
649 		    rt_print_buf(rt, rtbuf, sizeof(rtbuf)), error);
650 	}
651 	wa->error = error;
652 
653 	return (0);
654 }
655 
656 static void
dump_rtable_one(struct netlink_walkargs * wa,uint32_t fibnum,int family)657 dump_rtable_one(struct netlink_walkargs *wa, uint32_t fibnum, int family)
658 {
659 	FIB_LOG(LOG_DEBUG2, fibnum, family, "Start dump");
660 	wa->count = 0;
661 	wa->dumped = 0;
662 
663 	rib_walk(fibnum, family, false, dump_rtentry, wa);
664 
665 	wa->dumped_tables++;
666 
667 	FIB_LOG(LOG_DEBUG2, fibnum, family, "End dump, iterated %d dumped %d",
668 	    wa->count, wa->dumped);
669 }
670 
671 static int
dump_rtable_fib(struct netlink_walkargs * wa,uint32_t fibnum,int family)672 dump_rtable_fib(struct netlink_walkargs *wa, uint32_t fibnum, int family)
673 {
674 	wa->fibnum = fibnum;
675 
676 	if (family == AF_UNSPEC) {
677 		for (int i = 0; i < AF_MAX; i++) {
678 			if (rt_tables_get_rnh(fibnum, i) != 0) {
679 				wa->family = i;
680 				dump_rtable_one(wa, fibnum, i);
681 				if (wa->error != 0)
682 					break;
683 			}
684 		}
685 	} else {
686 		if (rt_tables_get_rnh(fibnum, family) != 0) {
687 			wa->family = family;
688 			dump_rtable_one(wa, fibnum, family);
689 		}
690 	}
691 
692 	return (wa->error);
693 }
694 
695 static int
handle_rtm_getroute(struct nlpcb * nlp,struct nl_parsed_route * attrs,struct nlmsghdr * hdr,struct nl_pstate * npt)696 handle_rtm_getroute(struct nlpcb *nlp, struct nl_parsed_route *attrs,
697     struct nlmsghdr *hdr, struct nl_pstate *npt)
698 {
699 	RIB_RLOCK_TRACKER;
700 	struct rib_head *rnh;
701 	const struct rtentry *rt;
702 	struct route_nhop_data rnd;
703 	uint32_t fibnum = attrs->rta_table;
704 	sa_family_t family = attrs->rtm_family;
705 
706 	if (attrs->rta_dst == NULL) {
707 		NLMSG_REPORT_ERR_MSG(npt, "No RTA_DST supplied");
708 			return (EINVAL);
709 	}
710 
711 	rnh = rt_tables_get_rnh(fibnum, family);
712 	if (rnh == NULL)
713 		return (EAFNOSUPPORT);
714 
715 	RIB_RLOCK(rnh);
716 
717 	struct sockaddr *dst = attrs->rta_dst;
718 
719 	if (attrs->rtm_flags & RTM_F_PREFIX)
720 		rt = rib_lookup_prefix_plen(rnh, dst, attrs->rtm_dst_len, &rnd);
721 	else
722 		rt = (const struct rtentry *)rnh->rnh_matchaddr(dst, &rnh->head);
723 	if (rt == NULL) {
724 		RIB_RUNLOCK(rnh);
725 		return (ESRCH);
726 	}
727 
728 	rt_get_rnd(rt, &rnd);
729 
730 	RIB_RUNLOCK(rnh);
731 
732 	if (!rt_is_exportable(rt, nlp_get_cred(nlp)))
733 		return (ESRCH);
734 
735 	IF_DEBUG_LEVEL(LOG_DEBUG2) {
736 		char rtbuf[NHOP_PRINT_BUFSIZE] __unused, nhbuf[NHOP_PRINT_BUFSIZE] __unused;
737 		FIB_LOG(LOG_DEBUG2, fibnum, family, "getroute completed: got %s for %s",
738 		    nhop_print_buf_any(rnd.rnd_nhop, nhbuf, sizeof(nhbuf)),
739 		    rt_print_buf(rt, rtbuf, sizeof(rtbuf)));
740 	}
741 
742 	hdr->nlmsg_type = NL_RTM_NEWROUTE;
743 	dump_px(fibnum, hdr, rt, &rnd, npt->nw);
744 
745 	return (0);
746 }
747 
748 static int
handle_rtm_dump(struct nlpcb * nlp,uint32_t fibnum,int family,struct nlmsghdr * hdr,struct nl_writer * nw)749 handle_rtm_dump(struct nlpcb *nlp, uint32_t fibnum, int family,
750     struct nlmsghdr *hdr, struct nl_writer *nw)
751 {
752 	struct netlink_walkargs wa = {
753 		.nlp = nlp,
754 		.nw = nw,
755 		.hdr.nlmsg_pid = hdr->nlmsg_pid,
756 		.hdr.nlmsg_seq = hdr->nlmsg_seq,
757 		.hdr.nlmsg_type = NL_RTM_NEWROUTE,
758 		.hdr.nlmsg_flags = hdr->nlmsg_flags | NLM_F_MULTI,
759 	};
760 
761 	if (fibnum == RT_TABLE_UNSPEC) {
762 		for (int i = 0; i < V_rt_numfibs; i++) {
763 			dump_rtable_fib(&wa, i, family);
764 			if (wa.error != 0)
765 				break;
766 		}
767 	} else
768 		dump_rtable_fib(&wa, fibnum, family);
769 
770 	if (wa.error == 0 && wa.dumped_tables == 0) {
771 		FIB_LOG(LOG_DEBUG, fibnum, family, "incorrect fibnum/family");
772 		wa.error = ESRCH;
773 		// How do we propagate it?
774 	}
775 
776 	if (!nlmsg_end_dump(wa.nw, wa.error, &wa.hdr)) {
777                 NL_LOG(LOG_DEBUG, "Unable to finalize the dump");
778                 return (ENOMEM);
779         }
780 
781 	return (wa.error);
782 }
783 
784 static struct nhop_object *
finalize_nhop(struct nhop_object * nh,const struct sockaddr * dst,int * perror)785 finalize_nhop(struct nhop_object *nh, const struct sockaddr *dst, int *perror)
786 {
787 	/*
788 	 * The following MUST be filled:
789 	 *  nh_ifp, nh_ifa, nh_gw
790 	 */
791 	if (nh->gw_sa.sa_family == 0) {
792 		/*
793 		 * Empty gateway. Can be direct route with RTA_OIF set.
794 		 */
795 		if (nh->nh_ifp != NULL)
796 			nhop_set_direct_gw(nh, nh->nh_ifp);
797 		else {
798 			NL_LOG(LOG_DEBUG, "empty gateway and interface, skipping");
799 			*perror = EINVAL;
800 			return (NULL);
801 		}
802 		/* Both nh_ifp and gateway are set */
803 	} else {
804 		/* Gateway is set up, we can derive ifp if not set */
805 		if (nh->nh_ifp == NULL) {
806 			uint32_t fibnum = nhop_get_fibnum(nh);
807 			uint32_t flags = 0;
808 
809 			if (nh->nh_flags & NHF_GATEWAY)
810 				flags = RTF_GATEWAY;
811 			else if (nh->nh_flags & NHF_HOST)
812 				flags = RTF_HOST;
813 
814 			struct ifaddr *ifa = ifa_ifwithroute(flags, dst, &nh->gw_sa, fibnum);
815 			if (ifa == NULL) {
816 				NL_LOG(LOG_DEBUG, "Unable to determine ifp, skipping");
817 				*perror = EINVAL;
818 				return (NULL);
819 			}
820 			nhop_set_transmit_ifp(nh, ifa->ifa_ifp);
821 		}
822 	}
823 	/* Both nh_ifp and gateway are set */
824 	if (nh->nh_ifa == NULL) {
825 		const struct sockaddr *gw_sa = &nh->gw_sa;
826 
827 		if (gw_sa->sa_family != dst->sa_family) {
828 			/*
829 			 * Use dst as the target for determining the default
830 			 * preferred ifa IF
831 			 * 1) the gateway is link-level (e.g. direct route)
832 			 * 2) the gateway family is different (e.g. IPv4 over IPv6).
833 			 */
834 			gw_sa = dst;
835 		}
836 
837 		struct ifaddr *ifa = ifaof_ifpforaddr(gw_sa, nh->nh_ifp);
838 		if (ifa == NULL) {
839 			/* Try link-level ifa. */
840 			gw_sa = &nh->gw_sa;
841 			ifa = ifaof_ifpforaddr(gw_sa, nh->nh_ifp);
842 			if (ifa == NULL) {
843 				NL_LOG(LOG_DEBUG, "Unable to determine ifa, skipping");
844 				*perror = EINVAL;
845 				return (NULL);
846 			}
847 		}
848 		nhop_set_src(nh, ifa);
849 	}
850 
851 	return (nhop_get_nhop(nh, perror));
852 }
853 
854 static int
get_pxflag(const struct nl_parsed_route * attrs)855 get_pxflag(const struct nl_parsed_route *attrs)
856 {
857 	int pxflag = 0;
858 	switch (attrs->rtm_family) {
859 	case AF_INET:
860 		if (attrs->rtm_dst_len == 32)
861 			pxflag = NHF_HOST;
862 		else if (attrs->rtm_dst_len == 0)
863 			pxflag = NHF_DEFAULT;
864 		break;
865 	case AF_INET6:
866 		if (attrs->rtm_dst_len == 128)
867 			pxflag = NHF_HOST;
868 		else if (attrs->rtm_dst_len == 0)
869 			pxflag = NHF_DEFAULT;
870 		break;
871 	}
872 
873 	return (pxflag);
874 }
875 
876 static int
get_op_flags(int nlm_flags)877 get_op_flags(int nlm_flags)
878 {
879 	int op_flags = 0;
880 
881 	op_flags |= (nlm_flags & NLM_F_REPLACE) ? RTM_F_REPLACE : 0;
882 	op_flags |= (nlm_flags & NLM_F_EXCL) ? RTM_F_EXCL : 0;
883 	op_flags |= (nlm_flags & NLM_F_CREATE) ? RTM_F_CREATE : 0;
884 	op_flags |= (nlm_flags & NLM_F_APPEND) ? RTM_F_APPEND : 0;
885 
886 	return (op_flags);
887 }
888 
889 static int
create_nexthop_one(struct nl_parsed_route * attrs,struct rta_mpath_nh * mpnh,struct nl_pstate * npt,struct nhop_object ** pnh)890 create_nexthop_one(struct nl_parsed_route *attrs, struct rta_mpath_nh *mpnh,
891     struct nl_pstate *npt, struct nhop_object **pnh)
892 {
893 	int error;
894 
895 	if (mpnh->gw == NULL)
896 		return (EINVAL);
897 
898 	struct nhop_object *nh = nhop_alloc(attrs->rta_table, attrs->rtm_family);
899 	if (nh == NULL)
900 		return (ENOMEM);
901 
902 	error = nl_set_nexthop_gw(nh, mpnh->gw, mpnh->ifp, npt);
903 	if (error != 0) {
904 		nhop_free(nh);
905 		return (error);
906 	}
907 	if (mpnh->ifp != NULL)
908 		nhop_set_transmit_ifp(nh, mpnh->ifp);
909 	if (attrs->rta_pref_src != NULL) {
910 		error = nl_set_nexthop_prefsrc(nh, attrs->rta_pref_src);
911 		if (error != 0) {
912 			nhop_free(nh);
913 			return (error);
914 		}
915 	}
916 	nhop_set_pxtype_flag(nh, get_pxflag(attrs));
917 	nhop_set_rtflags(nh, attrs->rta_rtflags);
918 	nhop_set_metric(nh, attrs->rta_metric);
919 	if (attrs->rtm_protocol > RTPROT_STATIC)
920 		nhop_set_origin(nh, attrs->rtm_protocol);
921 
922 	*pnh = finalize_nhop(nh, attrs->rta_dst, &error);
923 
924 	return (error);
925 }
926 
927 static struct nhop_object *
create_nexthop_from_attrs(struct nl_parsed_route * attrs,struct nl_pstate * npt,int * perror)928 create_nexthop_from_attrs(struct nl_parsed_route *attrs,
929     struct nl_pstate *npt, int *perror)
930 {
931 	struct nhop_object *nh = NULL;
932 	int error = 0;
933 	uint32_t nh_expire = 0;
934 
935 	if (attrs->rta_multipath != NULL) {
936 		/* Multipath w/o explicit nexthops */
937 		int num_nhops = attrs->rta_multipath->num_nhops;
938 		struct weightened_nhop *wn = npt_alloc(npt, sizeof(*wn) * num_nhops);
939 
940 		if (wn == NULL) {
941 			*perror = ENOMEM;
942 			return (NULL);
943 		}
944 		for (int i = 0; i < num_nhops; i++) {
945 			struct rta_mpath_nh *mpnh = &attrs->rta_multipath->nhops[i];
946 
947 			error = create_nexthop_one(attrs, mpnh, npt, &wn[i].nh);
948 			if (error != 0) {
949 				for (int j = 0; j < i; j++)
950 					nhop_free(wn[j].nh);
951 				break;
952 			}
953 			wn[i].weight = mpnh->rtnh_weight > 0 ? mpnh->rtnh_weight : 1;
954 		}
955 		if (error == 0) {
956 			struct rib_head *rh = nhop_get_rh(wn[0].nh);
957 			struct nhgrp_object *nhg;
958 
959 			nhg = nhgrp_alloc(rh->rib_fibnum, rh->rib_family,
960 			    wn, num_nhops, perror);
961 			if (nhg != NULL) {
962 				if (attrs->rtm_protocol > RTPROT_STATIC)
963 					nhgrp_set_origin(nhg, attrs->rtm_protocol);
964 				nhg = nhgrp_get_nhgrp(nhg, perror);
965 			}
966 			for (int i = 0; i < num_nhops; i++)
967 				nhop_free(wn[i].nh);
968 			if (nhg != NULL)
969 				return ((struct nhop_object *)nhg);
970 			error = *perror;
971 		}
972 		*perror = error;
973 	} else {
974 		nh = nhop_alloc(attrs->rta_table, attrs->rtm_family);
975 		if (nh == NULL) {
976 			*perror = ENOMEM;
977 			return (NULL);
978 		}
979 		if (attrs->rta_gw != NULL) {
980 			*perror = nl_set_nexthop_gw(nh, attrs->rta_gw, attrs->rta_oif, npt);
981 			if (*perror != 0) {
982 				nhop_free(nh);
983 				return (NULL);
984 			}
985 		}
986 		if (attrs->rta_oif != NULL)
987 			nhop_set_transmit_ifp(nh, attrs->rta_oif);
988 		if (attrs->rta_pref_src != NULL) {
989 			*perror = nl_set_nexthop_prefsrc(nh, attrs->rta_pref_src);
990 			if (*perror != 0) {
991 				nhop_free(nh);
992 				return (NULL);
993 			}
994 		}
995 		if (attrs->rtax_mtu != 0)
996 			nhop_set_mtu(nh, attrs->rtax_mtu, true);
997 		if (attrs->rta_expire > 0) {
998 			nh_expire = attrs->rta_expire - time_second + time_uptime;
999 			nhop_set_expire(nh, nh_expire);
1000 		}
1001 		if (attrs->rta_rtflags & RTF_BROADCAST)
1002 			nhop_set_broadcast(nh, true);
1003 		if (attrs->rtm_protocol > RTPROT_STATIC)
1004 			nhop_set_origin(nh, attrs->rtm_protocol);
1005 		nhop_set_metric(nh, attrs->rta_metric);
1006 		nhop_set_pxtype_flag(nh, get_pxflag(attrs));
1007 		nhop_set_rtflags(nh, attrs->rta_rtflags);
1008 
1009 		switch (attrs->rtm_type) {
1010 		case RTN_UNICAST:
1011 			break;
1012 		case RTN_BLACKHOLE:
1013 			nhop_set_blackhole(nh, RTF_BLACKHOLE);
1014 			break;
1015 		case RTN_PROHIBIT:
1016 		case RTN_UNREACHABLE:
1017 			nhop_set_blackhole(nh, RTF_REJECT);
1018 			break;
1019 		/* TODO: return ENOTSUP for other types if strict option is set */
1020 		}
1021 
1022 		nh = finalize_nhop(nh, attrs->rta_dst, perror);
1023 	}
1024 
1025 	return (nh);
1026 }
1027 
1028 /* pre-2.6.19 Linux API compatibility: prefer RTA_TABLE, fall back to rtm_table */
1029 static inline void
old_linux_compat(struct nl_parsed_route * attrs)1030 old_linux_compat(struct nl_parsed_route *attrs)
1031 {
1032 	if (attrs->rtm_table > 0 && attrs->rta_table == 0)
1033 		attrs->rta_table = attrs->rtm_table;
1034 }
1035 
1036 static int
rtnl_handle_newroute(struct nlmsghdr * hdr,struct nlpcb * nlp,struct nl_pstate * npt)1037 rtnl_handle_newroute(struct nlmsghdr *hdr, struct nlpcb *nlp,
1038     struct nl_pstate *npt)
1039 {
1040 	struct rib_cmd_info rc = {};
1041 	struct nhop_object *nh = NULL;
1042 	int error;
1043 
1044 	struct nl_parsed_route attrs = {};
1045 	error = nl_parse_nlmsg(hdr, &rtm_parser, npt, &attrs);
1046 	if (error != 0)
1047 		return (error);
1048 
1049 	/* Check if we have enough data */
1050 	if (attrs.rta_dst == NULL) {
1051 		NL_LOG(LOG_DEBUG, "missing RTA_DST");
1052 		return (EINVAL);
1053 	}
1054 
1055 	old_linux_compat(&attrs);
1056 	if (attrs.rta_table >= V_rt_numfibs || attrs.rtm_family >= AF_MAX) {
1057 		NLMSG_REPORT_ERR_MSG(npt, "invalid fib");
1058 		return (EINVAL);
1059 	}
1060 
1061 	if (attrs.rta_nh_id != 0) {
1062 		/* Referenced uindex */
1063 		int pxflag = get_pxflag(&attrs);
1064 		nh = nl_find_nhop(attrs.rta_table, attrs.rtm_family, attrs.rta_nh_id,
1065 		    pxflag, &error);
1066 		if (error != 0)
1067 			return (error);
1068 	} else {
1069 		nh = create_nexthop_from_attrs(&attrs, npt, &error);
1070 		if (error != 0) {
1071 			NL_LOG(LOG_DEBUG, "Error creating nexthop");
1072 			return (error);
1073 		}
1074 	}
1075 
1076 	if (!NH_IS_NHGRP(nh) && attrs.rta_weight == 0)
1077 		attrs.rta_weight = RT_DEFAULT_WEIGHT;
1078 	struct route_nhop_data rnd = { .rnd_nhop = nh, .rnd_weight = attrs.rta_weight };
1079 	int op_flags = get_op_flags(hdr->nlmsg_flags);
1080 
1081 	error = rib_add_route_px(attrs.rta_table, attrs.rta_dst, attrs.rtm_dst_len,
1082 	    &rnd, op_flags, &rc);
1083 	if (error == 0)
1084 		report_operation(attrs.rta_table, &rc, nlp, hdr);
1085 	return (error);
1086 }
1087 
1088 static int
path_match_func(const struct rtentry * rt,const struct nhop_object * nh,void * _data)1089 path_match_func(const struct rtentry *rt, const struct nhop_object *nh, void *_data)
1090 {
1091 	struct nl_parsed_route *attrs = (struct nl_parsed_route *)_data;
1092 
1093 	if (attrs->rta_metric != 0 && attrs->rta_metric != nhop_get_metric(nh))
1094 		return (0);
1095 
1096 	if ((attrs->rta_gw != NULL) && !rib_match_gw(rt, nh, attrs->rta_gw))
1097 		return (0);
1098 
1099 	if ((attrs->rta_oif != NULL) && (attrs->rta_oif != nh->nh_ifp))
1100 		return (0);
1101 
1102 	return (1);
1103 }
1104 
1105 static int
rtnl_handle_delroute(struct nlmsghdr * hdr,struct nlpcb * nlp,struct nl_pstate * npt)1106 rtnl_handle_delroute(struct nlmsghdr *hdr, struct nlpcb *nlp,
1107     struct nl_pstate *npt)
1108 {
1109 	struct rib_cmd_info rc;
1110 	int error;
1111 
1112 	struct nl_parsed_route attrs = {};
1113 	error = nl_parse_nlmsg(hdr, &rtm_parser, npt, &attrs);
1114 	if (error != 0)
1115 		return (error);
1116 
1117 	if (attrs.rta_dst == NULL) {
1118 		NLMSG_REPORT_ERR_MSG(npt, "RTA_DST is not set");
1119 		return (ESRCH);
1120 	}
1121 
1122 	old_linux_compat(&attrs);
1123 	if (attrs.rta_table >= V_rt_numfibs || attrs.rtm_family >= AF_MAX) {
1124 		NLMSG_REPORT_ERR_MSG(npt, "invalid fib");
1125 		return (EINVAL);
1126 	}
1127 
1128 	error = rib_del_route_px(attrs.rta_table, attrs.rta_dst,
1129 	    attrs.rtm_dst_len, path_match_func, &attrs,
1130 	    (attrs.rta_rtflags & RTF_PINNED) ? RTM_F_FORCE : 0, &rc);
1131 	if (error == 0)
1132 		report_operation(attrs.rta_table, &rc, nlp, hdr);
1133 	return (error);
1134 }
1135 
1136 static int
rtnl_handle_getroute(struct nlmsghdr * hdr,struct nlpcb * nlp,struct nl_pstate * npt)1137 rtnl_handle_getroute(struct nlmsghdr *hdr, struct nlpcb *nlp, struct nl_pstate *npt)
1138 {
1139 	int error;
1140 
1141 	struct nl_parsed_route attrs = {};
1142 	error = nl_parse_nlmsg(hdr, &rtm_parser, npt, &attrs);
1143 	if (error != 0)
1144 		return (error);
1145 
1146 	old_linux_compat(&attrs);
1147 	if (attrs.rta_table >= V_rt_numfibs || attrs.rtm_family >= AF_MAX) {
1148 		NLMSG_REPORT_ERR_MSG(npt, "invalid fib");
1149 		return (EINVAL);
1150 	}
1151 
1152 	if (hdr->nlmsg_flags & NLM_F_DUMP)
1153 		error = handle_rtm_dump(nlp, attrs.rta_table, attrs.rtm_family, hdr, npt->nw);
1154 	else
1155 		error = handle_rtm_getroute(nlp, &attrs, hdr, npt);
1156 
1157 	return (error);
1158 }
1159 
1160 void
rtnl_handle_route_event(uint32_t fibnum,const struct rib_cmd_info * rc)1161 rtnl_handle_route_event(uint32_t fibnum, const struct rib_cmd_info *rc)
1162 {
1163 	struct nl_writer nw;
1164 	int family, nlm_flags = 0;
1165 
1166 	family = rt_get_family(rc->rc_rt);
1167 
1168 	/* XXX: check if there are active listeners first */
1169 
1170 	/* TODO: consider passing PID/type/seq */
1171 	switch (rc->rc_cmd) {
1172 	case RTM_ADD:
1173 		nlm_flags = NLM_F_EXCL | NLM_F_CREATE;
1174 		break;
1175 	case RTM_CHANGE:
1176 		nlm_flags = NLM_F_REPLACE;
1177 		break;
1178 	case RTM_DELETE:
1179 		nlm_flags = 0;
1180 		break;
1181 	}
1182 	IF_DEBUG_LEVEL(LOG_DEBUG2) {
1183 		char rtbuf[NHOP_PRINT_BUFSIZE] __unused;
1184 		FIB_LOG(LOG_DEBUG2, fibnum, family,
1185 		    "received event %s for %s / nlm_flags=%X",
1186 		    rib_print_cmd(rc->rc_cmd),
1187 		    rt_print_buf(rc->rc_rt, rtbuf, sizeof(rtbuf)),
1188 		    nlm_flags);
1189 	}
1190 
1191 	struct nlmsghdr hdr = {
1192 		.nlmsg_flags = nlm_flags,
1193 		.nlmsg_type = get_rtmsg_type_from_rtsock(rc->rc_cmd),
1194 	};
1195 
1196 	struct route_nhop_data rnd = {
1197 		.rnd_nhop = rc_get_nhop(rc),
1198 		.rnd_weight = rc->rc_nh_weight,
1199 	};
1200 
1201 	uint32_t group_id = family_to_group(family);
1202 	if (!nl_writer_group(&nw, NLMSG_SMALL, NETLINK_ROUTE, group_id, 0,
1203 	    false)) {
1204 		NL_LOG(LOG_DEBUG, "error allocating event buffer");
1205 		return;
1206 	}
1207 
1208 	dump_px(fibnum, &hdr, rc->rc_rt, &rnd, &nw);
1209 	nlmsg_flush(&nw);
1210 }
1211 
1212 static const struct rtnl_cmd_handler cmd_handlers[] = {
1213 	{
1214 		.cmd = NL_RTM_GETROUTE,
1215 		.name = "RTM_GETROUTE",
1216 		.cb = &rtnl_handle_getroute,
1217 		.flags = RTNL_F_ALLOW_NONVNET_JAIL,
1218 	},
1219 	{
1220 		.cmd = NL_RTM_DELROUTE,
1221 		.name = "RTM_DELROUTE",
1222 		.cb = &rtnl_handle_delroute,
1223 		.priv = PRIV_NET_ROUTE,
1224 		.flags = RTNL_F_ALLOW_NONVNET_JAIL,
1225 	},
1226 	{
1227 		.cmd = NL_RTM_NEWROUTE,
1228 		.name = "RTM_NEWROUTE",
1229 		.cb = &rtnl_handle_newroute,
1230 		.priv = PRIV_NET_ROUTE,
1231 		.flags = RTNL_F_ALLOW_NONVNET_JAIL,
1232 	}
1233 };
1234 
1235 static const struct nlhdr_parser *all_parsers[] = {&mpath_parser, &metrics_parser, &rtm_parser};
1236 
1237 void
rtnl_routes_init(void)1238 rtnl_routes_init(void)
1239 {
1240 	NL_VERIFY_PARSERS(all_parsers);
1241 	rtnl_register_messages(cmd_handlers, nitems(cmd_handlers));
1242 }
1243