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