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