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