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