xref: /f-stack/tools/netstat/nhops.c (revision d4a07e70)
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 #ifndef FSTACK
122 static struct nhop_entry *nhop_get(struct nhop_map *map, uint32_t idx);
123 #endif
124 
125 static struct ifmap_entry *ifmap;
126 static size_t ifmap_size;
127 
128 #ifndef FSTACK
129 static void
130 print_sockaddr_buf(char *buf, size_t bufsize, const struct sockaddr *sa)
131 {
132 
133 	switch (sa->sa_family) {
134 	case AF_INET:
135 		inet_ntop(AF_INET, &((struct sockaddr_in *)sa)->sin_addr,
136 		    buf, bufsize);
137 		break;
138 	case AF_INET6:
139 		inet_ntop(AF_INET6, &((struct sockaddr_in6 *)sa)->sin6_addr,
140 		    buf, bufsize);
141 		break;
142 	default:
143 		snprintf(buf, bufsize, "unknown:%d", sa->sa_family);
144 		break;
145 	}
146 }
147 #endif
148 
149 static int
150 print_addr(const char *name, const char *addr, int width)
151 {
152 	char buf[128];
153 	int protrusion;
154 
155 	if (width < 0) {
156 		snprintf(buf, sizeof(buf), "{:%s/%%s} ", name);
157 		xo_emit(buf, addr);
158 		protrusion = 0;
159 	} else {
160 		if (Wflag != 0 || numeric_addr) {
161 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%s}{]:} ",
162 			    -width, name);
163 			xo_emit(buf, addr);
164 			protrusion = strlen(addr) - width;
165 			if (protrusion < 0)
166 				protrusion = 0;
167 		} else {
168 			snprintf(buf, sizeof(buf), "{[:%d}{:%s/%%-.*s}{]:} ",
169 			    -width, name);
170 			xo_emit(buf, width, addr);
171 			protrusion = 0;
172 		}
173 	}
174 	return (protrusion);
175 }
176 
177 
178 static void
179 print_nhop_header(int af1 __unused)
180 {
181 
182 	if (Wflag) {
183 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
184 		    "{T:/%*.*s} {T:/%-*.*s} {T:/%*.*s} {T:/%*.*s} {T:/%*.*s} {T:/%*s}\n",
185 			wid_nhidx,	wid_nhidx,	"Idx",
186 			wid_nhtype,	wid_nhtype,	"Type",
187 			wid_dst,	wid_dst,	"IFA",
188 			wid_gw,		wid_gw,		"Gateway",
189 			wid_flags,	wid_flags,	"Flags",
190 			wid_pksent,	wid_pksent,	"Use",
191 			wid_mtu,	wid_mtu,	"Mtu",
192 			wid_if,		wid_if,		"Netif",
193 			wid_if,		wid_if,		"Addrif",
194 			wid_refcnt,	wid_refcnt,	"Refcnt",
195 			wid_prepend,			"Prepend");
196 	} else {
197 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s} {T:/%*.*s} "
198 		    " {T:/%*s}\n",
199 			wid_nhidx,	wid_nhidx,	"Idx",
200 			wid_dst,	wid_dst,	"IFA",
201 			wid_gw,		wid_gw,		"Gateway",
202 			wid_flags,	wid_flags,	"Flags",
203 			wid_if,		wid_if,		"Netif",
204 			wid_prepend,			"Refcnt");
205 	}
206 }
207 
208 void
209 nhop_map_update(struct nhop_map *map, uint32_t idx, char *gw, char *ifname)
210 {
211 	if (idx >= map->size) {
212 		uint32_t new_size;
213 		size_t sz;
214 		if (map->size  == 0)
215 			new_size = 32;
216 		else
217 			new_size = map->size * 2;
218 		if (new_size <= idx)
219 			new_size = roundup(idx + 1, 32);
220 
221 		sz = new_size * (sizeof(struct nhop_entry));
222 		if ((map->ptr = realloc(map->ptr, sz)) == NULL)
223 			errx(2, "realloc(%zu) failed", sz);
224 
225 		memset(&map->ptr[map->size], 0, (new_size - map->size) * sizeof(struct nhop_entry));
226 		map->size = new_size;
227 	}
228 
229 	strlcpy(map->ptr[idx].ifname, ifname, sizeof(map->ptr[idx].ifname));
230 	strlcpy(map->ptr[idx].gw, gw, sizeof(map->ptr[idx].gw));
231 }
232 
233 #ifndef FSTACK
234 static struct nhop_entry *
235 nhop_get(struct nhop_map *map, uint32_t idx)
236 {
237 
238 	if (idx >= map->size)
239 		return (NULL);
240 	if (*map->ptr[idx].ifname == '\0')
241 		return (NULL);
242 	return &map->ptr[idx];
243 }
244 #endif
245 
246 static void
247 print_nhop_entry_sysctl(const char *name, struct rt_msghdr *rtm, struct nhop_external *nh)
248 {
249 	char buffer[128];
250 	char iface_name[128];
251 	int protrusion;
252 	char gw_addr[64];
253 	struct nhop_addrs *na;
254 	struct sockaddr *sa_gw, *sa_ifa;
255 
256 	xo_open_instance(name);
257 
258 	snprintf(buffer, sizeof(buffer), "{[:-%d}{:index/%%lu}{]:} ", wid_nhidx);
259 	//xo_emit("{t:index/%-lu} ", wid_nhidx, nh->nh_idx);
260 	xo_emit(buffer, nh->nh_idx);
261 
262 	if (Wflag) {
263 		char *cp = nh_types[nh->nh_type];
264 		xo_emit("{t:type_str/%*s} ", wid_nhtype, cp);
265 	}
266 	memset(iface_name, 0, sizeof(iface_name));
267 	if (nh->ifindex < (uint32_t)ifmap_size) {
268 		strlcpy(iface_name, ifmap[nh->ifindex].ifname,
269 		    sizeof(iface_name));
270 		if (*iface_name == '\0')
271 			strlcpy(iface_name, "---", sizeof(iface_name));
272 	}
273 
274 	na = (struct nhop_addrs *)((char *)nh + nh->nh_len);
275 	//inet_ntop(nh->nh_family, &nh->nh_src, src_addr, sizeof(src_addr));
276 	//protrusion = p_addr("ifa", src_addr, wid_dst);
277 	sa_gw = (struct sockaddr *)((char *)na + na->gw_sa_off);
278 	sa_ifa = (struct sockaddr *)((char *)na + na->src_sa_off);
279 	protrusion = p_sockaddr("ifa", sa_ifa, NULL, RTF_HOST, wid_dst);
280 
281 	if (nh->nh_flags & NHF_GATEWAY) {
282 		const char *cp;
283 		cp = fmt_sockaddr(sa_gw, NULL, RTF_HOST);
284 		strlcpy(gw_addr, cp, sizeof(gw_addr));
285 	} else
286 		snprintf(gw_addr, sizeof(gw_addr), "%s/resolve", iface_name);
287 	protrusion = print_addr("gateway", gw_addr, wid_dst - protrusion);
288 
289 	nhop_map_update(&global_nhop_map, nh->nh_idx, gw_addr, iface_name);
290 
291 	snprintf(buffer, sizeof(buffer), "{[:-%d}{:flags/%%s}{]:} ",
292 	    wid_flags - protrusion);
293 
294 	//p_nhflags(nh->nh_flags, buffer);
295 	print_flags_generic(rtm->rtm_flags, rt_bits, buffer, "rt_flags_pretty");
296 
297 	if (Wflag) {
298 		xo_emit("{t:use/%*lu} ", wid_pksent, nh->nh_pksent);
299 		xo_emit("{t:mtu/%*lu} ", wid_mtu, nh->nh_mtu);
300 	}
301 	//printf("IDX: %d IFACE: %s FAMILY: %d TYPE: %d FLAGS: %X GW \n");
302 
303 	if (Wflag)
304 		xo_emit("{t:interface-name/%*s}", wid_if, iface_name);
305 	else
306 		xo_emit("{t:interface-name/%*.*s}", wid_if, wid_if, iface_name);
307 
308 	memset(iface_name, 0, sizeof(iface_name));
309 	if (nh->aifindex < (uint32_t)ifmap_size && nh->ifindex != nh->aifindex) {
310 		strlcpy(iface_name, ifmap[nh->aifindex].ifname,
311 		    sizeof(iface_name));
312 		if (*iface_name == '\0')
313 			strlcpy(iface_name, "---", sizeof(iface_name));
314 	}
315 	if (Wflag)
316 		xo_emit("{t:address-interface-name/%*s}", wid_if, iface_name);
317 
318 	xo_emit("{t:refcount/%*lu} ", wid_refcnt, nh->nh_refcount);
319 	if (Wflag && nh->prepend_len) {
320 		char *prepend_hex = "AABBCCDDEE";
321 		xo_emit(" {:nhop-prepend/%*s}", wid_prepend, prepend_hex);
322 	}
323 
324 	xo_emit("\n");
325 	xo_close_instance(name);
326 }
327 
328 static int
329 cmp_nh_idx(const void *_a, const void *_b)
330 {
331 	const struct nhops_map *a, *b;
332 
333 	a = _a;
334 	b = _b;
335 
336 	if (a->idx > b->idx)
337 		return (1);
338 	else if (a->idx < b->idx)
339 		return (-1);
340 	return (0);
341 }
342 
343 void
344 dump_nhops_sysctl(int fibnum, int af, struct nhops_dump *nd)
345 {
346 	size_t needed;
347 	int mib[7];
348 	char *buf, *next, *lim;
349 	struct rt_msghdr *rtm;
350 	struct nhop_external *nh;
351 	struct nhops_map *nh_map;
352 	size_t nh_count, nh_size;
353 
354 	mib[0] = CTL_NET;
355 	mib[1] = PF_ROUTE;
356 	mib[2] = 0;
357 	mib[3] = af;
358 	mib[4] = NET_RT_NHOP;
359 	mib[5] = 0;
360 	mib[6] = fibnum;
361 	if (sysctl(mib, nitems(mib), NULL, &needed, NULL, 0) < 0)
362 		err(EX_OSERR, "sysctl: net.route.0.%d.nhdump.%d estimate", af,
363 		    fibnum);
364 	if ((buf = malloc(needed)) == NULL)
365 		errx(2, "malloc(%lu)", (unsigned long)needed);
366 	if (sysctl(mib, nitems(mib), buf, &needed, NULL, 0) < 0)
367 		err(1, "sysctl: net.route.0.%d.nhdump.%d", af, fibnum);
368 	lim  = buf + needed;
369 
370 	/*
371 	 * nexhops are received unsorted. Collect everything first, sort and then display
372 	 * sorted.
373 	 */
374 	nh_count = 0;
375 	nh_size = 16;
376 	nh_map = calloc(nh_size, sizeof(struct nhops_map));
377 	for (next = buf; next < lim; next += rtm->rtm_msglen) {
378 		rtm = (struct rt_msghdr *)next;
379 		if (rtm->rtm_version != RTM_VERSION)
380 			continue;
381 
382 		if (nh_count >= nh_size) {
383 			nh_size *= 2;
384 			nh_map = realloc(nh_map, nh_size * sizeof(struct nhops_map));
385 		}
386 
387 		nh = (struct nhop_external *)(rtm + 1);
388 		nh_map[nh_count].idx = nh->nh_idx;
389 		nh_map[nh_count].rtm = rtm;
390 		nh_count++;
391 	}
392 
393 	if (nh_count > 0)
394 		qsort(nh_map, nh_count, sizeof(struct nhops_map), cmp_nh_idx);
395 	nd->nh_buf = buf;
396 	nd->nh_count = nh_count;
397 	nd->nh_map = nh_map;
398 }
399 
400 static void
401 print_nhops_sysctl(int fibnum, int af)
402 {
403 	struct nhops_dump nd;
404 	struct nhop_external *nh;
405 	int fam;
406 	struct rt_msghdr *rtm;
407 
408 	dump_nhops_sysctl(fibnum, af, &nd);
409 
410 	xo_open_container("nhop-table");
411 	xo_open_list("rt-family");
412 	if (nd.nh_count > 0) {
413 		nh = (struct nhop_external *)(nd.nh_map[0].rtm + 1);
414 		fam = nh->nh_family;
415 
416 		wid_dst = WID_GW_DEFAULT(fam);
417 		wid_gw = WID_GW_DEFAULT(fam);
418 		wid_nhidx = 5;
419 		wid_nhtype = 12;
420 		wid_refcnt = 6;
421 		wid_flags = 6;
422 		wid_pksent = 8;
423 		wid_mtu = 6;
424 		wid_if = WID_IF_DEFAULT(fam);
425 		xo_open_instance("rt-family");
426 		pr_family(fam);
427 		xo_open_list("nh-entry");
428 
429 		print_nhop_header(fam);
430 
431 		for (size_t i = 0; i < nd.nh_count; i++) {
432 			rtm = nd.nh_map[i].rtm;
433 			nh = (struct nhop_external *)(rtm + 1);
434 			print_nhop_entry_sysctl("nh-entry", rtm, nh);
435 		}
436 
437 		xo_close_list("nh-entry");
438 		xo_close_instance("rt-family");
439 	}
440 	xo_close_list("rt-family");
441 	xo_close_container("nhop-table");
442 	free(nd.nh_buf);
443 }
444 
445 #ifndef FSTACK
446 static void
447 p_nhflags(int f, const char *format)
448 {
449 	struct bits *p;
450 	char *pretty_name = "nh_flags_pretty";
451 
452 	xo_emit(format, fmt_flags(nh_bits, f));
453 
454 	xo_open_list(pretty_name);
455 	for (p = nh_bits; p->b_mask; p++)
456 		if (p->b_mask & f)
457 			xo_emit("{le:nh_flags_pretty/%s}", p->b_name);
458 	xo_close_list(pretty_name);
459 }
460 #endif
461 
462 void
463 nhops_print(int fibnum, int af)
464 {
465 	size_t intsize;
466 	int numfibs;
467 
468 	intsize = sizeof(int);
469 	if (fibnum == -1 &&
470 	    sysctlbyname("net.my_fibnum", &fibnum, &intsize, NULL, 0) == -1)
471 		fibnum = 0;
472 	if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
473 		numfibs = 1;
474 	if (fibnum < 0 || fibnum > numfibs - 1)
475 		errx(EX_USAGE, "%d: invalid fib", fibnum);
476 
477 	ifmap = prepare_ifmap(&ifmap_size);
478 
479 	xo_open_container("route-nhop-information");
480 	xo_emit("{T:Nexthop data}");
481 	if (fibnum)
482 		xo_emit(" ({L:fib}: {:fib/%d})", fibnum);
483 	xo_emit("\n");
484 	print_nhops_sysctl(fibnum, af);
485 	xo_close_container("route-nhop-information");
486 }
487 
488