xref: /freebsd/usr.bin/netstat/nhgrp.c (revision 535af610)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2020 Alexander V. Chernikov
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 <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 #include <sys/param.h>
31 #include <sys/socket.h>
32 #include <sys/sysctl.h>
33 
34 #include <net/if.h>
35 #include <net/if_dl.h>
36 #include <net/if_types.h>
37 #include <net/route.h>
38 #include <net/route/nhop.h>
39 
40 #include <netinet/in.h>
41 
42 #include <arpa/inet.h>
43 #include <libutil.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdbool.h>
47 #include <string.h>
48 #include <sysexits.h>
49 #include <unistd.h>
50 #include <err.h>
51 #include <libxo/xo.h>
52 #include "netstat.h"
53 #include "common.h"
54 
55 #define	WID_GW_DEFAULT(af)	(((af) == AF_INET6) ? 40 : 18)
56 
57 static int wid_gw;
58 static int wid_if = 10;
59 static int wid_nhidx = 8;
60 static int wid_refcnt = 8;
61 
62 struct nhop_entry {
63 	char	gw[64];
64 	char	ifname[IFNAMSIZ];
65 };
66 
67 struct nhop_map {
68 	struct nhop_entry	*ptr;
69 	size_t			size;
70 };
71 static struct nhop_map global_nhop_map;
72 
73 static struct ifmap_entry *ifmap;
74 static size_t ifmap_size;
75 
76 static struct nhop_entry *
77 nhop_get(struct nhop_map *map, uint32_t idx)
78 {
79 
80 	if (idx >= map->size)
81 		return (NULL);
82 	if (*map->ptr[idx].ifname == '\0')
83 		return (NULL);
84 	return &map->ptr[idx];
85 }
86 
87 static void
88 print_nhgroup_header(int af1 __unused)
89 {
90 
91 	xo_emit("{T:/%-*.*s}{T:/%-*.*s}{T:/%*.*s}{T:/%*.*s}{T:/%*.*s}"
92 	    "{T:/%*.*s}{T:/%*s}\n",
93 		wid_nhidx,	wid_nhidx,	"GrpIdx",
94 		wid_nhidx,	wid_nhidx,	"NhIdx",
95 		wid_nhidx,	wid_nhidx,	"Weight",
96 		wid_nhidx,	wid_nhidx,	"Slots",
97 		wid_gw,		wid_gw,		"Gateway",
98 		wid_if,		wid_if,		"Netif",
99 		wid_refcnt,			"Refcnt");
100 }
101 
102 static void
103 print_padding(char sym, int len)
104 {
105 	char buffer[56];
106 
107 	memset(buffer, sym, sizeof(buffer));
108 	buffer[0] = '{';
109 	buffer[1] = 'P';
110 	buffer[2] = ':';
111 	buffer[3] = ' ';
112 	buffer[len + 3] = '}';
113 	buffer[len + 4] = '\0';
114 	xo_emit(buffer);
115 }
116 
117 
118 static void
119 print_nhgroup_entry_sysctl(const char *name, struct rt_msghdr *rtm,
120     struct nhgrp_external *nhge)
121 {
122 	char buffer[128];
123 	struct nhop_entry *ne;
124 	struct nhgrp_nhop_external *ext_cp, *ext_dp;
125 	struct nhgrp_container *nhg_cp, *nhg_dp;
126 
127 	nhg_cp = (struct nhgrp_container *)(nhge + 1);
128 	if (nhg_cp->nhgc_type != NHG_C_TYPE_CNHOPS || nhg_cp->nhgc_subtype != 0)
129 		return;
130 	ext_cp = (struct nhgrp_nhop_external *)(nhg_cp + 1);
131 
132 	nhg_dp = (struct nhgrp_container *)((char *)nhg_cp + nhg_cp->nhgc_len);
133 	if (nhg_dp->nhgc_type != NHG_C_TYPE_DNHOPS || nhg_dp->nhgc_subtype != 0)
134 		return;
135 	ext_dp = (struct nhgrp_nhop_external *)(nhg_dp + 1);
136 
137 	xo_open_instance(name);
138 
139 	snprintf(buffer, sizeof(buffer), "{[:-%d}{:nhgrp-index/%%lu}{]:} ", wid_nhidx);
140 
141 	xo_emit(buffer, nhge->nhg_idx);
142 
143 	/* nhidx */
144 	print_padding('-', wid_nhidx);
145 	/* weight */
146 	print_padding('-', wid_nhidx);
147 	/* slots */
148 	print_padding('-', wid_nhidx);
149 	print_padding('-', wid_gw);
150 	print_padding('-', wid_if);
151 	xo_emit("{t:nhg-refcnt/%*lu}", wid_refcnt, nhge->nhg_refcount);
152 	xo_emit("\n");
153 
154 	xo_open_list("nhop-weights");
155 	for (uint32_t i = 0; i < nhg_cp->nhgc_count; i++) {
156 		/* TODO: optimize slots calculations */
157 		uint32_t slots = 0;
158 		for (uint32_t sidx = 0; sidx < nhg_dp->nhgc_count; sidx++) {
159 			if (ext_dp[sidx].nh_idx == ext_cp[i].nh_idx)
160 				slots++;
161 		}
162 		xo_open_instance("nhop-weight");
163 		print_padding(' ', wid_nhidx);
164 		// nh index
165 		xo_emit("{t:nh-index/%*lu}", wid_nhidx, ext_cp[i].nh_idx);
166 		xo_emit("{t:nh-weight/%*lu}", wid_nhidx, ext_cp[i].nh_weight);
167 		xo_emit("{t:nh-slots/%*lu}", wid_nhidx, slots);
168 		ne = nhop_get(&global_nhop_map, ext_cp[i].nh_idx);
169 		if (ne != NULL) {
170 			xo_emit("{t:nh-gw/%*.*s}", wid_gw, wid_gw, ne->gw);
171 			xo_emit("{t:nh-interface/%*.*s}", wid_if, wid_if, ne->ifname);
172 		}
173 		xo_emit("\n");
174 		xo_close_instance("nhop-weight");
175 	}
176 	xo_close_list("nhop-weights");
177 	xo_close_instance(name);
178 }
179 
180 static int
181 cmp_nhg_idx(const void *_a, const void *_b)
182 {
183 	const struct nhops_map *a, *b;
184 
185 	a = _a;
186 	b = _b;
187 
188 	if (a->idx > b->idx)
189 		return (1);
190 	else if (a->idx < b->idx)
191 		return (-1);
192 	return (0);
193 }
194 
195 static void
196 dump_nhgrp_sysctl(int fibnum, int af, struct nhops_dump *nd)
197 {
198 	size_t needed;
199 	int mib[7];
200 	char *buf, *next, *lim;
201 	struct rt_msghdr *rtm;
202 	struct nhgrp_external *nhg;
203 	struct nhops_map *nhg_map;
204 	size_t nhg_count, nhg_size;
205 
206 	mib[0] = CTL_NET;
207 	mib[1] = PF_ROUTE;
208 	mib[2] = 0;
209 	mib[3] = af;
210 	mib[4] = NET_RT_NHGRP;
211 	mib[5] = 0;
212 	mib[6] = fibnum;
213 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
214 		err(EX_OSERR, "sysctl: net.route.0.%d.nhgrpdump.%d estimate",
215 		    af, fibnum);
216 	if ((buf = malloc(needed)) == NULL)
217 		errx(2, "malloc(%lu)", (unsigned long)needed);
218 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
219 		err(1, "sysctl: net.route.0.%d.nhgrpdump.%d", af, fibnum);
220 	lim  = buf + needed;
221 
222 	/*
223 	 * nexhops groups are received unsorted. Collect everything first,
224 	 * and sort prior displaying.
225 	 */
226 	nhg_count = 0;
227 	nhg_size = 16;
228 	nhg_map = calloc(nhg_size, sizeof(struct nhops_map));
229 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
230 		rtm = (struct rt_msghdr *)next;
231 		if (rtm->rtm_version != RTM_VERSION)
232 			continue;
233 
234 		if (nhg_count >= nhg_size) {
235 			nhg_size *= 2;
236 			nhg_map = realloc(nhg_map, nhg_size * sizeof(struct nhops_map));
237 		}
238 
239 		nhg = (struct nhgrp_external *)(rtm + 1);
240 		nhg_map[nhg_count].idx = nhg->nhg_idx;
241 		nhg_map[nhg_count].rtm = rtm;
242 		nhg_count++;
243 	}
244 
245 	if (nhg_count > 0)
246 		qsort(nhg_map, nhg_count, sizeof(struct nhops_map), cmp_nhg_idx);
247 	nd->nh_buf = buf;
248 	nd->nh_count = nhg_count;
249 	nd->nh_map = nhg_map;
250 }
251 
252 static void
253 print_nhgrp_sysctl(int fibnum, int af)
254 {
255 	struct nhops_dump nd;
256 	struct nhgrp_external *nhg;
257 	struct rt_msghdr *rtm;
258 
259 	dump_nhgrp_sysctl(fibnum, af, &nd);
260 
261 	xo_open_container("nhgrp-table");
262 	xo_open_list("rt-family");
263 	if (nd.nh_count > 0) {
264 		wid_gw = WID_GW_DEFAULT(af);
265 		xo_open_instance("rt-family");
266 		pr_family(af);
267 		xo_open_list("nhgrp-entry");
268 
269 		print_nhgroup_header(af);
270 
271 		for (size_t i = 0; i < nd.nh_count; i++) {
272 			rtm = nd.nh_map[i].rtm;
273 			nhg = (struct nhgrp_external *)(rtm + 1);
274 			print_nhgroup_entry_sysctl("nhgrp-entry", rtm, nhg);
275 		}
276 	}
277 	xo_close_list("rt-family");
278 	xo_close_container("nhgrp-table");
279 	free(nd.nh_buf);
280 }
281 
282 static void
283 update_global_map(struct nhop_external *nh)
284 {
285 	char iface_name[128];
286 	char gw_addr[64];
287 	struct nhop_addrs *na;
288 	struct sockaddr *sa_gw;
289 
290 	na = (struct nhop_addrs *)((char *)nh + nh->nh_len);
291 	sa_gw = (struct sockaddr *)((char *)na + na->gw_sa_off);
292 
293 	memset(iface_name, 0, sizeof(iface_name));
294 	if (nh->ifindex < (uint32_t)ifmap_size) {
295 		strlcpy(iface_name, ifmap[nh->ifindex].ifname,
296 		    sizeof(iface_name));
297 		if (*iface_name == '\0')
298 			strlcpy(iface_name, "---", sizeof(iface_name));
299 	}
300 
301 	if (nh->nh_flags & NHF_GATEWAY) {
302 		const char *cp;
303 		cp = fmt_sockaddr(sa_gw, NULL, RTF_HOST);
304 		strlcpy(gw_addr, cp, sizeof(gw_addr));
305 	} else
306 		snprintf(gw_addr, sizeof(gw_addr), "%s/resolve", iface_name);
307 
308 	nhop_map_update(&global_nhop_map, nh->nh_idx, gw_addr, iface_name);
309 }
310 
311 static void
312 prepare_nh_map(int fibnum, int af)
313 {
314 	struct nhops_dump nd;
315 	struct nhop_external *nh;
316 	struct rt_msghdr *rtm;
317 
318 	dump_nhops_sysctl(fibnum, af, &nd);
319 
320 	for (size_t i = 0; i < nd.nh_count; i++) {
321 		rtm = nd.nh_map[i].rtm;
322 		nh = (struct nhop_external *)(rtm + 1);
323 		update_global_map(nh);
324 	}
325 
326 	free(nd.nh_buf);
327 }
328 
329 void
330 nhgrp_print(int fibnum, int af)
331 {
332 	size_t intsize;
333 	int numfibs;
334 
335 	intsize = sizeof(int);
336 	if (fibnum == -1 &&
337 	    sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
338 		fibnum = 0;
339 	if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
340 		numfibs = 1;
341 	if (fibnum < 0 || fibnum > numfibs - 1)
342 		errx(EX_USAGE, "%d: invalid fib", fibnum);
343 
344 	ifmap = prepare_ifmap(&ifmap_size);
345 	prepare_nh_map(fibnum, af);
346 
347 	xo_open_container("route-nhgrp-information");
348 	xo_emit("{T:Nexthop groups data}");
349 	if (fibnum)
350 		xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
351 	xo_emit("\n");
352 	print_nhgrp_sysctl(fibnum, af);
353 	xo_close_container("route-nhgrp-information");
354 }
355 
356