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