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