xref: /f-stack/tools/ndp/ndp.c (revision d4a07e70)
1 /*	$FreeBSD$	*/
2 /*	$KAME: ndp.c,v 1.104 2003/06/27 07:48:39 itojun Exp $	*/
3 
4 /*-
5  * SPDX-License-Identifier: BSD-3-Clause
6  *
7  * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the project nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 /*
35  * Copyright (c) 1984, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * This code is derived from software contributed to Berkeley by
39  * Sun Microsystems, Inc.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  */
65 
66 /*
67  * Based on:
68  * "@(#) Copyright (c) 1984, 1993\n\
69  *	The Regents of the University of California.  All rights reserved.\n";
70  *
71  * "@(#)arp.c	8.2 (Berkeley) 1/2/94";
72  */
73 
74 /*
75  * ndp - display, set, delete and flush neighbor cache
76  */
77 
78 
79 #include <sys/param.h>
80 #include <sys/file.h>
81 #include <sys/ioctl.h>
82 #include <sys/socket.h>
83 #include <sys/sysctl.h>
84 #include <sys/time.h>
85 #include <sys/queue.h>
86 
87 #include <net/if.h>
88 #include <net/if_dl.h>
89 #include <net/if_types.h>
90 #include <net/route.h>
91 
92 #include <netinet/in.h>
93 #include <netinet/if_ether.h>
94 
95 #include <netinet/icmp6.h>
96 #include <netinet6/in6_var.h>
97 #include <netinet6/nd6.h>
98 
99 #include <arpa/inet.h>
100 
101 #include <ctype.h>
102 #include <netdb.h>
103 #include <errno.h>
104 #include <nlist.h>
105 #include <stdio.h>
106 #include <string.h>
107 #include <paths.h>
108 #include <err.h>
109 #include <stdlib.h>
110 #include <fcntl.h>
111 #include <unistd.h>
112 #ifndef FSTACK
113 #include "gmt2local.h"
114 #else
115 #include <time.h>
116 
117 #include "rtioctl.h"
118 #include "ff_ipc.h"
119 #include "ff_api.h"
120 
121 #ifndef __unused
122 #define __unused __attribute__((__unused__))
123 
124 #define socket(a, b, c) rt_socket((a), (b), (c))
125 #define close(a) rt_close(a)
126 
127 #endif
128 
129 int32_t gmt2local(time_t);
130 /*#define SA_SIZE_NDP(sa)						\
131 	(  (((struct sockaddr *)(sa))->sa_len == 0) ?   \
132 	sizeof(long)        :               \
133 	1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(long) - 1) ) )
134 */
135 #ifndef	ALIGNBYTES
136 /*
137  * On systems with a routing socket, ALIGNBYTES should match the value
138  * that the kernel uses when building the messages.
139  */
140 #define	ALIGNBYTES	(sizeof(long long) - 1)
141 #endif
142 #ifndef	ALIGN
143 #define	ALIGN(p)	(((u_long)(p) + ALIGNBYTES) &~ ALIGNBYTES)
144 #endif
145 
146 #endif
147 
148 #define	NEXTADDR(w, s)					\
149 	if (rtm->rtm_addrs & (w)) {			\
150 		bcopy((char *)&s, cp, sizeof(s));	\
151 		cp += SA_SIZE(&s);			\
152 	}
153 
154 static pid_t pid;
155 static int nflag;
156 static int tflag;
157 static int32_t thiszone;	/* time difference with gmt */
158 static int s = -1;
159 static int repeat = 0;
160 
161 static char host_buf[NI_MAXHOST];	/* getnameinfo() */
162 static char ifix_buf[IFNAMSIZ];		/* if_indextoname() */
163 
164 static int file(char *);
165 static void getsocket(void);
166 static int set(int, char **);
167 static void get(char *);
168 static int delete(char *);
169 static void dump(struct sockaddr_in6 *, int);
170 static struct in6_nbrinfo *getnbrinfo(struct in6_addr *, int, int);
171 static char *ether_str(struct sockaddr_dl *);
172 static int ndp_ether_aton(char *, u_char *);
173 static void usage(void);
174 static int rtmsg(int);
175 static void ifinfo(char *, int, char **);
176 static void rtrlist(void);
177 static void plist(void);
178 static void pfx_flush(void);
179 static void rtr_flush(void);
180 static void harmonize_rtr(void);
181 #ifdef SIOCSDEFIFACE_IN6	/* XXX: check SIOCGDEFIFACE_IN6 as well? */
182 static void getdefif(void);
183 static void setdefif(char *);
184 #endif
185 static char *sec2str(time_t);
186 static void ts_print(const struct timeval *);
187 
188 static const char *rtpref_str[] = {
189 	"medium",		/* 00 */
190 	"high",			/* 01 */
191 	"rsv",			/* 10 */
192 	"low"			/* 11 */
193 };
194 
195 #ifdef FSTACK
196 int32_t
gmt2local(time_t t)197 gmt2local(time_t t)
198 {
199 	register int dt, dir;
200 	register struct tm *gmt, *loc;
201 	struct tm sgmt;
202 
203 	if (t == 0)
204 		t = time(NULL);
205 	gmt = &sgmt;
206 	*gmt = *gmtime(&t);
207 	loc = localtime(&t);
208 	dt = (loc->tm_hour - gmt->tm_hour) * 60 * 60 +
209 		(loc->tm_min - gmt->tm_min) * 60;
210 
211 	/*
212 	 * If the year or julian day is different, we span 00:00 GMT
213 	 * and must add or subtract a day. Check the year first to
214 	 * avoid problems when the julian day wraps.
215 	 */
216 	dir = loc->tm_year - gmt->tm_year;
217 	if (dir == 0)
218 		dir = loc->tm_yday - gmt->tm_yday;
219 	dt += dir * 24 * 60 * 60;
220 
221 	return (dt);
222 }
223 #endif
224 
225 int
main(int argc,char ** argv)226 main(int argc, char **argv)
227 {
228 	int ch, mode = 0;
229 	char *arg = NULL;
230 
231 	pid = getpid();
232 	thiszone = gmt2local(0);
233 #ifndef FSTACK
234 	while ((ch = getopt(argc, argv, "acd:f:Ii:nprstA:HPR")) != -1)
235 #else
236 	ff_ipc_init();
237 	while ((ch = getopt(argc, argv, "acd:f:Ii:nprstA:HPRC:")) != -1)
238 #endif
239 		switch (ch) {
240 		case 'a':
241 		case 'c':
242 		case 'p':
243 		case 'r':
244 		case 'H':
245 		case 'P':
246 		case 'R':
247 		case 's':
248 		case 'I':
249 			if (mode) {
250 				usage();
251 				/*NOTREACHED*/
252 			}
253 			mode = ch;
254 			arg = NULL;
255 			break;
256 		case 'f':
257 			exit(file(optarg) ? 1 : 0);
258 		case 'd':
259 		case 'i':
260 			if (mode) {
261 				usage();
262 				/*NOTREACHED*/
263 			}
264 			mode = ch;
265 			arg = optarg;
266 			break;
267 		case 'n':
268 			nflag = 1;
269 			break;
270 		case 't':
271 			tflag = 1;
272 			break;
273 		case 'A':
274 			if (mode) {
275 				usage();
276 				/*NOTREACHED*/
277 			}
278 			mode = 'a';
279 			repeat = atoi(optarg);
280 			if (repeat < 0) {
281 				usage();
282 				/*NOTREACHED*/
283 			}
284 			break;
285 #ifdef FSTACK
286 		case 'C':
287 			ff_set_proc_id(atoi(optarg));
288 			break;
289 #endif
290 		default:
291 			usage();
292 		}
293 
294 	argc -= optind;
295 	argv += optind;
296 
297 	switch (mode) {
298 	case 'a':
299 	case 'c':
300 		if (argc != 0) {
301 			usage();
302 			/*NOTREACHED*/
303 		}
304 		dump(0, mode == 'c');
305 		break;
306 	case 'd':
307 		if (argc != 0) {
308 			usage();
309 			/*NOTREACHED*/
310 		}
311 		delete(arg);
312 		break;
313 	case 'I':
314 #ifdef SIOCSDEFIFACE_IN6	/* XXX: check SIOCGDEFIFACE_IN6 as well? */
315 		if (argc > 1) {
316 			usage();
317 			/*NOTREACHED*/
318 		} else if (argc == 1) {
319 			if (strcmp(*argv, "delete") == 0 ||
320 			    if_nametoindex(*argv))
321 				setdefif(*argv);
322 			else
323 				errx(1, "invalid interface %s", *argv);
324 		}
325 		getdefif(); /* always call it to print the result */
326 		break;
327 #else
328 		errx(1, "not supported yet");
329 		/*NOTREACHED*/
330 #endif
331 	case 'p':
332 		if (argc != 0) {
333 			usage();
334 			/*NOTREACHED*/
335 		}
336 		plist();
337 		break;
338 	case 'i':
339 		ifinfo(arg, argc, argv);
340 		break;
341 	case 'r':
342 		if (argc != 0) {
343 			usage();
344 			/*NOTREACHED*/
345 		}
346 		rtrlist();
347 		break;
348 	case 's':
349 		if (argc < 2 || argc > 4)
350 			usage();
351 		exit(set(argc, argv) ? 1 : 0);
352 	case 'H':
353 		if (argc != 0) {
354 			usage();
355 			/*NOTREACHED*/
356 		}
357 		harmonize_rtr();
358 		break;
359 	case 'P':
360 		if (argc != 0) {
361 			usage();
362 			/*NOTREACHED*/
363 		}
364 		pfx_flush();
365 		break;
366 	case 'R':
367 		if (argc != 0) {
368 			usage();
369 			/*NOTREACHED*/
370 		}
371 		rtr_flush();
372 		break;
373 	case 0:
374 		if (argc != 1) {
375 			usage();
376 			/*NOTREACHED*/
377 		}
378 		get(argv[0]);
379 		break;
380 	}
381 	exit(0);
382 }
383 
384 /*
385  * Process a file to set standard ndp entries
386  */
387 static int
file(char * name)388 file(char *name)
389 {
390 	FILE *fp;
391 	int i, retval;
392 	char line[100], arg[5][50], *args[5], *p;
393 
394 	if ((fp = fopen(name, "r")) == NULL)
395 		err(1, "cannot open %s", name);
396 	args[0] = &arg[0][0];
397 	args[1] = &arg[1][0];
398 	args[2] = &arg[2][0];
399 	args[3] = &arg[3][0];
400 	args[4] = &arg[4][0];
401 	retval = 0;
402 	while (fgets(line, sizeof(line), fp) != NULL) {
403 		if ((p = strchr(line, '#')) != NULL)
404 			*p = '\0';
405 		for (p = line; isblank(*p); p++);
406 		if (*p == '\n' || *p == '\0')
407 			continue;
408 		i = sscanf(line, "%49s %49s %49s %49s %49s",
409 		    arg[0], arg[1], arg[2], arg[3], arg[4]);
410 		if (i < 2) {
411 			warnx("bad line: %s", line);
412 			retval = 1;
413 			continue;
414 		}
415 		if (set(i, args))
416 			retval = 1;
417 	}
418 	fclose(fp);
419 	return (retval);
420 }
421 
422 static void
getsocket()423 getsocket()
424 {
425 	if (s < 0) {
426 		s = socket(PF_ROUTE, SOCK_RAW, 0);
427 		if (s < 0) {
428 			err(1, "socket");
429 			/* NOTREACHED */
430 		}
431 	}
432 }
433 
434 static struct sockaddr_in6 so_mask = {
435 	.sin6_len = sizeof(so_mask),
436 	.sin6_family = AF_INET6
437 };
438 static struct sockaddr_in6 blank_sin = {
439 	.sin6_len = sizeof(blank_sin),
440 	.sin6_family = AF_INET6
441 };
442 static struct sockaddr_in6 sin_m;
443 static struct sockaddr_dl blank_sdl = {
444 	.sdl_len = sizeof(blank_sdl),
445 	.sdl_family = AF_LINK
446 };
447 static struct sockaddr_dl sdl_m;
448 static time_t expire_time;
449 static int flags, found_entry;
450 static struct {
451 	struct	rt_msghdr m_rtm;
452 	char	m_space[512];
453 } m_rtmsg;
454 
455 /*
456  * Set an individual neighbor cache entry
457  */
458 static int
set(int argc,char ** argv)459 set(int argc, char **argv)
460 {
461 	register struct sockaddr_in6 *sin = &sin_m;
462 	register struct sockaddr_dl *sdl;
463 	register struct rt_msghdr *rtm = &(m_rtmsg.m_rtm);
464 	struct addrinfo hints, *res;
465 	int gai_error;
466 	u_char *ea;
467 	char *host = argv[0], *eaddr = argv[1];
468 
469 	getsocket();
470 	argc -= 2;
471 	argv += 2;
472 	sdl_m = blank_sdl;
473 	sin_m = blank_sin;
474 
475 	bzero(&hints, sizeof(hints));
476 	hints.ai_family = AF_INET6;
477 	gai_error = getaddrinfo(host, NULL, &hints, &res);
478 	if (gai_error) {
479 		fprintf(stderr, "ndp: %s: %s\n", host,
480 			gai_strerror(gai_error));
481 		return 1;
482 	}
483 	sin->sin6_addr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
484 	sin->sin6_scope_id =
485 	    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
486 	ea = (u_char *)LLADDR(&sdl_m);
487 	if (ndp_ether_aton(eaddr, ea) == 0)
488 		sdl_m.sdl_alen = 6;
489 	flags = expire_time = 0;
490 	while (argc-- > 0) {
491 		if (strncmp(argv[0], "temp", 4) == 0) {
492 			struct timeval now;
493 
494 			gettimeofday(&now, 0);
495 			expire_time = now.tv_sec + 20 * 60;
496 		} else if (strncmp(argv[0], "proxy", 5) == 0)
497 			flags |= RTF_ANNOUNCE;
498 		argv++;
499 	}
500 	if (rtmsg(RTM_GET) < 0) {
501 		errx(1, "RTM_GET(%s) failed", host);
502 		/* NOTREACHED */
503 	}
504 	sin = (struct sockaddr_in6 *)(rtm + 1);
505 	sdl = (struct sockaddr_dl *)(ALIGN(sin->sin6_len) + (char *)sin);
506 	if (IN6_ARE_ADDR_EQUAL(&sin->sin6_addr, &sin_m.sin6_addr)) {
507 		if (sdl->sdl_family == AF_LINK &&
508 		    !(rtm->rtm_flags & RTF_GATEWAY)) {
509 			switch (sdl->sdl_type) {
510 			case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023:
511 			case IFT_ISO88024: case IFT_ISO88025:
512 			case IFT_L2VLAN: case IFT_BRIDGE:
513 				goto overwrite;
514 			}
515 		}
516 		fprintf(stderr, "set: cannot configure a new entry\n");
517 		return 1;
518 	}
519 
520 overwrite:
521 	if (sdl->sdl_family != AF_LINK) {
522 		printf("cannot intuit interface index and type for %s\n", host);
523 		return (1);
524 	}
525 	sdl_m.sdl_type = sdl->sdl_type;
526 	sdl_m.sdl_index = sdl->sdl_index;
527 	return (rtmsg(RTM_ADD));
528 }
529 
530 /*
531  * Display an individual neighbor cache entry
532  */
533 static void
get(char * host)534 get(char *host)
535 {
536 	struct sockaddr_in6 *sin = &sin_m;
537 	struct addrinfo hints, *res;
538 	int gai_error;
539 
540 	sin_m = blank_sin;
541 	bzero(&hints, sizeof(hints));
542 	hints.ai_family = AF_INET6;
543 	gai_error = getaddrinfo(host, NULL, &hints, &res);
544 	if (gai_error) {
545 		fprintf(stderr, "ndp: %s: %s\n", host,
546 		    gai_strerror(gai_error));
547 		return;
548 	}
549 	sin->sin6_addr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
550 	sin->sin6_scope_id =
551 	    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
552 	dump(sin, 0);
553 	if (found_entry == 0) {
554 #ifndef FSTACK
555 		getnameinfo((struct sockaddr *)sin, sin->sin6_len, host_buf,
556 		    sizeof(host_buf), NULL ,0,
557 		    (nflag ? NI_NUMERICHOST : 0));
558 #else
559 		inet_ntop(AF_INET6_LINUX, &sin->sin6_addr, host_buf, sizeof(host_buf));
560 #endif
561 		printf("%s (%s) -- no entry\n", host, host_buf);
562 		exit(1);
563 	}
564 }
565 
566 /*
567  * Delete a neighbor cache entry
568  */
569 static int
delete(char * host)570 delete(char *host)
571 {
572 	struct sockaddr_in6 *sin = &sin_m;
573 	register struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
574 	register char *cp = m_rtmsg.m_space;
575 	struct sockaddr_dl *sdl;
576 	struct addrinfo hints, *res;
577 	int gai_error;
578 
579 	getsocket();
580 	sin_m = blank_sin;
581 
582 	bzero(&hints, sizeof(hints));
583 	hints.ai_family = AF_INET6;
584 	gai_error = getaddrinfo(host, NULL, &hints, &res);
585 	if (gai_error) {
586 		fprintf(stderr, "ndp: %s: %s\n", host,
587 		    gai_strerror(gai_error));
588 		return 1;
589 	}
590 	sin->sin6_addr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
591 	sin->sin6_scope_id =
592 	    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
593 	if (rtmsg(RTM_GET) < 0) {
594 		errx(1, "RTM_GET(%s) failed", host);
595 		/* NOTREACHED */
596 	}
597 	sin = (struct sockaddr_in6 *)(rtm + 1);
598 	sdl = (struct sockaddr_dl *)(ALIGN(sin->sin6_len) + (char *)sin);
599 	if (IN6_ARE_ADDR_EQUAL(&sin->sin6_addr, &sin_m.sin6_addr)) {
600 		if (sdl->sdl_family == AF_LINK &&
601 		    !(rtm->rtm_flags & RTF_GATEWAY)) {
602 			goto delete;
603 		}
604 		fprintf(stderr, "delete: cannot delete non-NDP entry\n");
605 		return 1;
606 	}
607 
608 delete:
609 	if (sdl->sdl_family != AF_LINK) {
610 		printf("cannot locate %s\n", host);
611 		return (1);
612 	}
613 	/*
614 	 * need to reinit the field because it has rt_key
615 	 * but we want the actual address
616 	 */
617 	NEXTADDR(RTA_DST, sin_m);
618 	rtm->rtm_flags |= RTF_LLDATA;
619 	if (rtmsg(RTM_DELETE) == 0) {
620 #ifndef FSTACK
621 		getnameinfo((struct sockaddr *)sin,
622 		    sin->sin6_len, host_buf,
623 		    sizeof(host_buf), NULL, 0,
624 		    (nflag ? NI_NUMERICHOST : 0));
625 #else
626 		inet_ntop(AF_INET6_LINUX, &sin->sin6_addr, host_buf, sizeof(host_buf));
627 #endif
628 		printf("%s (%s) deleted\n", host, host_buf);
629 	}
630 
631 	return 0;
632 }
633 
634 #define W_ADDR	36
635 #define W_LL	17
636 #define W_IF	6
637 
638 /*
639  * Dump the entire neighbor cache
640  */
641 static void
dump(struct sockaddr_in6 * addr,int cflag)642 dump(struct sockaddr_in6 *addr, int cflag)
643 {
644 	int mib[6];
645 	size_t needed;
646 	char *lim, *buf, *next;
647 	struct rt_msghdr *rtm;
648 	struct sockaddr_in6 *sin;
649 	struct sockaddr_dl *sdl;
650 	struct timeval now;
651 	time_t expire;
652 	int addrwidth;
653 	int llwidth;
654 	int ifwidth;
655 	char flgbuf[8];
656 	char *ifname;
657 
658 	/* Print header */
659 	if (!tflag && !cflag)
660 		printf("%-*.*s %-*.*s %*.*s %-9.9s %1s %5s\n",
661 		    W_ADDR, W_ADDR, "Neighbor", W_LL, W_LL, "Linklayer Address",
662 		    W_IF, W_IF, "Netif", "Expire", "S", "Flags");
663 
664 again:;
665 	mib[0] = CTL_NET;
666 	mib[1] = PF_ROUTE;
667 	mib[2] = 0;
668 	mib[3] = AF_INET6;
669 	mib[4] = NET_RT_FLAGS;
670 #ifdef RTF_LLINFO
671 	mib[5] = RTF_LLINFO;
672 #else
673 	mib[5] = 0;
674 #endif
675 	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
676 		err(1, "sysctl(PF_ROUTE estimate)");
677 	if (needed > 0) {
678 		if ((buf = malloc(needed)) == NULL)
679 			err(1, "malloc");
680 		if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
681 			err(1, "sysctl(PF_ROUTE, NET_RT_FLAGS)");
682 		lim = buf + needed;
683 	} else
684 		buf = lim = NULL;
685 
686 	for (next = buf; next && next < lim; next += rtm->rtm_msglen) {
687 		int isrouter = 0, prbs = 0;
688 
689 		rtm = (struct rt_msghdr *)next;
690 		sin = (struct sockaddr_in6 *)(rtm + 1);
691 		sdl = (struct sockaddr_dl *)((char *)sin +
692 		    ALIGN(sin->sin6_len));
693 
694 		/*
695 		 * Some OSes can produce a route that has the LINK flag but
696 		 * has a non-AF_LINK gateway (e.g. fe80::xx%lo0 on FreeBSD
697 		 * and BSD/OS, where xx is not the interface identifier on
698 		 * lo0).  Such routes entry would annoy getnbrinfo() below,
699 		 * so we skip them.
700 		 * XXX: such routes should have the GATEWAY flag, not the
701 		 * LINK flag.  However, there is rotten routing software
702 		 * that advertises all routes that have the GATEWAY flag.
703 		 * Thus, KAME kernel intentionally does not set the LINK flag.
704 		 * What is to be fixed is not ndp, but such routing software
705 		 * (and the kernel workaround)...
706 		 */
707 		if (sdl->sdl_family != AF_LINK)
708 			continue;
709 
710 		if (!(rtm->rtm_flags & RTF_HOST))
711 			continue;
712 
713 		if (addr) {
714 			if (IN6_ARE_ADDR_EQUAL(&addr->sin6_addr,
715 			    &sin->sin6_addr) == 0 ||
716 			    addr->sin6_scope_id != sin->sin6_scope_id)
717 				continue;
718 			found_entry = 1;
719 		} else if (IN6_IS_ADDR_MULTICAST(&sin->sin6_addr))
720 			continue;
721 		if (IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr) ||
722 		    IN6_IS_ADDR_MC_LINKLOCAL(&sin->sin6_addr)) {
723 			/* XXX: should scope id be filled in the kernel? */
724 			if (sin->sin6_scope_id == 0)
725 				sin->sin6_scope_id = sdl->sdl_index;
726 		}
727 #ifndef FSTACK
728 		getnameinfo((struct sockaddr *)sin, sin->sin6_len, host_buf,
729 		    sizeof(host_buf), NULL, 0, (nflag ? NI_NUMERICHOST : 0));
730 #else
731 		inet_ntop(AF_INET6_LINUX, &sin->sin6_addr, host_buf, sizeof(host_buf));
732 #endif
733 		if (cflag) {
734 #ifdef RTF_WASCLONED
735 			if (rtm->rtm_flags & RTF_WASCLONED)
736 				delete(host_buf);
737 #elif defined(RTF_CLONED)
738 			if (rtm->rtm_flags & RTF_CLONED)
739 				delete(host_buf);
740 #else
741 			if (rtm->rtm_flags & RTF_PINNED)
742 				continue;
743 			delete(host_buf);
744 #endif
745 			continue;
746 		}
747 		gettimeofday(&now, 0);
748 		if (tflag)
749 			ts_print(&now);
750 
751 		addrwidth = strlen(host_buf);
752 		if (addrwidth < W_ADDR)
753 			addrwidth = W_ADDR;
754 		llwidth = strlen(ether_str(sdl));
755 		if (W_ADDR + W_LL - addrwidth > llwidth)
756 			llwidth = W_ADDR + W_LL - addrwidth;
757 		ifname = if_indextoname(sdl->sdl_index, ifix_buf);
758 		if (ifname == NULL) {
759 			strlcpy(ifix_buf, "?", sizeof(ifix_buf));
760 			ifname = ifix_buf;
761 		}
762 		ifwidth = strlen(ifname);
763 		if (W_ADDR + W_LL + W_IF - addrwidth - llwidth > ifwidth)
764 			ifwidth = W_ADDR + W_LL + W_IF - addrwidth - llwidth;
765 
766 		printf("%-*.*s %-*.*s %*.*s", addrwidth, addrwidth, host_buf,
767 		    llwidth, llwidth, ether_str(sdl), ifwidth, ifwidth, ifname);
768 
769 		/* Print neighbor discovery specific information */
770 		expire = rtm->rtm_rmx.rmx_expire;
771 		if (expire > now.tv_sec)
772 			printf(" %-9.9s", sec2str(expire - now.tv_sec));
773 		else if (expire == 0)
774 			printf(" %-9.9s", "permanent");
775 		else
776 			printf(" %-9.9s", "expired");
777 
778 		switch (rtm->rtm_rmx.rmx_state) {
779 		case ND6_LLINFO_NOSTATE:
780 			printf(" N");
781 			break;
782 #ifdef ND6_LLINFO_WAITDELETE
783 		case ND6_LLINFO_WAITDELETE:
784 			printf(" W");
785 			break;
786 #endif
787 		case ND6_LLINFO_INCOMPLETE:
788 			printf(" I");
789 			break;
790 		case ND6_LLINFO_REACHABLE:
791 			printf(" R");
792 			break;
793 		case ND6_LLINFO_STALE:
794 			printf(" S");
795 			break;
796 		case ND6_LLINFO_DELAY:
797 			printf(" D");
798 			break;
799 		case ND6_LLINFO_PROBE:
800 			printf(" P");
801 			break;
802 		default:
803 			printf(" ?");
804 			break;
805 		}
806 
807 		isrouter = rtm->rtm_flags & RTF_GATEWAY;
808 		prbs = rtm->rtm_rmx.rmx_pksent;
809 
810 		/*
811 		 * other flags. R: router, P: proxy, W: ??
812 		 */
813 		if ((rtm->rtm_addrs & RTA_NETMASK) == 0) {
814 			snprintf(flgbuf, sizeof(flgbuf), "%s%s",
815 			    isrouter ? "R" : "",
816 			    (rtm->rtm_flags & RTF_ANNOUNCE) ? "p" : "");
817 		} else {
818 #if 0			/* W and P are mystery even for us */
819 			sin = (struct sockaddr_in6 *)
820 			    (sdl->sdl_len + (char *)sdl);
821 			snprintf(flgbuf, sizeof(flgbuf), "%s%s%s%s",
822 			    isrouter ? "R" : "",
823 			    !IN6_IS_ADDR_UNSPECIFIED(&sin->sin6_addr) ? "P" : "",
824 			    (sin->sin6_len != sizeof(struct sockaddr_in6)) ? "W" : "",
825 			    (rtm->rtm_flags & RTF_ANNOUNCE) ? "p" : "");
826 #else
827 			snprintf(flgbuf, sizeof(flgbuf), "%s%s",
828 			    isrouter ? "R" : "",
829 			    (rtm->rtm_flags & RTF_ANNOUNCE) ? "p" : "");
830 #endif
831 		}
832 		printf(" %s", flgbuf);
833 
834 		if (prbs)
835 			printf(" %d", prbs);
836 
837 		printf("\n");
838 	}
839 	if (buf != NULL)
840 		free(buf);
841 
842 	if (repeat) {
843 		printf("\n");
844 		fflush(stdout);
845 		sleep(repeat);
846 		goto again;
847 	}
848 }
849 
850 static struct in6_nbrinfo *
getnbrinfo(struct in6_addr * addr,int ifindex,int warning)851 getnbrinfo(struct in6_addr *addr, int ifindex, int warning)
852 {
853 	static struct in6_nbrinfo nbi;
854 	int sock;
855 
856 	if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
857 		err(1, "socket");
858 
859 	bzero(&nbi, sizeof(nbi));
860 	if_indextoname(ifindex, nbi.ifname);
861 	nbi.addr = *addr;
862 	if (ioctl(sock, SIOCGNBRINFO_IN6, (caddr_t)&nbi) < 0) {
863 		if (warning)
864 			warn("ioctl(SIOCGNBRINFO_IN6)");
865 		close(sock);
866 		return(NULL);
867 	}
868 
869 	close(sock);
870 	return(&nbi);
871 }
872 
873 static char *
ether_str(struct sockaddr_dl * sdl)874 ether_str(struct sockaddr_dl *sdl)
875 {
876 	static char hbuf[NI_MAXHOST];
877 
878 	if (sdl->sdl_alen == ETHER_ADDR_LEN) {
879 		strlcpy(hbuf, ether_ntoa((struct ether_addr *)LLADDR(sdl)),
880 		    sizeof(hbuf));
881 	} else if (sdl->sdl_alen) {
882 		int n = sdl->sdl_nlen > 0 ? sdl->sdl_nlen + 1 : 0;
883 		snprintf(hbuf, sizeof(hbuf), "%s", link_ntoa(sdl) + n);
884 	} else
885 		snprintf(hbuf, sizeof(hbuf), "(incomplete)");
886 
887 	return(hbuf);
888 }
889 
890 static int
ndp_ether_aton(char * a,u_char * n)891 ndp_ether_aton(char *a, u_char *n)
892 {
893 	int i, o[6];
894 
895 	i = sscanf(a, "%x:%x:%x:%x:%x:%x", &o[0], &o[1], &o[2],
896 	    &o[3], &o[4], &o[5]);
897 	if (i != 6) {
898 		fprintf(stderr, "ndp: invalid Ethernet address '%s'\n", a);
899 		return (1);
900 	}
901 	for (i = 0; i < 6; i++)
902 		n[i] = o[i];
903 	return (0);
904 }
905 
906 static void
usage()907 usage()
908 {
909 #ifndef FSTACK
910 	printf("usage: ndp [-nt] hostname\n");
911 	printf("       ndp [-nt] -a | -c | -p | -r | -H | -P | -R\n");
912 	printf("       ndp [-nt] -A wait\n");
913 	printf("       ndp [-nt] -d hostname\n");
914 	printf("       ndp [-nt] -f filename\n");
915 	printf("       ndp [-nt] -i interface [flags...]\n");
916 #ifdef SIOCSDEFIFACE_IN6
917 	printf("       ndp [-nt] -I [interface|delete]\n");
918 #endif
919 	printf("       ndp [-nt] -s nodename etheraddr [temp] [proxy]\n");
920 #else
921 	printf("usage: ndp -C <f-stack proc_id> [-nt] hostname\n");
922 	printf("       ndp -C <f-stack proc_id> [-nt] -a | -c | -p | -r | -H | -P | -R\n");
923 	printf("       ndp -C <f-stack proc_id> [-nt] -A wait\n");
924 	printf("       ndp -C <f-stack proc_id> [-nt] -d hostname\n");
925 	printf("       ndp -C <f-stack proc_id> [-nt] -f filename\n");
926 	printf("       ndp -C <f-stack proc_id> [-nt] -i interface [flags...]\n");
927 #ifdef SIOCSDEFIFACE_IN6
928 	printf("       ndp -C <f-stack proc_id> [-nt] -I [interface|delete]\n");
929 #endif
930 	printf("       ndp -C <f-stack proc_id> [-nt] -s nodename etheraddr [temp] [proxy]\n");
931 #endif
932 	exit(1);
933 }
934 
935 static int
rtmsg(int cmd)936 rtmsg(int cmd)
937 {
938 	static int seq;
939 	int rlen;
940 	register struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
941 	register char *cp = m_rtmsg.m_space;
942 	register int l;
943 
944 	errno = 0;
945 	if (cmd == RTM_DELETE)
946 		goto doit;
947 	bzero((char *)&m_rtmsg, sizeof(m_rtmsg));
948 	rtm->rtm_flags = flags;
949 	rtm->rtm_version = RTM_VERSION;
950 
951 	switch (cmd) {
952 	default:
953 		fprintf(stderr, "ndp: internal wrong cmd\n");
954 		exit(1);
955 	case RTM_ADD:
956 		rtm->rtm_addrs |= RTA_GATEWAY;
957 		if (expire_time) {
958 			rtm->rtm_rmx.rmx_expire = expire_time;
959 			rtm->rtm_inits = RTV_EXPIRE;
960 		}
961 		rtm->rtm_flags |= (RTF_HOST | RTF_STATIC | RTF_LLDATA);
962 		/* FALLTHROUGH */
963 	case RTM_GET:
964 		rtm->rtm_addrs |= RTA_DST;
965 	}
966 
967 	NEXTADDR(RTA_DST, sin_m);
968 	NEXTADDR(RTA_GATEWAY, sdl_m);
969 
970 	rtm->rtm_msglen = cp - (char *)&m_rtmsg;
971 doit:
972 	l = rtm->rtm_msglen;
973 	rtm->rtm_seq = ++seq;
974 	rtm->rtm_type = cmd;
975 #ifndef FSTACK
976 	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
977 		if (errno != ESRCH || cmd != RTM_DELETE) {
978 			err(1, "writing to routing socket");
979 			/* NOTREACHED */
980 		}
981 	}
982 	do {
983 		l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
984 	} while (l > 0 && (rtm->rtm_type != cmd || rtm->rtm_seq != seq ||
985 	    rtm->rtm_pid != pid));
986 #else
987 	l = rtioctl((char *)&m_rtmsg, l, sizeof(m_rtmsg));
988 #endif
989 	if (l < 0)
990 		(void) fprintf(stderr, "ndp: read from routing socket: %s\n",
991 		    strerror(errno));
992 	return (0);
993 }
994 
995 static void
ifinfo(char * ifname,int argc,char ** argv)996 ifinfo(char *ifname, int argc, char **argv)
997 {
998 	struct in6_ndireq nd;
999 	int i, sock;
1000 	u_int32_t newflags;
1001 #ifdef IPV6CTL_USETEMPADDR
1002 	u_int8_t nullbuf[8];
1003 #endif
1004 
1005 	if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1006 		err(1, "socket");
1007 		/* NOTREACHED */
1008 	}
1009 	bzero(&nd, sizeof(nd));
1010 	strlcpy(nd.ifname, ifname, sizeof(nd.ifname));
1011 	if (ioctl(sock, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
1012 		err(1, "ioctl(SIOCGIFINFO_IN6)");
1013 		/* NOTREACHED */
1014 	}
1015 #define	ND nd.ndi
1016 	newflags = ND.flags;
1017 	for (i = 0; i < argc; i++) {
1018 		int clear = 0;
1019 		char *cp = argv[i];
1020 
1021 		if (*cp == '-') {
1022 			clear = 1;
1023 			cp++;
1024 		}
1025 
1026 #define	SETFLAG(s, f) do {			\
1027 	if (strcmp(cp, (s)) == 0) {		\
1028 		if (clear)			\
1029 			newflags &= ~(f);	\
1030 		else				\
1031 			newflags |= (f);	\
1032 	}					\
1033 } while (0)
1034 /*
1035  * XXX: this macro is not 100% correct, in that it matches "nud" against
1036  *      "nudbogus".  But we just let it go since this is minor.
1037  */
1038 #define	SETVALUE(f, v) do {						\
1039 	char *valptr;							\
1040 	unsigned long newval;						\
1041 	v = 0; /* unspecified */					\
1042 	if (strncmp(cp, f, strlen(f)) == 0) {				\
1043 		valptr = strchr(cp, '=');				\
1044 		if (valptr == NULL)					\
1045 			err(1, "syntax error in %s field", (f));	\
1046 		errno = 0;						\
1047 		newval = strtoul(++valptr, NULL, 0);			\
1048 		if (errno)						\
1049 			err(1, "syntax error in %s's value", (f));	\
1050 		v = newval;						\
1051 	}								\
1052 } while (0)
1053 
1054 		SETFLAG("disabled", ND6_IFF_IFDISABLED);
1055 		SETFLAG("nud", ND6_IFF_PERFORMNUD);
1056 #ifdef ND6_IFF_ACCEPT_RTADV
1057 		SETFLAG("accept_rtadv", ND6_IFF_ACCEPT_RTADV);
1058 #endif
1059 #ifdef ND6_IFF_AUTO_LINKLOCAL
1060 		SETFLAG("auto_linklocal", ND6_IFF_AUTO_LINKLOCAL);
1061 #endif
1062 #ifdef ND6_IFF_NO_PREFER_IFACE
1063 		SETFLAG("no_prefer_iface", ND6_IFF_NO_PREFER_IFACE);
1064 #endif
1065 		SETVALUE("basereachable", ND.basereachable);
1066 		SETVALUE("retrans", ND.retrans);
1067 		SETVALUE("curhlim", ND.chlim);
1068 
1069 		ND.flags = newflags;
1070 		if (ioctl(sock, SIOCSIFINFO_IN6, (caddr_t)&nd) < 0) {
1071 			err(1, "ioctl(SIOCSIFINFO_IN6)");
1072 			/* NOTREACHED */
1073 		}
1074 #undef SETFLAG
1075 #undef SETVALUE
1076 	}
1077 
1078 	if (!ND.initialized) {
1079 		errx(1, "%s: not initialized yet", ifname);
1080 		/* NOTREACHED */
1081 	}
1082 
1083 	if (ioctl(sock, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
1084 		err(1, "ioctl(SIOCGIFINFO_IN6)");
1085 		/* NOTREACHED */
1086 	}
1087 	printf("linkmtu=%d", ND.linkmtu);
1088 	printf(", maxmtu=%d", ND.maxmtu);
1089 	printf(", curhlim=%d", ND.chlim);
1090 	printf(", basereachable=%ds%dms",
1091 	    ND.basereachable / 1000, ND.basereachable % 1000);
1092 	printf(", reachable=%ds", ND.reachable);
1093 	printf(", retrans=%ds%dms", ND.retrans / 1000, ND.retrans % 1000);
1094 #ifdef IPV6CTL_USETEMPADDR
1095 	memset(nullbuf, 0, sizeof(nullbuf));
1096 	if (memcmp(nullbuf, ND.randomid, sizeof(nullbuf)) != 0) {
1097 		int j;
1098 		u_int8_t *rbuf;
1099 
1100 		for (i = 0; i < 3; i++) {
1101 			switch (i) {
1102 			case 0:
1103 				printf("\nRandom seed(0): ");
1104 				rbuf = ND.randomseed0;
1105 				break;
1106 			case 1:
1107 				printf("\nRandom seed(1): ");
1108 				rbuf = ND.randomseed1;
1109 				break;
1110 			case 2:
1111 				printf("\nRandom ID:      ");
1112 				rbuf = ND.randomid;
1113 				break;
1114 			default:
1115 				errx(1, "impossible case for tempaddr display");
1116 			}
1117 			for (j = 0; j < 8; j++)
1118 				printf("%02x", rbuf[j]);
1119 		}
1120 	}
1121 #endif /* IPV6CTL_USETEMPADDR */
1122 	if (ND.flags) {
1123 		printf("\nFlags: ");
1124 #ifdef ND6_IFF_IFDISABLED
1125 		if ((ND.flags & ND6_IFF_IFDISABLED))
1126 			printf("disabled ");
1127 #endif
1128 		if ((ND.flags & ND6_IFF_PERFORMNUD))
1129 			printf("nud ");
1130 #ifdef ND6_IFF_ACCEPT_RTADV
1131 		if ((ND.flags & ND6_IFF_ACCEPT_RTADV))
1132 			printf("accept_rtadv ");
1133 #endif
1134 #ifdef ND6_IFF_AUTO_LINKLOCAL
1135 		if ((ND.flags & ND6_IFF_AUTO_LINKLOCAL))
1136 			printf("auto_linklocal ");
1137 #endif
1138 #ifdef ND6_IFF_NO_PREFER_IFACE
1139 		if ((ND.flags & ND6_IFF_NO_PREFER_IFACE))
1140 			printf("no_prefer_iface ");
1141 #endif
1142 	}
1143 	putc('\n', stdout);
1144 #undef ND
1145 
1146 	close(sock);
1147 }
1148 
1149 #ifndef ND_RA_FLAG_RTPREF_MASK	/* XXX: just for compilation on *BSD release */
1150 #define ND_RA_FLAG_RTPREF_MASK	0x18 /* 00011000 */
1151 #endif
1152 
1153 static void
rtrlist()1154 rtrlist()
1155 {
1156 	int mib[] = { CTL_NET, PF_INET6, IPPROTO_ICMPV6, ICMPV6CTL_ND6_DRLIST };
1157 	char *buf;
1158 	struct in6_defrouter *p, *ep;
1159 	size_t l;
1160 	struct timeval now;
1161 
1162 	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0) {
1163 		err(1, "sysctl(ICMPV6CTL_ND6_DRLIST)");
1164 		/*NOTREACHED*/
1165 	}
1166 	if (l == 0)
1167 		return;
1168 	buf = malloc(l);
1169 	if (!buf) {
1170 		err(1, "malloc");
1171 		/*NOTREACHED*/
1172 	}
1173 	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
1174 		err(1, "sysctl(ICMPV6CTL_ND6_DRLIST)");
1175 		/*NOTREACHED*/
1176 	}
1177 
1178 	ep = (struct in6_defrouter *)(buf + l);
1179 	for (p = (struct in6_defrouter *)buf; p < ep; p++) {
1180 		int rtpref;
1181 #ifndef FSTACK
1182 		if (getnameinfo((struct sockaddr *)&p->rtaddr,
1183 		    p->rtaddr.sin6_len, host_buf, sizeof(host_buf), NULL, 0,
1184 		    (nflag ? NI_NUMERICHOST : 0)) != 0)
1185 #else
1186 		if (inet_ntop(AF_INET6_LINUX, &p->rtaddr.sin6_addr, host_buf, sizeof(host_buf)) == NULL)
1187 #endif
1188 			strlcpy(host_buf, "?", sizeof(host_buf));
1189 
1190 		printf("%s if=%s", host_buf,
1191 		    if_indextoname(p->if_index, ifix_buf));
1192 		printf(", flags=%s%s",
1193 		    p->flags & ND_RA_FLAG_MANAGED ? "M" : "",
1194 		    p->flags & ND_RA_FLAG_OTHER   ? "O" : "");
1195 #ifdef DRAFT_IETF_6MAN_IPV6ONLY_FLAG
1196 		printf("%s", p->flags & ND_RA_FLAG_IPV6_ONLY ? "S" : "");
1197 #endif
1198 		rtpref = ((p->flags & ND_RA_FLAG_RTPREF_MASK) >> 3) & 0xff;
1199 		printf(", pref=%s", rtpref_str[rtpref]);
1200 
1201 		gettimeofday(&now, 0);
1202 		if (p->expire == 0)
1203 			printf(", expire=Never\n");
1204 		else
1205 			printf(", expire=%s\n",
1206 			    sec2str(p->expire - now.tv_sec));
1207 	}
1208 	free(buf);
1209 }
1210 
1211 static void
plist()1212 plist()
1213 {
1214 	int mib[] = { CTL_NET, PF_INET6, IPPROTO_ICMPV6, ICMPV6CTL_ND6_PRLIST };
1215 	char *buf;
1216 	struct in6_prefix *p, *ep, *n;
1217 	struct sockaddr_in6 *advrtr;
1218 	size_t l;
1219 	struct timeval now;
1220 	const int niflags = NI_NUMERICHOST;
1221 	int ninflags = nflag ? NI_NUMERICHOST : 0;
1222 	char namebuf[NI_MAXHOST];
1223 
1224 	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0) {
1225 		err(1, "sysctl(ICMPV6CTL_ND6_PRLIST)");
1226 		/*NOTREACHED*/
1227 	}
1228 	buf = malloc(l);
1229 	if (!buf) {
1230 		err(1, "malloc");
1231 		/*NOTREACHED*/
1232 	}
1233 	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
1234 		err(1, "sysctl(ICMPV6CTL_ND6_PRLIST)");
1235 		/*NOTREACHED*/
1236 	}
1237 
1238 	ep = (struct in6_prefix *)(buf + l);
1239 	for (p = (struct in6_prefix *)buf; p < ep; p = n) {
1240 		advrtr = (struct sockaddr_in6 *)(p + 1);
1241 		n = (struct in6_prefix *)&advrtr[p->advrtrs];
1242 #ifndef FSTACK
1243 		if (getnameinfo((struct sockaddr *)&p->prefix,
1244 		    p->prefix.sin6_len, namebuf, sizeof(namebuf),
1245 		    NULL, 0, niflags) != 0)
1246 #else
1247 		inet_ntop(AF_INET6_LINUX, &p->prefix.sin6_addr, namebuf, sizeof(namebuf));
1248 #endif
1249 			strlcpy(namebuf, "?", sizeof(namebuf));
1250 		printf("%s/%d if=%s\n", namebuf, p->prefixlen,
1251 		    if_indextoname(p->if_index, ifix_buf));
1252 
1253 		gettimeofday(&now, 0);
1254 		/*
1255 		 * meaning of fields, especially flags, is very different
1256 		 * by origin.  notify the difference to the users.
1257 		 */
1258 		printf("flags=%s%s%s%s%s",
1259 		    p->raflags.onlink ? "L" : "",
1260 		    p->raflags.autonomous ? "A" : "",
1261 		    (p->flags & NDPRF_ONLINK) != 0 ? "O" : "",
1262 		    (p->flags & NDPRF_DETACHED) != 0 ? "D" : "",
1263 #ifdef NDPRF_HOME
1264 		    (p->flags & NDPRF_HOME) != 0 ? "H" : ""
1265 #else
1266 		    ""
1267 #endif
1268 		    );
1269 		if (p->vltime == ND6_INFINITE_LIFETIME)
1270 			printf(" vltime=infinity");
1271 		else
1272 			printf(" vltime=%lu", (unsigned long)p->vltime);
1273 		if (p->pltime == ND6_INFINITE_LIFETIME)
1274 			printf(", pltime=infinity");
1275 		else
1276 			printf(", pltime=%lu", (unsigned long)p->pltime);
1277 		if (p->expire == 0)
1278 			printf(", expire=Never");
1279 		else if (p->expire >= now.tv_sec)
1280 			printf(", expire=%s",
1281 			    sec2str(p->expire - now.tv_sec));
1282 		else
1283 			printf(", expired");
1284 		printf(", ref=%d", p->refcnt);
1285 		printf("\n");
1286 		/*
1287 		 * "advertising router" list is meaningful only if the prefix
1288 		 * information is from RA.
1289 		 */
1290 		if (p->advrtrs) {
1291 			int j;
1292 			struct sockaddr_in6 *sin6;
1293 
1294 			sin6 = advrtr;
1295 			printf("  advertised by\n");
1296 			for (j = 0; j < p->advrtrs; j++) {
1297 				struct in6_nbrinfo *nbi;
1298 #ifndef FSTACK
1299 				if (getnameinfo((struct sockaddr *)sin6,
1300 				    sin6->sin6_len, namebuf, sizeof(namebuf),
1301 				    NULL, 0, ninflags) != 0)
1302 #else
1303 				if (inet_ntop(AF_INET6_LINUX, &sin6->sin6_addr, namebuf, sizeof(namebuf)) == NULL)
1304 #endif
1305 					strlcpy(namebuf, "?", sizeof(namebuf));
1306 				printf("    %s", namebuf);
1307 
1308 				nbi = getnbrinfo(&sin6->sin6_addr,
1309 				    p->if_index, 0);
1310 				if (nbi) {
1311 					switch (nbi->state) {
1312 					case ND6_LLINFO_REACHABLE:
1313 					case ND6_LLINFO_STALE:
1314 					case ND6_LLINFO_DELAY:
1315 					case ND6_LLINFO_PROBE:
1316 						printf(" (reachable)\n");
1317 						break;
1318 					default:
1319 						printf(" (unreachable)\n");
1320 					}
1321 				} else
1322 					printf(" (no neighbor state)\n");
1323 				sin6++;
1324 			}
1325 		} else
1326 			printf("  No advertising router\n");
1327 	}
1328 	free(buf);
1329 }
1330 
1331 static void
pfx_flush()1332 pfx_flush()
1333 {
1334 	char dummyif[IFNAMSIZ+8];
1335 	int sock;
1336 
1337 	if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1338 		err(1, "socket");
1339 	strlcpy(dummyif, "lo0", sizeof(dummyif)); /* dummy */
1340 	if (ioctl(sock, SIOCSPFXFLUSH_IN6, (caddr_t)&dummyif) < 0)
1341 		err(1, "ioctl(SIOCSPFXFLUSH_IN6)");
1342 
1343 	close(sock);
1344 }
1345 
1346 static void
rtr_flush()1347 rtr_flush()
1348 {
1349 	char dummyif[IFNAMSIZ+8];
1350 	int sock;
1351 
1352 	if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1353 		err(1, "socket");
1354 	strlcpy(dummyif, "lo0", sizeof(dummyif)); /* dummy */
1355 	if (ioctl(sock, SIOCSRTRFLUSH_IN6, (caddr_t)&dummyif) < 0)
1356 		err(1, "ioctl(SIOCSRTRFLUSH_IN6)");
1357 
1358 	close(sock);
1359 }
1360 
1361 static void
harmonize_rtr()1362 harmonize_rtr()
1363 {
1364 	char dummyif[IFNAMSIZ+8];
1365 	int sock;
1366 
1367 	if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1368 		err(1, "socket");
1369 	strlcpy(dummyif, "lo0", sizeof(dummyif)); /* dummy */
1370 	if (ioctl(sock, SIOCSNDFLUSH_IN6, (caddr_t)&dummyif) < 0)
1371 		err(1, "ioctl(SIOCSNDFLUSH_IN6)");
1372 
1373 	close(sock);
1374 }
1375 
1376 #ifdef SIOCSDEFIFACE_IN6	/* XXX: check SIOCGDEFIFACE_IN6 as well? */
1377 static void
setdefif(char * ifname)1378 setdefif(char *ifname)
1379 {
1380 	struct in6_ndifreq ndifreq;
1381 	unsigned int ifindex;
1382 	int sock;
1383 
1384 	if (strcasecmp(ifname, "delete") == 0)
1385 		ifindex = 0;
1386 	else {
1387 		if ((ifindex = if_nametoindex(ifname)) == 0)
1388 			err(1, "failed to resolve i/f index for %s", ifname);
1389 	}
1390 
1391 	if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1392 		err(1, "socket");
1393 
1394 	strlcpy(ndifreq.ifname, "lo0", sizeof(ndifreq.ifname)); /* dummy */
1395 	ndifreq.ifindex = ifindex;
1396 
1397 	if (ioctl(sock, SIOCSDEFIFACE_IN6, (caddr_t)&ndifreq) < 0)
1398 		err(1, "ioctl(SIOCSDEFIFACE_IN6)");
1399 
1400 	close(sock);
1401 }
1402 
1403 static void
getdefif()1404 getdefif()
1405 {
1406 	struct in6_ndifreq ndifreq;
1407 	char ifname[IFNAMSIZ+8];
1408 	int sock;
1409 
1410 	if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1411 		err(1, "socket");
1412 
1413 	memset(&ndifreq, 0, sizeof(ndifreq));
1414 	strlcpy(ndifreq.ifname, "lo0", sizeof(ndifreq.ifname)); /* dummy */
1415 
1416 	if (ioctl(sock, SIOCGDEFIFACE_IN6, (caddr_t)&ndifreq) < 0)
1417 		err(1, "ioctl(SIOCGDEFIFACE_IN6)");
1418 
1419 	if (ndifreq.ifindex == 0)
1420 		printf("No default interface.\n");
1421 	else {
1422 		if ((if_indextoname(ndifreq.ifindex, ifname)) == NULL)
1423 			err(1, "failed to resolve ifname for index %lu",
1424 			    ndifreq.ifindex);
1425 		printf("ND default interface = %s\n", ifname);
1426 	}
1427 
1428 	close(sock);
1429 }
1430 #endif /* SIOCSDEFIFACE_IN6 */
1431 
1432 static char *
sec2str(time_t total)1433 sec2str(time_t total)
1434 {
1435 	static char result[256];
1436 	int days, hours, mins, secs;
1437 	int first = 1;
1438 	char *p = result;
1439 	char *ep = &result[sizeof(result)];
1440 	int n;
1441 
1442 	days = total / 3600 / 24;
1443 	hours = (total / 3600) % 24;
1444 	mins = (total / 60) % 60;
1445 	secs = total % 60;
1446 
1447 	if (days) {
1448 		first = 0;
1449 		n = snprintf(p, ep - p, "%dd", days);
1450 		if (n < 0 || n >= ep - p)
1451 			return "?";
1452 		p += n;
1453 	}
1454 	if (!first || hours) {
1455 		first = 0;
1456 		n = snprintf(p, ep - p, "%dh", hours);
1457 		if (n < 0 || n >= ep - p)
1458 			return "?";
1459 		p += n;
1460 	}
1461 	if (!first || mins) {
1462 		first = 0;
1463 		n = snprintf(p, ep - p, "%dm", mins);
1464 		if (n < 0 || n >= ep - p)
1465 			return "?";
1466 		p += n;
1467 	}
1468 	snprintf(p, ep - p, "%ds", secs);
1469 
1470 	return(result);
1471 }
1472 
1473 /*
1474  * Print the timestamp
1475  * from tcpdump/util.c
1476  */
1477 static void
ts_print(const struct timeval * tvp)1478 ts_print(const struct timeval *tvp)
1479 {
1480 	int sec;
1481 
1482 	/* Default */
1483 	sec = (tvp->tv_sec + thiszone) % 86400;
1484 	(void)printf("%02d:%02d:%02d.%06u ",
1485 	    sec / 3600, (sec % 3600) / 60, sec % 60, (u_int32_t)tvp->tv_usec);
1486 }
1487 
1488 #undef NEXTADDR
1489