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