xref: /freebsd/usr.bin/netstat/nhops.c (revision 96190b4fef3b4a0cc3ca0606b0c4e3e69a5e6717)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/param.h>
33 #include <sys/protosw.h>
34 #include <sys/socket.h>
35 #include <sys/socketvar.h>
36 #include <sys/sysctl.h>
37 #include <sys/time.h>
38 
39 #include <net/ethernet.h>
40 #include <net/if.h>
41 #include <net/if_dl.h>
42 #include <net/if_types.h>
43 #include <net/route.h>
44 #include <net/route/nhop.h>
45 
46 #include <netinet/in.h>
47 #include <netgraph/ng_socket.h>
48 
49 #include <arpa/inet.h>
50 #include <ifaddrs.h>
51 #include <libutil.h>
52 #include <netdb.h>
53 #include <stdbool.h>
54 #include <stdint.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <stdbool.h>
58 #include <string.h>
59 #include <sysexits.h>
60 #include <unistd.h>
61 #include <libxo/xo.h>
62 #include "netstat.h"
63 #include "common.h"
64 
65 /* column widths; each followed by one space */
66 #define WID_IF_DEFAULT		(Wflag ? IFNAMSIZ : 12)	/* width of netif column */
67 #ifndef INET6
68 #define	WID_DST_DEFAULT(af) 	18	/* width of destination column */
69 #define	WID_GW_DEFAULT(af)	18	/* width of gateway column */
70 #else
71 #define	WID_DST_DEFAULT(af) \
72 	((af) == AF_INET6 ? (numeric_addr ? 33: 18) : 18)
73 #define	WID_GW_DEFAULT(af) \
74 	((af) == AF_INET6 ? (numeric_addr ? 29 : 18) : 18)
75 #endif /*INET6*/
76 static int wid_dst;
77 static int wid_gw;
78 static int wid_flags;
79 static int wid_pksent;
80 static int wid_mtu;
81 static int wid_if;
82 static int wid_nhidx;
83 static int wid_nhtype;
84 static int wid_refcnt;
85 static int wid_prepend;
86 
87 static struct bits nh_bits[] = {
88 	{ NHF_REJECT,	'R', "reject" },
89 	{ NHF_BLACKHOLE,'B', "blackhole" },
90 	{ NHF_REDIRECT,	'r', "redirect" },
91 	{ NHF_GATEWAY,	'G', "gateway" },
92 	{ NHF_DEFAULT,	'd', "default" },
93 	{ NHF_BROADCAST,'b', "broadcast" },
94 	{ 0 , 0, NULL }
95 };
96 
97 static char *nh_types[] = {
98 	"empty", /* 0 */
99 	"v4/resolve", /* 1 */
100 	"v4/gw",
101 	"v6/resolve",
102 	"v6/gw"
103 };
104 
105 struct nhop_entry {
106 	char	gw[64];
107 	char	ifname[IFNAMSIZ];
108 };
109 
110 struct nhop_map {
111 	struct nhop_entry	*ptr;
112 	size_t			size;
113 };
114 static struct nhop_map global_nhop_map;
115 
116 static struct nhop_entry *nhop_get(struct nhop_map *map, uint32_t idx);
117 
118 
119 static struct ifmap_entry *ifmap;
120 static size_t ifmap_size;
121 
122 static void
123 print_sockaddr_buf(char *buf, size_t bufsize, const struct sockaddr *sa)
124 {
125 
126 	switch (sa->sa_family) {
127 	case AF_INET:
128 		inet_ntop(AF_INET, &((struct sockaddr_in *)sa)->sin_addr,
129 		    buf, bufsize);
130 		break;
131 	case AF_INET6:
132 		inet_ntop(AF_INET6, &((struct sockaddr_in6 *)sa)->sin6_addr,
133 		    buf, bufsize);
134 		break;
135 	default:
136 		snprintf(buf, bufsize, "unknown:%d", sa->sa_family);
137 		break;
138 	}
139 }
140 
141 static int
142 print_addr(const char *name, const char *addr, int width)
143 {
144 	char buf[128];
145 	int protrusion;
146 
147 	if (width < 0) {
148 		snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
149 		xo_emit(buf, addr);
150 		protrusion = 0;
151 	} else {
152 		if (Wflag != 0 || numeric_addr) {
153 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
154 			    -width, name);
155 			xo_emit(buf, addr);
156 			protrusion = strlen(addr) - width;
157 			if (protrusion < 0)
158 				protrusion = 0;
159 		} else {
160 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
161 			    -width, name);
162 			xo_emit(buf, width, addr);
163 			protrusion = 0;
164 		}
165 	}
166 	return (protrusion);
167 }
168 
169 
170 static void
171 print_nhop_header(int af1 __unused)
172 {
173 
174 	if (Wflag) {
175 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
176 		    "{T:/%*.*s} {T:/%-*.*s} {T:/%*.*s} {T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
177 			wid_nhidx,	wid_nhidx,	"Idx",
178 			wid_nhtype,	wid_nhtype,	"Type",
179 			wid_dst,	wid_dst,	"IFA",
180 			wid_gw,		wid_gw,		"Gateway",
181 			wid_flags,	wid_flags,	"Flags",
182 			wid_pksent,	wid_pksent,	"Use",
183 			wid_mtu,	wid_mtu,	"Mtu",
184 			wid_if,		wid_if,		"Netif",
185 			wid_if,		wid_if,		"Addrif",
186 			wid_refcnt,	wid_refcnt,	"Refcnt",
187 			wid_prepend,			"Prepend");
188 	} else {
189 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
190 		    " {T:/%*s}\n",
191 			wid_nhidx,	wid_nhidx,	"Idx",
192 			wid_dst,	wid_dst,	"IFA",
193 			wid_gw,		wid_gw,		"Gateway",
194 			wid_flags,	wid_flags,	"Flags",
195 			wid_if,		wid_if,		"Netif",
196 			wid_prepend,			"Refcnt");
197 	}
198 }
199 
200 void
201 nhop_map_update(struct nhop_map *map, uint32_t idx, char *gw, char *ifname)
202 {
203 	if (idx >= map->size) {
204 		uint32_t new_size;
205 		size_t sz;
206 		if (map->size  == 0)
207 			new_size = 32;
208 		else
209 			new_size = map->size * 2;
210 		if (new_size <= idx)
211 			new_size = roundup2(idx + 1, 32);
212 
213 		sz = new_size * (sizeof(struct nhop_entry));
214 		if ((map->ptr = realloc(map->ptr, sz)) == NULL)
215 			xo_errx(EX_OSERR, "realloc(%zu) failed", sz);
216 
217 		memset(&map->ptr[map->size], 0, (new_size - map->size) * sizeof(struct nhop_entry));
218 		map->size = new_size;
219 	}
220 
221 	strlcpy(map->ptr[idx].ifname, ifname, sizeof(map->ptr[idx].ifname));
222 	strlcpy(map->ptr[idx].gw, gw, sizeof(map->ptr[idx].gw));
223 }
224 
225 static struct nhop_entry *
226 nhop_get(struct nhop_map *map, uint32_t idx)
227 {
228 
229 	if (idx >= map->size)
230 		return (NULL);
231 	if (*map->ptr[idx].ifname == '\0')
232 		return (NULL);
233 	return &map->ptr[idx];
234 }
235 
236 static void
237 print_nhop_entry_sysctl(const char *name, struct rt_msghdr *rtm, struct nhop_external *nh)
238 {
239 	char buffer[128];
240 	char iface_name[128];
241 	int protrusion;
242 	char gw_addr[64];
243 	struct nhop_addrs *na;
244 	struct sockaddr *sa_gw, *sa_ifa;
245 
246 	xo_open_instance(name);
247 
248 	snprintf(buffer, sizeof(buffer), "{[:-%d}{:index/%%lu}{]:} ", wid_nhidx);
249 	//xo_emit("{t:index/%-lu} ", wid_nhidx, nh->nh_idx);
250 	xo_emit(buffer, nh->nh_idx);
251 
252 	if (Wflag) {
253 		char *cp = nh_types[nh->nh_type];
254 		xo_emit("{t:type_str/%*s} ", wid_nhtype, cp);
255 	}
256 	memset(iface_name, 0, sizeof(iface_name));
257 	if (nh->ifindex < (uint32_t)ifmap_size) {
258 		strlcpy(iface_name, ifmap[nh->ifindex].ifname,
259 		    sizeof(iface_name));
260 		if (*iface_name == '\0')
261 			strlcpy(iface_name, "---", sizeof(iface_name));
262 	}
263 
264 	na = (struct nhop_addrs *)((char *)nh + nh->nh_len);
265 	//inet_ntop(nh->nh_family, &nh->nh_src, src_addr, sizeof(src_addr));
266 	//protrusion = p_addr("ifa", src_addr, wid_dst);
267 	sa_gw = (struct sockaddr *)((char *)na + na->gw_sa_off);
268 	sa_ifa = (struct sockaddr *)((char *)na + na->src_sa_off);
269 	protrusion = p_sockaddr("ifa", sa_ifa, NULL, RTF_HOST, wid_dst);
270 
271 	if (nh->nh_flags & NHF_GATEWAY) {
272 		const char *cp;
273 		cp = fmt_sockaddr(sa_gw, NULL, RTF_HOST);
274 		strlcpy(gw_addr, cp, sizeof(gw_addr));
275 	} else
276 		snprintf(gw_addr, sizeof(gw_addr), "%s/resolve", iface_name);
277 	protrusion = print_addr("gateway", gw_addr, wid_dst - protrusion);
278 
279 	nhop_map_update(&global_nhop_map, nh->nh_idx, gw_addr, iface_name);
280 
281 	snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
282 	    wid_flags - protrusion);
283 
284 	//p_nhflags(nh->nh_flags, buffer);
285 	print_flags_generic(rtm->rtm_flags, rt_bits, buffer, "rt_flags_pretty");
286 
287 	if (Wflag) {
288 		xo_emit("{t:use/%*lu} ", wid_pksent, nh->nh_pksent);
289 		xo_emit("{t:mtu/%*lu} ", wid_mtu, nh->nh_mtu);
290 	}
291 	//printf("IDX: %d IFACE: %s FAMILY: %d TYPE: %d FLAGS: %X GW \n");
292 
293 	if (Wflag)
294 		xo_emit("{t:interface-name/%*s}", wid_if, iface_name);
295 	else
296 		xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if, iface_name);
297 
298 	memset(iface_name, 0, sizeof(iface_name));
299 	if (nh->aifindex < (uint32_t)ifmap_size && nh->ifindex != nh->aifindex) {
300 		strlcpy(iface_name, ifmap[nh->aifindex].ifname,
301 		    sizeof(iface_name));
302 		if (*iface_name == '\0')
303 			strlcpy(iface_name, "---", sizeof(iface_name));
304 	}
305 	if (Wflag)
306 		xo_emit("{t:address-interface-name/%*s}", wid_if, iface_name);
307 
308 	xo_emit("{t:refcount/%*lu} ", wid_refcnt, nh->nh_refcount);
309 	if (Wflag && nh->prepend_len) {
310 		int max_bytes = MIN(nh->prepend_len, sizeof(buffer) / 2 - 1);
311 		for (int i = 0; i < max_bytes; i++)
312 			snprintf(&buffer[i * 2], 3, "%02X", nh->nh_prepend[i]);
313 		xo_emit(" {:nhop-prepend/%*s}", wid_prepend, buffer);
314 	}
315 
316 	xo_emit("\n");
317 	xo_close_instance(name);
318 }
319 
320 static int
321 cmp_nh_idx(const void *_a, const void *_b)
322 {
323 	const struct nhops_map *a, *b;
324 
325 	a = _a;
326 	b = _b;
327 
328 	if (a->idx > b->idx)
329 		return (1);
330 	else if (a->idx < b->idx)
331 		return (-1);
332 	return (0);
333 }
334 
335 void
336 dump_nhops_sysctl(int fibnum, int af, struct nhops_dump *nd)
337 {
338 	size_t needed;
339 	int mib[7];
340 	char *buf, *next, *lim;
341 	struct rt_msghdr *rtm;
342 	struct nhop_external *nh;
343 	struct nhops_map *nh_map;
344 	size_t nh_count, nh_size;
345 
346 	mib[0] = CTL_NET;
347 	mib[1] = PF_ROUTE;
348 	mib[2] = 0;
349 	mib[3] = af;
350 	mib[4] = NET_RT_NHOP;
351 	mib[5] = 0;
352 	mib[6] = fibnum;
353 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
354 		xo_err(EX_OSERR, "sysctl: net.route.0.%d.nhdump.%d estimate", af,
355 		    fibnum);
356 	if ((buf = malloc(needed)) == NULL)
357 		xo_errx(EX_OSERR, "malloc(%lu)", (unsigned long)needed);
358 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
359 		xo_err(EX_OSERR, "sysctl: net.route.0.%d.nhdump.%d", af, fibnum);
360 	lim  = buf + needed;
361 
362 	/*
363 	 * nexhops are received unsorted. Collect everything first, sort and then display
364 	 * sorted.
365 	 */
366 	nh_count = 0;
367 	nh_size = 16;
368 	nh_map = calloc(nh_size, sizeof(struct nhops_map));
369 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
370 		rtm = (struct rt_msghdr *)next;
371 		if (rtm->rtm_version != RTM_VERSION)
372 			continue;
373 
374 		if (nh_count >= nh_size) {
375 			nh_size *= 2;
376 			nh_map = realloc(nh_map, nh_size * sizeof(struct nhops_map));
377 		}
378 
379 		nh = (struct nhop_external *)(rtm + 1);
380 		nh_map[nh_count].idx = nh->nh_idx;
381 		nh_map[nh_count].rtm = rtm;
382 		nh_count++;
383 	}
384 
385 	if (nh_count > 0)
386 		qsort(nh_map, nh_count, sizeof(struct nhops_map), cmp_nh_idx);
387 	nd->nh_buf = buf;
388 	nd->nh_count = nh_count;
389 	nd->nh_map = nh_map;
390 }
391 
392 static void
393 print_nhops_sysctl(int fibnum, int af)
394 {
395 	struct nhops_dump nd;
396 	struct nhop_external *nh;
397 	int fam;
398 	struct rt_msghdr *rtm;
399 
400 	dump_nhops_sysctl(fibnum, af, &nd);
401 
402 	xo_open_container("nhop-table");
403 	xo_open_list("rt-family");
404 	if (nd.nh_count > 0) {
405 		nh = (struct nhop_external *)(nd.nh_map[0].rtm + 1);
406 		fam = nh->nh_family;
407 
408 		wid_dst = WID_GW_DEFAULT(fam);
409 		wid_gw = WID_GW_DEFAULT(fam);
410 		wid_nhidx = 5;
411 		wid_nhtype = 12;
412 		wid_refcnt = 6;
413 		wid_flags = 6;
414 		wid_pksent = 8;
415 		wid_mtu = 6;
416 		wid_if = WID_IF_DEFAULT;
417 		xo_open_instance("rt-family");
418 		pr_family(fam);
419 		xo_open_list("nh-entry");
420 
421 		print_nhop_header(fam);
422 
423 		for (size_t i = 0; i < nd.nh_count; i++) {
424 			rtm = nd.nh_map[i].rtm;
425 			nh = (struct nhop_external *)(rtm + 1);
426 			print_nhop_entry_sysctl("nh-entry", rtm, nh);
427 		}
428 
429 		xo_close_list("nh-entry");
430 		xo_close_instance("rt-family");
431 	}
432 	xo_close_list("rt-family");
433 	xo_close_container("nhop-table");
434 	free(nd.nh_buf);
435 }
436 
437 static void
438 p_nhflags(int f, const char *format)
439 {
440 	struct bits *p;
441 	char *pretty_name = "nh_flags_pretty";
442 
443 	xo_emit(format, fmt_flags(nh_bits, f));
444 
445 	xo_open_list(pretty_name);
446 	for (p = nh_bits; p->b_mask; p++)
447 		if (p->b_mask & f)
448 			xo_emit("{le:nh_flags_pretty/%s}", p->b_name);
449 	xo_close_list(pretty_name);
450 }
451 
452 void
453 nhops_print(int fibnum, int af)
454 {
455 	size_t intsize;
456 	int numfibs;
457 
458 	intsize = sizeof(int);
459 	if (fibnum == -1 &&
460 	    sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
461 		fibnum = 0;
462 	if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
463 		numfibs = 1;
464 	if (fibnum < 0 || fibnum > numfibs - 1)
465 		xo_errx(EX_USAGE, "%d: invalid fib", fibnum);
466 
467 	ifmap = prepare_ifmap(&ifmap_size);
468 
469 	xo_open_container("route-nhop-information");
470 	xo_emit("{T:Nexthop data}");
471 	if (fibnum)
472 		xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
473 	xo_emit("\n");
474 	print_nhops_sysctl(fibnum, af);
475 	xo_close_container("route-nhop-information");
476 }
477 
478