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