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