xref: /freebsd/sbin/ifconfig/ifconfig_netlink.c (revision 70bc3f4331a1b6e7045ae5326cbe03428503b612)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2022 Alexander V. Chernikov <melifaro@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <stdbool.h>
32 #include <err.h>
33 #include <errno.h>
34 #include <netdb.h>
35 
36 #include <sys/bitcount.h>
37 #include <sys/param.h>
38 #include <sys/linker.h>
39 #include <sys/module.h>
40 #include <sys/socket.h>
41 #include <sys/sysctl.h>
42 #include <sys/time.h>
43 #include <sys/types.h>
44 
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 
48 #include <net/ethernet.h>
49 #include <net/if.h>
50 #include <net/if_dl.h>
51 #include <net/if_strings.h>
52 #include <net/if_types.h>
53 #include "ifconfig.h"
54 #include "ifconfig_netlink.h"
55 
56 static const char	*IFFBITS[] = {
57 	"UP",			/* 00:0x1 IFF_UP*/
58 	"BROADCAST",		/* 01:0x2 IFF_BROADCAST*/
59 	"DEBUG",		/* 02:0x4 IFF_DEBUG*/
60 	"LOOPBACK",		/* 03:0x8 IFF_LOOPBACK*/
61 	"POINTOPOINT",		/* 04:0x10 IFF_POINTOPOINT*/
62 	"NEEDSEPOCH",		/* 05:0x20 IFF_NEEDSEPOCH*/
63 	"RUNNING",		/* 06:0x40 IFF_DRV_RUNNING*/
64 	"NOARP",		/* 07:0x80 IFF_NOARP*/
65 	"PROMISC",		/* 08:0x100 IFF_PROMISC*/
66 	"ALLMULTI",		/* 09:0x200 IFF_ALLMULTI*/
67 	"DRV_OACTIVE",		/* 10:0x400 IFF_DRV_OACTIVE*/
68 	"SIMPLEX",		/* 11:0x800 IFF_SIMPLEX*/
69 	"LINK0",		/* 12:0x1000 IFF_LINK0*/
70 	"LINK1",		/* 13:0x2000 IFF_LINK1*/
71 	"LINK2",		/* 14:0x4000 IFF_LINK2*/
72 	"MULTICAST",		/* 15:0x8000 IFF_MULTICAST*/
73 	"CANTCONFIG",		/* 16:0x10000 IFF_CANTCONFIG*/
74 	"PPROMISC",		/* 17:0x20000 IFF_PPROMISC*/
75 	"MONITOR",		/* 18:0x40000 IFF_MONITOR*/
76 	"STATICARP",		/* 19:0x80000 IFF_STATICARP*/
77 	"STICKYARP",		/* 20:0x100000 IFF_STICKYARP*/
78 	"DYING",		/* 21:0x200000 IFF_DYING*/
79 	"RENAMING",		/* 22:0x400000 IFF_RENAMING*/
80 	"NOGROUP",		/* 23:0x800000 IFF_NOGROUP*/
81 	"LOWER_UP",		/* 24:0x1000000 IFF_NETLINK_1*/
82 };
83 
84 static void
85 print_bits(const char *btype, uint32_t *v, const int v_count,
86     const char **names, const int n_count)
87 {
88 	int num = 0;
89 
90 	for (int i = 0; i < v_count * 32; i++) {
91 		bool is_set = v[i / 32] & (1 << (i % 32));
92 		if (i == 31)
93 			v++;
94 		if (is_set) {
95 			if (num++ == 0)
96 				printf("<");
97 			if (num != 1)
98 				printf(",");
99 			if (i < n_count)
100 				printf("%s", names[i]);
101 			else
102 				printf("%s_%d", btype, i);
103 		}
104 	}
105 	if (num > 0)
106 		printf(">");
107 }
108 
109 static void
110 nl_init_socket(struct snl_state *ss)
111 {
112 	if (snl_init(ss, NETLINK_ROUTE))
113 		return;
114 
115 	if (modfind("netlink") == -1 && errno == ENOENT) {
116 		/* Try to load */
117 		if (kldload("netlink") == -1)
118 			err(1, "netlink is not loaded and load attempt failed");
119 		if (snl_init(ss, NETLINK_ROUTE))
120 			return;
121 	}
122 
123 	err(1, "unable to open netlink socket");
124 }
125 
126 int
127 ifconfig_nl(if_ctx *ctx, int iscreate,
128     const struct afswtch *uafp)
129 {
130 	struct snl_state ss = {};
131 
132 	nl_init_socket(&ss);
133 	ctx->io_ss = &ss;
134 
135 	int error = ifconfig_ioctl(ctx, iscreate, uafp);
136 
137 	snl_free(&ss);
138 	ctx->io_ss = NULL;
139 
140 	return (error);
141 }
142 
143 struct ifa {
144 	struct ifa		*next;
145 	uint32_t		idx;
146 	struct snl_parsed_addr	addr;
147 };
148 
149 struct iface {
150 	struct snl_parsed_link	link;
151 	struct ifa		*ifa;
152 	uint32_t		ifa_count;
153 	uint32_t		idx;
154 };
155 
156 struct ifmap {
157 	uint32_t		size;
158 	uint32_t		count;
159 	struct iface		**ifaces;
160 };
161 
162 /*
163  * Returns ifmap ifindex->snl_parsed_link.
164  * Memory is allocated using snl temporary buffers
165  */
166 static struct ifmap *
167 prepare_ifmap(struct snl_state *ss)
168 {
169 	struct snl_writer nw = {};
170 
171 	snl_init_writer(ss, &nw);
172 	struct nlmsghdr *hdr = snl_create_msg_request(&nw, RTM_GETLINK);
173 	hdr->nlmsg_flags |= NLM_F_DUMP;
174 	snl_reserve_msg_object(&nw, struct ifinfomsg);
175 
176 	if (!snl_finalize_msg(&nw) || !snl_send_message(ss, hdr))
177 		return (NULL);
178 
179 	uint32_t nlmsg_seq = hdr->nlmsg_seq;
180 	struct ifmap *ifmap = snl_allocz(ss, sizeof(*ifmap));
181 	struct snl_errmsg_data e = {};
182 
183 	while ((hdr = snl_read_reply_multi(ss, nlmsg_seq, &e)) != NULL) {
184 		struct iface *iface = snl_allocz(ss, sizeof(*iface));
185 
186 		if (!snl_parse_nlmsg(ss, hdr, &snl_rtm_link_parser, &iface->link))
187 			continue;
188 		if (iface->link.ifi_index >= ifmap->size) {
189 			size_t new_size = MAX(ifmap->size, 32);
190 
191 			while (new_size <= iface->link.ifi_index + 1)
192 				new_size *= 2;
193 
194 			struct iface **ifaces= snl_allocz(ss, new_size * sizeof(void *));
195 			memcpy(ifaces, ifmap->ifaces, ifmap->size * sizeof(void *));
196 			ifmap->ifaces = ifaces;
197 			ifmap->size = new_size;
198 		}
199 		ifmap->ifaces[iface->link.ifi_index] = iface;
200 		ifmap->count++;
201 		iface->idx = ifmap->count;
202 	}
203 	return (ifmap);
204 }
205 
206 uint32_t
207 if_nametoindex_nl(struct snl_state *ss, const char *ifname)
208 {
209 	struct snl_writer nw = {};
210 	struct snl_parsed_link_simple link = {};
211 
212 	snl_init_writer(ss, &nw);
213 	struct nlmsghdr *hdr = snl_create_msg_request(&nw, RTM_GETLINK);
214 	snl_reserve_msg_object(&nw, struct ifinfomsg);
215 	snl_add_msg_attr_string(&nw, IFLA_IFNAME, ifname);
216 
217 	if (!snl_finalize_msg(&nw) || !snl_send_message(ss, hdr))
218 		return (0);
219 
220 	hdr = snl_read_reply(ss, hdr->nlmsg_seq);
221 	if (hdr->nlmsg_type != NL_RTM_NEWLINK)
222 		return (0);
223 	if (!snl_parse_nlmsg(ss, hdr, &snl_rtm_link_parser_simple, &link))
224 		return (0);
225 
226 	return (link.ifi_index);
227 }
228 
229 static void
230 prepare_ifaddrs(struct snl_state *ss, struct ifmap *ifmap)
231 {
232 	struct snl_writer nw = {};
233 
234 	snl_init_writer(ss, &nw);
235 	struct nlmsghdr *hdr = snl_create_msg_request(&nw, RTM_GETADDR);
236 	hdr->nlmsg_flags |= NLM_F_DUMP;
237 	snl_reserve_msg_object(&nw, struct ifaddrmsg);
238 
239 	if (!snl_finalize_msg(&nw) || !snl_send_message(ss, hdr))
240 		return;
241 
242 	uint32_t nlmsg_seq = hdr->nlmsg_seq;
243 	struct snl_errmsg_data e = {};
244 	uint32_t count = 0;
245 
246 	while ((hdr = snl_read_reply_multi(ss, nlmsg_seq, &e)) != NULL) {
247 		struct ifa *ifa = snl_allocz(ss, sizeof(*ifa));
248 
249 		if (!snl_parse_nlmsg(ss, hdr, &snl_rtm_addr_parser, &ifa->addr))
250 			continue;
251 
252 		const uint32_t ifindex = ifa->addr.ifa_index;
253 		if (ifindex >= ifmap->size || ifmap->ifaces[ifindex] == NULL)
254 			continue;
255 		struct iface *iface = ifmap->ifaces[ifindex];
256 		ifa->next = iface->ifa;
257 		ifa->idx = ++count;
258 		iface->ifa = ifa;
259 		iface->ifa_count++;
260 	}
261 }
262 
263 static bool
264 match_iface(struct ifconfig_args *args, struct iface *iface)
265 {
266 	if_link_t *link = &iface->link;
267 
268 	if (args->ifname != NULL && strcmp(args->ifname, link->ifla_ifname))
269 		return (false);
270 
271 	if (!match_if_flags(args, link->ifi_flags))
272 		return (false);
273 
274 	if (!group_member(link->ifla_ifname, args->matchgroup, args->nogroup))
275 		return (false);
276 
277 	if (args->afp == NULL)
278 		return (true);
279 
280 	if (!strcmp(args->afp->af_name, "ether")) {
281 		if (link->ifla_address == NULL)
282 			return (false);
283 
284 		struct sockaddr_dl sdl = {
285 			.sdl_len = sizeof(struct sockaddr_dl),
286 			.sdl_family = AF_LINK,
287 			.sdl_type = link->ifi_type,
288 			.sdl_alen = NLA_DATA_LEN(link->ifla_address),
289 		};
290 		return (match_ether(&sdl));
291 	}
292 
293 	for (struct ifa *ifa = iface->ifa; ifa != NULL; ifa = ifa->next) {
294 		if (args->afp->af_af == ifa->addr.ifa_family)
295 			return (true);
296 	}
297 
298 	return (false);
299 }
300 
301 /* Sort according to the kernel-provided order */
302 static int
303 cmp_iface(const void *_a, const void *_b)
304 {
305 	const struct iface *a = *((const void * const *)_a);
306 	const struct iface *b = *((const void * const *)_b);
307 
308 	return ((a->idx > b->idx) * 2 - 1);
309 }
310 
311 static int
312 cmp_ifaddr(const void *_a, const void *_b)
313 {
314 	const struct ifa *a = *((const void * const *)_a);
315 	const struct ifa *b = *((const void * const *)_b);
316 
317 	if (a->addr.ifa_family != b->addr.ifa_family)
318 		return ((a->addr.ifa_family > b->addr.ifa_family) * 2 - 1);
319 	return ((a->idx > b->idx) * 2 - 1);
320 }
321 
322 static void
323 sort_iface_ifaddrs(struct snl_state *ss, struct iface *iface)
324 {
325 	if (iface->ifa_count == 0)
326 		return;
327 
328 	struct ifa **sorted_ifaddrs = snl_allocz(ss, iface->ifa_count * sizeof(void *));
329 	struct ifa *ifa = iface->ifa;
330 
331 	for (uint32_t i = 0; i < iface->ifa_count; i++) {
332 		struct ifa *ifa_next = ifa->next;
333 
334 		sorted_ifaddrs[i] = ifa;
335 		ifa->next = NULL;
336 		ifa = ifa_next;
337 	}
338 	qsort(sorted_ifaddrs, iface->ifa_count, sizeof(void *), cmp_ifaddr);
339 	ifa = sorted_ifaddrs[0];
340 	iface->ifa = ifa;
341 	for (uint32_t i = 1; i < iface->ifa_count; i++) {
342 		ifa->next = sorted_ifaddrs[i];
343 		ifa = sorted_ifaddrs[i];
344 	}
345 }
346 
347 static void
348 print_ifcaps(if_ctx *ctx, if_link_t *link)
349 {
350 	uint32_t sz_u32 = roundup2(link->iflaf_caps.nla_bitset_size, 32) / 32;
351 
352 	if (sz_u32 > 0) {
353 		uint32_t *caps = link->iflaf_caps.nla_bitset_value;
354 
355 		printf("\toptions=%x", caps[0]);
356 		print_bits("IFCAPS", caps, sz_u32, ifcap_bit_names, nitems(ifcap_bit_names));
357 		putchar('\n');
358 	}
359 
360 	if (ctx->args->supmedia && sz_u32 > 0) {
361 		uint32_t *caps = link->iflaf_caps.nla_bitset_mask;
362 
363 		printf("\tcapabilities=%x", caps[0]);
364 		print_bits("IFCAPS", caps, sz_u32, ifcap_bit_names, nitems(ifcap_bit_names));
365 		putchar('\n');
366 	}
367 }
368 
369 static void
370 status_nl(if_ctx *ctx, struct iface *iface)
371 {
372 	if_link_t *link = &iface->link;
373 	struct ifconfig_args *args = ctx->args;
374 
375 	printf("%s: ", link->ifla_ifname);
376 
377 	printf("flags=%x", link->ifi_flags);
378 	print_bits("IFF", &link->ifi_flags, 1, IFFBITS, nitems(IFFBITS));
379 
380 	print_metric(ctx);
381 	printf(" mtu %d\n", link->ifla_mtu);
382 
383 	if (link->ifla_ifalias != NULL)
384 		printf("\tdescription: %s\n", link->ifla_ifalias);
385 
386 	print_ifcaps(ctx, link);
387 	tunnel_status(ctx);
388 
389 	if (args->allfamilies | (args->afp != NULL && args->afp->af_af == AF_LINK)) {
390 		/* Start with link-level */
391 		const struct afswtch *p = af_getbyfamily(AF_LINK);
392 		if (p != NULL && link->ifla_address != NULL)
393 			p->af_status(ctx, link, NULL);
394 	}
395 
396 	sort_iface_ifaddrs(ctx->io_ss, iface);
397 
398 	for (struct ifa *ifa = iface->ifa; ifa != NULL; ifa = ifa->next) {
399 		if (args->allfamilies) {
400 			const struct afswtch *p = af_getbyfamily(ifa->addr.ifa_family);
401 
402 			if (p != NULL)
403 				p->af_status(ctx, link, &ifa->addr);
404 		} else if (args->afp->af_af == ifa->addr.ifa_family) {
405 			const struct afswtch *p = args->afp;
406 
407 			p->af_status(ctx, link, &ifa->addr);
408 		}
409 	}
410 
411 	/* TODO: convert to netlink */
412 	if (args->allfamilies)
413 		af_other_status(ctx);
414 	else if (args->afp->af_other_status != NULL)
415 		args->afp->af_other_status(ctx);
416 
417 	print_ifstatus(ctx);
418 	if (args->verbose > 0)
419 		sfp_status(ctx);
420 }
421 
422 static int
423 get_local_socket(void)
424 {
425 	int s = socket(AF_LOCAL, SOCK_DGRAM, 0);
426 
427 	if (s < 0)
428 		err(1, "socket(family %u,SOCK_DGRAM)", AF_LOCAL);
429 	return (s);
430 }
431 
432 void
433 list_interfaces_nl(struct ifconfig_args *args)
434 {
435 	struct snl_state ss = {};
436 	struct ifconfig_context _ctx = {
437 		.args = args,
438 		.io_s = get_local_socket(),
439 		.io_ss = &ss,
440 	};
441 	struct ifconfig_context *ctx = &_ctx;
442 
443 	nl_init_socket(&ss);
444 
445 	struct ifmap *ifmap = prepare_ifmap(&ss);
446 	struct iface **sorted_ifaces = snl_allocz(&ss, ifmap->count * sizeof(void *));
447 	for (uint32_t i = 0, num = 0; i < ifmap->size; i++) {
448 		if (ifmap->ifaces[i] != NULL) {
449 			sorted_ifaces[num++] = ifmap->ifaces[i];
450 			if (num == ifmap->count)
451 				break;
452 		}
453 	}
454 	qsort(sorted_ifaces, ifmap->count, sizeof(void *), cmp_iface);
455 	prepare_ifaddrs(&ss, ifmap);
456 
457 	for (uint32_t i = 0, num = 0; i < ifmap->count; i++) {
458 		struct iface *iface = sorted_ifaces[i];
459 
460 		if (!match_iface(args, iface))
461 			continue;
462 
463 		ctx->ifname = iface->link.ifla_ifname;
464 
465 		if (args->namesonly) {
466 			if (num++ != 0)
467 				printf(" ");
468 			fputs(iface->link.ifla_ifname, stdout);
469 		} else if (args->argc == 0)
470 			status_nl(ctx, iface);
471 		else
472 			ifconfig_ioctl(ctx, 0, args->afp);
473 	}
474 	if (args->namesonly)
475 		printf("\n");
476 
477 	close(ctx->io_s);
478 	snl_free(&ss);
479 }
480 
481