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