ndp.c revision 219819
11558Srgrimes/*	$FreeBSD: head/usr.sbin/ndp/ndp.c 219819 2011-03-21 09:40:01Z jeff $	*/
21558Srgrimes/*	$KAME: ndp.c,v 1.104 2003/06/27 07:48:39 itojun Exp $	*/
31558Srgrimes
41558Srgrimes/*
51558Srgrimes * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
61558Srgrimes * All rights reserved.
71558Srgrimes *
81558Srgrimes * Redistribution and use in source and binary forms, with or without
91558Srgrimes * modification, are permitted provided that the following conditions
101558Srgrimes * are met:
111558Srgrimes * 1. Redistributions of source code must retain the above copyright
121558Srgrimes *    notice, this list of conditions and the following disclaimer.
131558Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141558Srgrimes *    notice, this list of conditions and the following disclaimer in the
151558Srgrimes *    documentation and/or other materials provided with the distribution.
161558Srgrimes * 3. Neither the name of the project nor the names of its contributors
171558Srgrimes *    may be used to endorse or promote products derived from this software
181558Srgrimes *    without specific prior written permission.
191558Srgrimes *
201558Srgrimes * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
211558Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221558Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231558Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
241558Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251558Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261558Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271558Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2823684Speter * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2950476Speter * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301558Srgrimes * SUCH DAMAGE.
31270112Srmacklem */
321558Srgrimes/*
331558Srgrimes * Copyright (c) 1984, 1993
341558Srgrimes *	The Regents of the University of California.  All rights reserved.
351558Srgrimes *
361558Srgrimes * This code is derived from software contributed to Berkeley by
371558Srgrimes * Sun Microsystems, Inc.
381558Srgrimes *
391558Srgrimes * Redistribution and use in source and binary forms, with or without
4068960Sru * modification, are permitted provided that the following conditions
41220981Srmacklem * are met:
421558Srgrimes * 1. Redistributions of source code must retain the above copyright
4353096Sdillon *    notice, this list of conditions and the following disclaimer.
44243785Salfred * 2. Redistributions in binary form must reproduce the above copyright
45243785Salfred *    notice, this list of conditions and the following disclaimer in the
461558Srgrimes *    documentation and/or other materials provided with the distribution.
4799501Scharnier * 4. Neither the name of the University nor the names of its contributors
4899501Scharnier *    may be used to endorse or promote products derived from this software
4999501Scharnier *    without specific prior written permission.
501558Srgrimes *
511558Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
521558Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
5368960Sru * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
541558Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
551558Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56269443Srmacklem * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
571558Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
581558Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
591558Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
601558Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
611558Srgrimes * SUCH DAMAGE.
621558Srgrimes */
631558Srgrimes
641558Srgrimes/*
651558Srgrimes * Based on:
6674462Salfred * "@(#) Copyright (c) 1984, 1993\n\
671558Srgrimes *	The Regents of the University of California.  All rights reserved.\n";
681558Srgrimes *
691558Srgrimes * "@(#)arp.c	8.2 (Berkeley) 1/2/94";
701558Srgrimes */
711558Srgrimes
7274462Salfred/*
7374462Salfred * ndp - display, set, delete and flush neighbor cache
7474462Salfred */
7574462Salfred
7674462Salfred
7774462Salfred#include <sys/param.h>
7874462Salfred#include <sys/file.h>
79243785Salfred#include <sys/ioctl.h>
80243785Salfred#include <sys/socket.h>
81243785Salfred#include <sys/sysctl.h>
82243785Salfred#include <sys/time.h>
83243785Salfred#include <sys/queue.h>
84243785Salfred
85243785Salfred#include <net/if.h>
86243785Salfred#include <net/if_var.h>
87243785Salfred#include <net/if_dl.h>
88243785Salfred#include <net/if_types.h>
89243785Salfred#include <net/route.h>
9053096Sdillon
9153096Sdillon#include <netinet/in.h>
9257668Ssheldonh#include <netinet/if_ether.h>
9357668Ssheldonh
9453096Sdillon#include <netinet/icmp6.h>
9553096Sdillon#include <netinet6/in6_var.h>
9653096Sdillon#include <netinet6/nd6.h>
9753096Sdillon
9853096Sdillon#include <arpa/inet.h>
9953096Sdillon
100131500Sru#include <netdb.h>
101131500Sru#include <errno.h>
10253096Sdillon#include <nlist.h>
103131500Sru#include <stdio.h>
104131500Sru#include <string.h>
10553096Sdillon#include <paths.h>
1061558Srgrimes#include <err.h>
1071558Srgrimes#include <stdlib.h>
1081558Srgrimes#include <fcntl.h>
1091558Srgrimes#include <unistd.h>
1101558Srgrimes#include "gmt2local.h"
1111558Srgrimes
1121558Srgrimes/* packing rule for routing socket */
1131558Srgrimes#define ROUNDUP(a) \
114192993Srmacklem	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
115220981Srmacklem#define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
116220981Srmacklem
117220981Srmacklem#define NEXTADDR(w, s) \
118220981Srmacklem	if (rtm->rtm_addrs & (w)) { \
119220981Srmacklem		bcopy((char *)&s, cp, sizeof(s)); cp += SA_SIZE(&s);}
1201558Srgrimes
1211558Srgrimes
12279754Sddstatic pid_t pid;
12335582Speterstatic int nflag;
1241558Srgrimesstatic int tflag;
1251558Srgrimesstatic int32_t thiszone;	/* time difference with gmt */
1261558Srgrimesstatic int s = -1;
1271558Srgrimesstatic int repeat = 0;
1281558Srgrimes
1291558Srgrimeschar ntop_buf[INET6_ADDRSTRLEN];	/* inet_ntop() */
1301558Srgrimeschar host_buf[NI_MAXHOST];		/* getnameinfo() */
1311558Srgrimeschar ifix_buf[IFNAMSIZ];		/* if_indextoname() */
1321558Srgrimes
1331558Srgrimesint main(int, char **);
13499501Scharnierint file(char *);
13599501Scharniervoid getsocket(void);
13699501Scharnierint set(int, char **);
1371558Srgrimesvoid get(char *);
1381558Srgrimesint delete(char *);
1391558Srgrimesvoid dump(struct in6_addr *, int);
140192674Srmacklemstatic struct in6_nbrinfo *getnbrinfo(struct in6_addr *, int, int);
141192674Srmacklemstatic char *ether_str(struct sockaddr_dl *);
142192674Srmacklemint ndp_ether_aton(char *, u_char *);
143192674Srmacklemvoid usage(void);
144192674Srmacklemint rtmsg(int);
1451558Srgrimesvoid ifinfo(char *, int, char **);
1462999Swollmanvoid rtrlist(void);
14768960Sruvoid plist(void);
14879754Sddvoid pfx_flush(void);
1492999Swollmanvoid rtr_flush(void);
1502999Swollmanvoid harmonize_rtr(void);
1512999Swollman#ifdef SIOCSDEFIFACE_IN6	/* XXX: check SIOCGDEFIFACE_IN6 as well? */
1522999Swollmanstatic void getdefif(void);
1532999Swollmanstatic void setdefif(char *);
154101685Smux#endif
1552999Swollmanstatic char *sec2str(time_t);
1562999Swollmanstatic void ts_print(const struct timeval *);
15745212Sghelmer
15868960Sru#ifdef ICMPV6CTL_ND6_DRLIST
1592999Swollmanstatic char *rtpref_str[] = {
1602999Swollman	"medium",		/* 00 */
16153096Sdillon	"high",			/* 01 */
16268960Sru	"rsv",			/* 10 */
16353096Sdillon	"low"			/* 11 */
16453096Sdillon};
16553096Sdillon#endif
166131500Sru
167131500Sruint mode = 0;
168131500Sruchar *arg = NULL;
169131500Sru
17053096Sdillonint
17153096Sdillonmain(argc, argv)
17299501Scharnier	int argc;
17399501Scharnier	char **argv;
17499501Scharnier{
17553096Sdillon	int ch;
17653096Sdillon
17753096Sdillon	pid = getpid();
178270112Srmacklem	thiszone = gmt2local(0);
179270112Srmacklem	while ((ch = getopt(argc, argv, "acd:f:Ii:nprstA:HPR")) != -1)
180270112Srmacklem		switch (ch) {
181270112Srmacklem		case 'a':
182270112Srmacklem		case 'c':
183270112Srmacklem		case 'p':
184270112Srmacklem		case 'r':
185270112Srmacklem		case 'H':
186270112Srmacklem		case 'P':
187270112Srmacklem		case 'R':
188270112Srmacklem		case 's':
189270112Srmacklem		case 'I':
190270112Srmacklem			if (mode) {
191270112Srmacklem				usage();
192270112Srmacklem				/*NOTREACHED*/
193270112Srmacklem			}
194270112Srmacklem			mode = ch;
195270112Srmacklem			arg = NULL;
19699501Scharnier			break;
19774462Salfred		case 'd':
19899501Scharnier		case 'f':
19974519Sru		case 'i' :
20074519Sru			if (mode) {
20174519Sru				usage();
20274519Sru				/*NOTREACHED*/
20374519Sru			}
20499501Scharnier			mode = ch;
20574462Salfred			arg = optarg;
20699501Scharnier			break;
20774462Salfred		case 'n':
20874519Sru			nflag = 1;
20974519Sru			break;
21074462Salfred		case 't':
21174462Salfred			tflag = 1;
21274462Salfred			break;
213140368Sru		case 'A':
21481687Sru			if (mode) {
2151558Srgrimes				usage();
2161558Srgrimes				/*NOTREACHED*/
217101685Smux			}
2181558Srgrimes			mode = 'a';
219192674Srmacklem			repeat = atoi(optarg);
220127640Ssimon			if (repeat < 0) {
221220875Srmacklem				usage();
222192674Srmacklem				/*NOTREACHED*/
22379366Sru			}
2241558Srgrimes			break;
22555937Sdillon		default:
226192674Srmacklem			usage();
227192674Srmacklem		}
228220833Srmacklem
2291558Srgrimes	argc -= optind;
2301558Srgrimes	argv += optind;
23168960Sru
23217797Smpp	switch (mode) {
23317797Smpp	case 'a':
234192674Srmacklem	case 'c':
235192674Srmacklem		if (argc != 0) {
236192674Srmacklem			usage();
237192674Srmacklem			/*NOTREACHED*/
238192674Srmacklem		}
239192674Srmacklem		dump(0, mode == 'c');
240192674Srmacklem		break;
241192674Srmacklem	case 'd':
242192674Srmacklem		if (argc != 0) {
243192674Srmacklem			usage();
244192674Srmacklem			/*NOTREACHED*/
245		}
246		delete(arg);
247		break;
248	case 'I':
249#ifdef SIOCSDEFIFACE_IN6	/* XXX: check SIOCGDEFIFACE_IN6 as well? */
250		if (argc > 1) {
251			usage();
252			/*NOTREACHED*/
253		} else if (argc == 1) {
254			if (strcmp(*argv, "delete") == 0 ||
255			    if_nametoindex(*argv))
256				setdefif(*argv);
257			else
258				errx(1, "invalid interface %s", *argv);
259		}
260		getdefif(); /* always call it to print the result */
261		break;
262#else
263		errx(1, "not supported yet");
264		/*NOTREACHED*/
265#endif
266	case 'p':
267		if (argc != 0) {
268			usage();
269			/*NOTREACHED*/
270		}
271		plist();
272		break;
273	case 'i':
274		ifinfo(arg, argc, argv);
275		break;
276	case 'r':
277		if (argc != 0) {
278			usage();
279			/*NOTREACHED*/
280		}
281		rtrlist();
282		break;
283	case 's':
284		if (argc < 2 || argc > 4)
285			usage();
286		exit(set(argc, argv) ? 1 : 0);
287	case 'H':
288		if (argc != 0) {
289			usage();
290			/*NOTREACHED*/
291		}
292		harmonize_rtr();
293		break;
294	case 'P':
295		if (argc != 0) {
296			usage();
297			/*NOTREACHED*/
298		}
299		pfx_flush();
300		break;
301	case 'R':
302		if (argc != 0) {
303			usage();
304			/*NOTREACHED*/
305		}
306		rtr_flush();
307		break;
308	case 0:
309		if (argc != 1) {
310			usage();
311			/*NOTREACHED*/
312		}
313		get(argv[0]);
314		break;
315	}
316	exit(0);
317}
318
319/*
320 * Process a file to set standard ndp entries
321 */
322int
323file(name)
324	char *name;
325{
326	FILE *fp;
327	int i, retval;
328	char line[100], arg[5][50], *args[5];
329
330	if ((fp = fopen(name, "r")) == NULL) {
331		fprintf(stderr, "ndp: cannot open %s\n", name);
332		exit(1);
333	}
334	args[0] = &arg[0][0];
335	args[1] = &arg[1][0];
336	args[2] = &arg[2][0];
337	args[3] = &arg[3][0];
338	args[4] = &arg[4][0];
339	retval = 0;
340	while (fgets(line, sizeof(line), fp) != NULL) {
341		i = sscanf(line, "%49s %49s %49s %49s %49s",
342		    arg[0], arg[1], arg[2], arg[3], arg[4]);
343		if (i < 2) {
344			fprintf(stderr, "ndp: bad line: %s\n", line);
345			retval = 1;
346			continue;
347		}
348		if (set(i, args))
349			retval = 1;
350	}
351	fclose(fp);
352	return (retval);
353}
354
355void
356getsocket()
357{
358	if (s < 0) {
359		s = socket(PF_ROUTE, SOCK_RAW, 0);
360		if (s < 0) {
361			err(1, "socket");
362			/* NOTREACHED */
363		}
364	}
365}
366
367struct	sockaddr_in6 so_mask = {sizeof(so_mask), AF_INET6 };
368struct	sockaddr_in6 blank_sin = {sizeof(blank_sin), AF_INET6 }, sin_m;
369struct	sockaddr_dl blank_sdl = {sizeof(blank_sdl), AF_LINK }, sdl_m;
370int	expire_time, flags, found_entry;
371struct	{
372	struct	rt_msghdr m_rtm;
373	char	m_space[512];
374}	m_rtmsg;
375
376/*
377 * Set an individual neighbor cache entry
378 */
379int
380set(argc, argv)
381	int argc;
382	char **argv;
383{
384	register struct sockaddr_in6 *sin = &sin_m;
385	register struct sockaddr_dl *sdl;
386	register struct rt_msghdr *rtm = &(m_rtmsg.m_rtm);
387	struct addrinfo hints, *res;
388	int gai_error;
389	u_char *ea;
390	char *host = argv[0], *eaddr = argv[1];
391
392	getsocket();
393	argc -= 2;
394	argv += 2;
395	sdl_m = blank_sdl;
396	sin_m = blank_sin;
397
398	bzero(&hints, sizeof(hints));
399	hints.ai_family = AF_INET6;
400	gai_error = getaddrinfo(host, NULL, &hints, &res);
401	if (gai_error) {
402		fprintf(stderr, "ndp: %s: %s\n", host,
403			gai_strerror(gai_error));
404		return 1;
405	}
406	sin->sin6_addr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
407#ifdef __KAME__
408	if (IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr)) {
409		*(u_int16_t *)&sin->sin6_addr.s6_addr[2] =
410		    htons(((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id);
411	}
412#endif
413	ea = (u_char *)LLADDR(&sdl_m);
414	if (ndp_ether_aton(eaddr, ea) == 0)
415		sdl_m.sdl_alen = 6;
416	flags = expire_time = 0;
417	while (argc-- > 0) {
418		if (strncmp(argv[0], "temp", 4) == 0) {
419			struct timeval time;
420
421			gettimeofday(&time, 0);
422			expire_time = time.tv_sec + 20 * 60;
423		} else if (strncmp(argv[0], "proxy", 5) == 0)
424			flags |= RTF_ANNOUNCE;
425		argv++;
426	}
427	if (rtmsg(RTM_GET) < 0) {
428		errx(1, "RTM_GET(%s) failed", host);
429		/* NOTREACHED */
430	}
431	sin = (struct sockaddr_in6 *)(rtm + 1);
432	sdl = (struct sockaddr_dl *)(ROUNDUP(sin->sin6_len) + (char *)sin);
433	if (IN6_ARE_ADDR_EQUAL(&sin->sin6_addr, &sin_m.sin6_addr)) {
434		if (sdl->sdl_family == AF_LINK &&
435		    !(rtm->rtm_flags & RTF_GATEWAY)) {
436			switch (sdl->sdl_type) {
437			case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023:
438			case IFT_ISO88024: case IFT_ISO88025:
439			case IFT_L2VLAN: case IFT_BRIDGE:
440				goto overwrite;
441			}
442		}
443		/*
444		 * IPv4 arp command retries with sin_other = SIN_PROXY here.
445		 */
446		fprintf(stderr, "set: cannot configure a new entry\n");
447		return 1;
448	}
449
450overwrite:
451	if (sdl->sdl_family != AF_LINK) {
452		printf("cannot intuit interface index and type for %s\n", host);
453		return (1);
454	}
455	sdl_m.sdl_type = sdl->sdl_type;
456	sdl_m.sdl_index = sdl->sdl_index;
457	return (rtmsg(RTM_ADD));
458}
459
460/*
461 * Display an individual neighbor cache entry
462 */
463void
464get(host)
465	char *host;
466{
467	struct sockaddr_in6 *sin = &sin_m;
468	struct addrinfo hints, *res;
469	int gai_error;
470
471	sin_m = blank_sin;
472	bzero(&hints, sizeof(hints));
473	hints.ai_family = AF_INET6;
474	gai_error = getaddrinfo(host, NULL, &hints, &res);
475	if (gai_error) {
476		fprintf(stderr, "ndp: %s: %s\n", host,
477		    gai_strerror(gai_error));
478		return;
479	}
480	sin->sin6_addr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
481#ifdef __KAME__
482	if (IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr)) {
483		*(u_int16_t *)&sin->sin6_addr.s6_addr[2] =
484		    htons(((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id);
485	}
486#endif
487	dump(&sin->sin6_addr, 0);
488	if (found_entry == 0) {
489		getnameinfo((struct sockaddr *)sin, sin->sin6_len, host_buf,
490		    sizeof(host_buf), NULL ,0,
491		    (nflag ? NI_NUMERICHOST : 0));
492		printf("%s (%s) -- no entry\n", host, host_buf);
493		exit(1);
494	}
495}
496
497/*
498 * Delete a neighbor cache entry
499 */
500int
501delete(host)
502	char *host;
503{
504	struct sockaddr_in6 *sin = &sin_m;
505	register struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
506	register char *cp = m_rtmsg.m_space;
507	struct sockaddr_dl *sdl;
508	struct addrinfo hints, *res;
509	int gai_error;
510
511	getsocket();
512	sin_m = blank_sin;
513
514	bzero(&hints, sizeof(hints));
515	hints.ai_family = AF_INET6;
516	gai_error = getaddrinfo(host, NULL, &hints, &res);
517	if (gai_error) {
518		fprintf(stderr, "ndp: %s: %s\n", host,
519		    gai_strerror(gai_error));
520		return 1;
521	}
522	sin->sin6_addr = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr;
523#ifdef __KAME__
524	if (IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr)) {
525		*(u_int16_t *)&sin->sin6_addr.s6_addr[2] =
526		    htons(((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id);
527	}
528#endif
529	if (rtmsg(RTM_GET) < 0) {
530		errx(1, "RTM_GET(%s) failed", host);
531		/* NOTREACHED */
532	}
533	sin = (struct sockaddr_in6 *)(rtm + 1);
534	sdl = (struct sockaddr_dl *)(ROUNDUP(sin->sin6_len) + (char *)sin);
535	if (IN6_ARE_ADDR_EQUAL(&sin->sin6_addr, &sin_m.sin6_addr)) {
536		if (sdl->sdl_family == AF_LINK &&
537		    !(rtm->rtm_flags & RTF_GATEWAY)) {
538			goto delete;
539		}
540		/*
541		 * IPv4 arp command retries with sin_other = SIN_PROXY here.
542		 */
543		fprintf(stderr, "delete: cannot delete non-NDP entry\n");
544		return 1;
545	}
546
547delete:
548	if (sdl->sdl_family != AF_LINK) {
549		printf("cannot locate %s\n", host);
550		return (1);
551	}
552        /*
553         * need to reinit the field because it has rt_key
554         * but we want the actual address
555         */
556	NEXTADDR(RTA_DST, sin_m);
557	rtm->rtm_flags |= RTF_LLDATA;
558	if (rtmsg(RTM_DELETE) == 0) {
559		struct sockaddr_in6 s6 = *sin; /* XXX: for safety */
560
561#ifdef __KAME__
562		if (IN6_IS_ADDR_LINKLOCAL(&s6.sin6_addr)) {
563			s6.sin6_scope_id = ntohs(*(u_int16_t *)&s6.sin6_addr.s6_addr[2]);
564			*(u_int16_t *)&s6.sin6_addr.s6_addr[2] = 0;
565		}
566#endif
567		getnameinfo((struct sockaddr *)&s6,
568		    s6.sin6_len, host_buf,
569		    sizeof(host_buf), NULL, 0,
570		    (nflag ? NI_NUMERICHOST : 0));
571		printf("%s (%s) deleted\n", host, host_buf);
572	}
573
574	return 0;
575}
576
577#define W_ADDR	36
578#define W_LL	17
579#define W_IF	6
580
581/*
582 * Dump the entire neighbor cache
583 */
584void
585dump(addr, cflag)
586	struct in6_addr *addr;
587	int cflag;
588{
589	int mib[6];
590	size_t needed;
591	char *lim, *buf, *next;
592	struct rt_msghdr *rtm;
593	struct sockaddr_in6 *sin;
594	struct sockaddr_dl *sdl;
595	extern int h_errno;
596	struct in6_nbrinfo *nbi;
597	struct timeval time;
598	int addrwidth;
599	int llwidth;
600	int ifwidth;
601	char flgbuf[8];
602	char *ifname;
603
604	/* Print header */
605	if (!tflag && !cflag)
606		printf("%-*.*s %-*.*s %*.*s %-9.9s %1s %5s\n",
607		    W_ADDR, W_ADDR, "Neighbor", W_LL, W_LL, "Linklayer Address",
608		    W_IF, W_IF, "Netif", "Expire", "S", "Flags");
609
610again:;
611	mib[0] = CTL_NET;
612	mib[1] = PF_ROUTE;
613	mib[2] = 0;
614	mib[3] = AF_INET6;
615	mib[4] = NET_RT_FLAGS;
616#ifdef RTF_LLINFO
617	mib[5] = RTF_LLINFO;
618#else
619	mib[5] = 0;
620#endif
621	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
622		err(1, "sysctl(PF_ROUTE estimate)");
623	if (needed > 0) {
624		if ((buf = malloc(needed)) == NULL)
625			err(1, "malloc");
626		if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
627			err(1, "sysctl(PF_ROUTE, NET_RT_FLAGS)");
628		lim = buf + needed;
629	} else
630		buf = lim = NULL;
631
632	for (next = buf; next && next < lim; next += rtm->rtm_msglen) {
633		int isrouter = 0, prbs = 0;
634
635		rtm = (struct rt_msghdr *)next;
636		sin = (struct sockaddr_in6 *)(rtm + 1);
637		sdl = (struct sockaddr_dl *)((char *)sin + ROUNDUP(sin->sin6_len));
638
639		/*
640		 * Some OSes can produce a route that has the LINK flag but
641		 * has a non-AF_LINK gateway (e.g. fe80::xx%lo0 on FreeBSD
642		 * and BSD/OS, where xx is not the interface identifier on
643		 * lo0).  Such routes entry would annoy getnbrinfo() below,
644		 * so we skip them.
645		 * XXX: such routes should have the GATEWAY flag, not the
646		 * LINK flag.  However, there is rotten routing software
647		 * that advertises all routes that have the GATEWAY flag.
648		 * Thus, KAME kernel intentionally does not set the LINK flag.
649		 * What is to be fixed is not ndp, but such routing software
650		 * (and the kernel workaround)...
651		 */
652		if (sdl->sdl_family != AF_LINK)
653			continue;
654
655		if (!(rtm->rtm_flags & RTF_HOST))
656			continue;
657
658		if (addr) {
659			if (!IN6_ARE_ADDR_EQUAL(addr, &sin->sin6_addr))
660				continue;
661			found_entry = 1;
662		} else if (IN6_IS_ADDR_MULTICAST(&sin->sin6_addr))
663			continue;
664		if (IN6_IS_ADDR_LINKLOCAL(&sin->sin6_addr) ||
665		    IN6_IS_ADDR_MC_LINKLOCAL(&sin->sin6_addr)) {
666			/* XXX: should scope id be filled in the kernel? */
667			if (sin->sin6_scope_id == 0)
668				sin->sin6_scope_id = sdl->sdl_index;
669#ifdef __KAME__
670			/* KAME specific hack; removed the embedded id */
671			*(u_int16_t *)&sin->sin6_addr.s6_addr[2] = 0;
672#endif
673		}
674		getnameinfo((struct sockaddr *)sin, sin->sin6_len, host_buf,
675		    sizeof(host_buf), NULL, 0, (nflag ? NI_NUMERICHOST : 0));
676		if (cflag) {
677#ifdef RTF_WASCLONED
678			if (rtm->rtm_flags & RTF_WASCLONED)
679				delete(host_buf);
680#elif defined(RTF_CLONED)
681			if (rtm->rtm_flags & RTF_CLONED)
682				delete(host_buf);
683#else
684			delete(host_buf);
685#endif
686			continue;
687		}
688		gettimeofday(&time, 0);
689		if (tflag)
690			ts_print(&time);
691
692		addrwidth = strlen(host_buf);
693		if (addrwidth < W_ADDR)
694			addrwidth = W_ADDR;
695		llwidth = strlen(ether_str(sdl));
696		if (W_ADDR + W_LL - addrwidth > llwidth)
697			llwidth = W_ADDR + W_LL - addrwidth;
698		ifname = if_indextoname(sdl->sdl_index, ifix_buf);
699		if (!ifname)
700			ifname = "?";
701		ifwidth = strlen(ifname);
702		if (W_ADDR + W_LL + W_IF - addrwidth - llwidth > ifwidth)
703			ifwidth = W_ADDR + W_LL + W_IF - addrwidth - llwidth;
704
705		printf("%-*.*s %-*.*s %*.*s", addrwidth, addrwidth, host_buf,
706		    llwidth, llwidth, ether_str(sdl), ifwidth, ifwidth, ifname);
707
708		/* Print neighbor discovery specific informations */
709		nbi = getnbrinfo(&sin->sin6_addr, sdl->sdl_index, 1);
710		if (nbi) {
711			if (nbi->expire > time.tv_sec) {
712				printf(" %-9.9s",
713				    sec2str(nbi->expire - time.tv_sec));
714			} else if (nbi->expire == 0)
715				printf(" %-9.9s", "permanent");
716			else
717				printf(" %-9.9s", "expired");
718
719			switch (nbi->state) {
720			case ND6_LLINFO_NOSTATE:
721				 printf(" N");
722				 break;
723#ifdef ND6_LLINFO_WAITDELETE
724			case ND6_LLINFO_WAITDELETE:
725				 printf(" W");
726				 break;
727#endif
728			case ND6_LLINFO_INCOMPLETE:
729				 printf(" I");
730				 break;
731			case ND6_LLINFO_REACHABLE:
732				 printf(" R");
733				 break;
734			case ND6_LLINFO_STALE:
735				 printf(" S");
736				 break;
737			case ND6_LLINFO_DELAY:
738				 printf(" D");
739				 break;
740			case ND6_LLINFO_PROBE:
741				 printf(" P");
742				 break;
743			default:
744				 printf(" ?");
745				 break;
746			}
747
748			isrouter = nbi->isrouter;
749			prbs = nbi->asked;
750		} else {
751			warnx("failed to get neighbor information");
752			printf("  ");
753		}
754
755		/*
756		 * other flags. R: router, P: proxy, W: ??
757		 */
758		if ((rtm->rtm_addrs & RTA_NETMASK) == 0) {
759			snprintf(flgbuf, sizeof(flgbuf), "%s%s",
760			    isrouter ? "R" : "",
761			    (rtm->rtm_flags & RTF_ANNOUNCE) ? "p" : "");
762		} else {
763			sin = (struct sockaddr_in6 *)
764			    (sdl->sdl_len + (char *)sdl);
765#if 0	/* W and P are mystery even for us */
766			snprintf(flgbuf, sizeof(flgbuf), "%s%s%s%s",
767			    isrouter ? "R" : "",
768			    !IN6_IS_ADDR_UNSPECIFIED(&sin->sin6_addr) ? "P" : "",
769			    (sin->sin6_len != sizeof(struct sockaddr_in6)) ? "W" : "",
770			    (rtm->rtm_flags & RTF_ANNOUNCE) ? "p" : "");
771#else
772			snprintf(flgbuf, sizeof(flgbuf), "%s%s",
773			    isrouter ? "R" : "",
774			    (rtm->rtm_flags & RTF_ANNOUNCE) ? "p" : "");
775#endif
776		}
777		printf(" %s", flgbuf);
778
779		if (prbs)
780			printf(" %d", prbs);
781
782		printf("\n");
783	}
784	if (buf != NULL)
785		free(buf);
786
787	if (repeat) {
788		printf("\n");
789		fflush(stdout);
790		sleep(repeat);
791		goto again;
792	}
793}
794
795static struct in6_nbrinfo *
796getnbrinfo(addr, ifindex, warning)
797	struct in6_addr *addr;
798	int ifindex;
799	int warning;
800{
801	static struct in6_nbrinfo nbi;
802	int s;
803
804	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
805		err(1, "socket");
806
807	bzero(&nbi, sizeof(nbi));
808	if_indextoname(ifindex, nbi.ifname);
809	nbi.addr = *addr;
810	if (ioctl(s, SIOCGNBRINFO_IN6, (caddr_t)&nbi) < 0) {
811		if (warning)
812			warn("ioctl(SIOCGNBRINFO_IN6)");
813		close(s);
814		return(NULL);
815	}
816
817	close(s);
818	return(&nbi);
819}
820
821static char *
822ether_str(struct sockaddr_dl *sdl)
823{
824	static char hbuf[NI_MAXHOST];
825	char *cp;
826
827	if (sdl->sdl_alen == ETHER_ADDR_LEN) {
828		strlcpy(hbuf, ether_ntoa((struct ether_addr *)LLADDR(sdl)),
829		    sizeof(hbuf));
830	} else if (sdl->sdl_alen) {
831		int n = sdl->sdl_nlen > 0 ? sdl->sdl_nlen + 1 : 0;
832		snprintf(hbuf, sizeof(hbuf), "%s", link_ntoa(sdl) + n);
833	} else
834		snprintf(hbuf, sizeof(hbuf), "(incomplete)");
835
836	return(hbuf);
837}
838
839int
840ndp_ether_aton(a, n)
841	char *a;
842	u_char *n;
843{
844	int i, o[6];
845
846	i = sscanf(a, "%x:%x:%x:%x:%x:%x", &o[0], &o[1], &o[2],
847	    &o[3], &o[4], &o[5]);
848	if (i != 6) {
849		fprintf(stderr, "ndp: invalid Ethernet address '%s'\n", a);
850		return (1);
851	}
852	for (i = 0; i < 6; i++)
853		n[i] = o[i];
854	return (0);
855}
856
857void
858usage()
859{
860	printf("usage: ndp [-nt] hostname\n");
861	printf("       ndp [-nt] -a | -c | -p | -r | -H | -P | -R\n");
862	printf("       ndp [-nt] -A wait\n");
863	printf("       ndp [-nt] -d hostname\n");
864	printf("       ndp [-nt] -f filename\n");
865	printf("       ndp [-nt] -i interface [flags...]\n");
866#ifdef SIOCSDEFIFACE_IN6
867	printf("       ndp [-nt] -I [interface|delete]\n");
868#endif
869	printf("       ndp [-nt] -s nodename etheraddr [temp] [proxy]\n");
870	exit(1);
871}
872
873int
874rtmsg(cmd)
875	int cmd;
876{
877	static int seq;
878	int rlen;
879	register struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
880	register char *cp = m_rtmsg.m_space;
881	register int l;
882
883	errno = 0;
884	if (cmd == RTM_DELETE)
885		goto doit;
886	bzero((char *)&m_rtmsg, sizeof(m_rtmsg));
887	rtm->rtm_flags = flags;
888	rtm->rtm_version = RTM_VERSION;
889
890	switch (cmd) {
891	default:
892		fprintf(stderr, "ndp: internal wrong cmd\n");
893		exit(1);
894	case RTM_ADD:
895		rtm->rtm_addrs |= RTA_GATEWAY;
896		if (expire_time) {
897			rtm->rtm_rmx.rmx_expire = expire_time;
898			rtm->rtm_inits = RTV_EXPIRE;
899		}
900		rtm->rtm_flags |= (RTF_HOST | RTF_STATIC | RTF_LLDATA);
901#if 0 /* we don't support ipv6addr/128 type proxying */
902		if (rtm->rtm_flags & RTF_ANNOUNCE) {
903			rtm->rtm_flags &= ~RTF_HOST;
904			rtm->rtm_addrs |= RTA_NETMASK;
905		}
906#endif
907		/* FALLTHROUGH */
908	case RTM_GET:
909		rtm->rtm_addrs |= RTA_DST;
910	}
911
912	NEXTADDR(RTA_DST, sin_m);
913	NEXTADDR(RTA_GATEWAY, sdl_m);
914#if 0 /* we don't support ipv6addr/128 type proxying */
915	memset(&so_mask.sin6_addr, 0xff, sizeof(so_mask.sin6_addr));
916	NEXTADDR(RTA_NETMASK, so_mask);
917#endif
918
919	rtm->rtm_msglen = cp - (char *)&m_rtmsg;
920doit:
921	l = rtm->rtm_msglen;
922	rtm->rtm_seq = ++seq;
923	rtm->rtm_type = cmd;
924	if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) {
925		if (errno != ESRCH || cmd != RTM_DELETE) {
926			err(1, "writing to routing socket");
927			/* NOTREACHED */
928		}
929	}
930	do {
931		l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
932	} while (l > 0 && (rtm->rtm_seq != seq || rtm->rtm_pid != pid));
933	if (l < 0)
934		(void) fprintf(stderr, "ndp: read from routing socket: %s\n",
935		    strerror(errno));
936	return (0);
937}
938
939void
940ifinfo(ifname, argc, argv)
941	char *ifname;
942	int argc;
943	char **argv;
944{
945	struct in6_ndireq nd;
946	int i, s;
947	u_int32_t newflags;
948#ifdef IPV6CTL_USETEMPADDR
949	u_int8_t nullbuf[8];
950#endif
951
952	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
953		err(1, "socket");
954		/* NOTREACHED */
955	}
956	bzero(&nd, sizeof(nd));
957	strlcpy(nd.ifname, ifname, sizeof(nd.ifname));
958	if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
959		err(1, "ioctl(SIOCGIFINFO_IN6)");
960		/* NOTREACHED */
961	}
962#define ND nd.ndi
963	newflags = ND.flags;
964	for (i = 0; i < argc; i++) {
965		int clear = 0;
966		char *cp = argv[i];
967
968		if (*cp == '-') {
969			clear = 1;
970			cp++;
971		}
972
973#define SETFLAG(s, f) \
974	do {\
975		if (strcmp(cp, (s)) == 0) {\
976			if (clear)\
977				newflags &= ~(f);\
978			else\
979				newflags |= (f);\
980		}\
981	} while (0)
982/*
983 * XXX: this macro is not 100% correct, in that it matches "nud" against
984 *      "nudbogus".  But we just let it go since this is minor.
985 */
986#define SETVALUE(f, v) \
987	do { \
988		char *valptr; \
989		unsigned long newval; \
990		v = 0; /* unspecified */ \
991		if (strncmp(cp, f, strlen(f)) == 0) { \
992			valptr = strchr(cp, '='); \
993			if (valptr == NULL) \
994				err(1, "syntax error in %s field", (f)); \
995			errno = 0; \
996			newval = strtoul(++valptr, NULL, 0); \
997			if (errno) \
998				err(1, "syntax error in %s's value", (f)); \
999			v = newval; \
1000		} \
1001	} while (0)
1002
1003		SETFLAG("disabled", ND6_IFF_IFDISABLED);
1004		SETFLAG("nud", ND6_IFF_PERFORMNUD);
1005#ifdef ND6_IFF_ACCEPT_RTADV
1006		SETFLAG("accept_rtadv", ND6_IFF_ACCEPT_RTADV);
1007#endif
1008#ifdef ND6_IFF_AUTO_LINKLOCAL
1009		SETFLAG("auto_linklocal", ND6_IFF_AUTO_LINKLOCAL);
1010#endif
1011#ifdef ND6_IFF_PREFER_SOURCE
1012		SETFLAG("prefer_source", ND6_IFF_PREFER_SOURCE);
1013#endif
1014		SETVALUE("basereachable", ND.basereachable);
1015		SETVALUE("retrans", ND.retrans);
1016		SETVALUE("curhlim", ND.chlim);
1017
1018		ND.flags = newflags;
1019		if (ioctl(s, SIOCSIFINFO_IN6, (caddr_t)&nd) < 0) {
1020			err(1, "ioctl(SIOCSIFINFO_IN6)");
1021			/* NOTREACHED */
1022		}
1023#undef SETFLAG
1024#undef SETVALUE
1025	}
1026
1027	if (!ND.initialized) {
1028		errx(1, "%s: not initialized yet", ifname);
1029		/* NOTREACHED */
1030	}
1031
1032	if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
1033		err(1, "ioctl(SIOCGIFINFO_IN6)");
1034		/* NOTREACHED */
1035	}
1036	printf("linkmtu=%d", ND.linkmtu);
1037	printf(", maxmtu=%d", ND.maxmtu);
1038	printf(", curhlim=%d", ND.chlim);
1039	printf(", basereachable=%ds%dms",
1040	    ND.basereachable / 1000, ND.basereachable % 1000);
1041	printf(", reachable=%ds", ND.reachable);
1042	printf(", retrans=%ds%dms", ND.retrans / 1000, ND.retrans % 1000);
1043#ifdef IPV6CTL_USETEMPADDR
1044	memset(nullbuf, 0, sizeof(nullbuf));
1045	if (memcmp(nullbuf, ND.randomid, sizeof(nullbuf)) != 0) {
1046		int j;
1047		u_int8_t *rbuf;
1048
1049		for (i = 0; i < 3; i++) {
1050			switch (i) {
1051			case 0:
1052				printf("\nRandom seed(0): ");
1053				rbuf = ND.randomseed0;
1054				break;
1055			case 1:
1056				printf("\nRandom seed(1): ");
1057				rbuf = ND.randomseed1;
1058				break;
1059			case 2:
1060				printf("\nRandom ID:      ");
1061				rbuf = ND.randomid;
1062				break;
1063			default:
1064				errx(1, "impossible case for tempaddr display");
1065			}
1066			for (j = 0; j < 8; j++)
1067				printf("%02x", rbuf[j]);
1068		}
1069	}
1070#endif
1071	if (ND.flags) {
1072		printf("\nFlags: ");
1073#ifdef ND6_IFF_IFDISABLED
1074		if ((ND.flags & ND6_IFF_IFDISABLED))
1075			printf("disabled ");
1076#endif
1077		if ((ND.flags & ND6_IFF_PERFORMNUD))
1078			printf("nud ");
1079#ifdef ND6_IFF_ACCEPT_RTADV
1080		if ((ND.flags & ND6_IFF_ACCEPT_RTADV))
1081			printf("accept_rtadv ");
1082#endif
1083#ifdef ND6_IFF_AUTO_LINKLOCAL
1084		if ((ND.flags & ND6_IFF_AUTO_LINKLOCAL))
1085			printf("auto_linklocal ");
1086#endif
1087#ifdef ND6_IFF_PREFER_SOURCE
1088		if ((ND.flags & ND6_IFF_PREFER_SOURCE))
1089			printf("prefer_source ");
1090#endif
1091	}
1092	putc('\n', stdout);
1093#undef ND
1094
1095	close(s);
1096}
1097
1098#ifndef ND_RA_FLAG_RTPREF_MASK	/* XXX: just for compilation on *BSD release */
1099#define ND_RA_FLAG_RTPREF_MASK	0x18 /* 00011000 */
1100#endif
1101
1102void
1103rtrlist()
1104{
1105#ifdef ICMPV6CTL_ND6_DRLIST
1106	int mib[] = { CTL_NET, PF_INET6, IPPROTO_ICMPV6, ICMPV6CTL_ND6_DRLIST };
1107	char *buf;
1108	struct in6_defrouter *p, *ep;
1109	size_t l;
1110	struct timeval time;
1111
1112	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0) {
1113		err(1, "sysctl(ICMPV6CTL_ND6_DRLIST)");
1114		/*NOTREACHED*/
1115	}
1116	if (l == 0)
1117		return;
1118	buf = malloc(l);
1119	if (!buf) {
1120		err(1, "malloc");
1121		/*NOTREACHED*/
1122	}
1123	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
1124		err(1, "sysctl(ICMPV6CTL_ND6_DRLIST)");
1125		/*NOTREACHED*/
1126	}
1127
1128	ep = (struct in6_defrouter *)(buf + l);
1129	for (p = (struct in6_defrouter *)buf; p < ep; p++) {
1130		int rtpref;
1131
1132		if (getnameinfo((struct sockaddr *)&p->rtaddr,
1133		    p->rtaddr.sin6_len, host_buf, sizeof(host_buf), NULL, 0,
1134		    (nflag ? NI_NUMERICHOST : 0)) != 0)
1135			strlcpy(host_buf, "?", sizeof(host_buf));
1136
1137		printf("%s if=%s", host_buf,
1138		    if_indextoname(p->if_index, ifix_buf));
1139		printf(", flags=%s%s",
1140		    p->flags & ND_RA_FLAG_MANAGED ? "M" : "",
1141		    p->flags & ND_RA_FLAG_OTHER   ? "O" : "");
1142		rtpref = ((p->flags & ND_RA_FLAG_RTPREF_MASK) >> 3) & 0xff;
1143		printf(", pref=%s", rtpref_str[rtpref]);
1144
1145		gettimeofday(&time, 0);
1146		if (p->expire == 0)
1147			printf(", expire=Never\n");
1148		else
1149			printf(", expire=%s\n",
1150			    sec2str(p->expire - time.tv_sec));
1151	}
1152	free(buf);
1153#else
1154	struct in6_drlist dr;
1155	int s, i;
1156	struct timeval time;
1157
1158	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1159		err(1, "socket");
1160		/* NOTREACHED */
1161	}
1162	bzero(&dr, sizeof(dr));
1163	strlcpy(dr.ifname, "lo0", sizeof(dr.ifname)); /* dummy */
1164	if (ioctl(s, SIOCGDRLST_IN6, (caddr_t)&dr) < 0) {
1165		err(1, "ioctl(SIOCGDRLST_IN6)");
1166		/* NOTREACHED */
1167	}
1168#define DR dr.defrouter[i]
1169	for (i = 0 ; DR.if_index && i < DRLSTSIZ ; i++) {
1170		struct sockaddr_in6 sin6;
1171
1172		bzero(&sin6, sizeof(sin6));
1173		sin6.sin6_family = AF_INET6;
1174		sin6.sin6_len = sizeof(sin6);
1175		sin6.sin6_addr = DR.rtaddr;
1176		getnameinfo((struct sockaddr *)&sin6, sin6.sin6_len, host_buf,
1177		    sizeof(host_buf), NULL, 0,
1178		    (nflag ? NI_NUMERICHOST : 0));
1179
1180		printf("%s if=%s", host_buf,
1181		    if_indextoname(DR.if_index, ifix_buf));
1182		printf(", flags=%s%s",
1183		    DR.flags & ND_RA_FLAG_MANAGED ? "M" : "",
1184		    DR.flags & ND_RA_FLAG_OTHER   ? "O" : "");
1185		gettimeofday(&time, 0);
1186		if (DR.expire == 0)
1187			printf(", expire=Never\n");
1188		else
1189			printf(", expire=%s\n",
1190			    sec2str(DR.expire - time.tv_sec));
1191	}
1192#undef DR
1193	close(s);
1194#endif
1195}
1196
1197void
1198plist()
1199{
1200#ifdef ICMPV6CTL_ND6_PRLIST
1201	int mib[] = { CTL_NET, PF_INET6, IPPROTO_ICMPV6, ICMPV6CTL_ND6_PRLIST };
1202	char *buf;
1203	struct in6_prefix *p, *ep, *n;
1204	struct sockaddr_in6 *advrtr;
1205	size_t l;
1206	struct timeval time;
1207	const int niflags = NI_NUMERICHOST;
1208	int ninflags = nflag ? NI_NUMERICHOST : 0;
1209	char namebuf[NI_MAXHOST];
1210
1211	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0) {
1212		err(1, "sysctl(ICMPV6CTL_ND6_PRLIST)");
1213		/*NOTREACHED*/
1214	}
1215	buf = malloc(l);
1216	if (!buf) {
1217		err(1, "malloc");
1218		/*NOTREACHED*/
1219	}
1220	if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
1221		err(1, "sysctl(ICMPV6CTL_ND6_PRLIST)");
1222		/*NOTREACHED*/
1223	}
1224
1225	ep = (struct in6_prefix *)(buf + l);
1226	for (p = (struct in6_prefix *)buf; p < ep; p = n) {
1227		advrtr = (struct sockaddr_in6 *)(p + 1);
1228		n = (struct in6_prefix *)&advrtr[p->advrtrs];
1229
1230		if (getnameinfo((struct sockaddr *)&p->prefix,
1231		    p->prefix.sin6_len, namebuf, sizeof(namebuf),
1232		    NULL, 0, niflags) != 0)
1233			strlcpy(namebuf, "?", sizeof(namebuf));
1234		printf("%s/%d if=%s\n", namebuf, p->prefixlen,
1235		    if_indextoname(p->if_index, ifix_buf));
1236
1237		gettimeofday(&time, 0);
1238		/*
1239		 * meaning of fields, especially flags, is very different
1240		 * by origin.  notify the difference to the users.
1241		 */
1242		printf("flags=%s%s%s%s%s",
1243		    p->raflags.onlink ? "L" : "",
1244		    p->raflags.autonomous ? "A" : "",
1245		    (p->flags & NDPRF_ONLINK) != 0 ? "O" : "",
1246		    (p->flags & NDPRF_DETACHED) != 0 ? "D" : "",
1247#ifdef NDPRF_HOME
1248		    (p->flags & NDPRF_HOME) != 0 ? "H" : ""
1249#else
1250		    ""
1251#endif
1252		    );
1253		if (p->vltime == ND6_INFINITE_LIFETIME)
1254			printf(" vltime=infinity");
1255		else
1256			printf(" vltime=%lu", (unsigned long)p->vltime);
1257		if (p->pltime == ND6_INFINITE_LIFETIME)
1258			printf(", pltime=infinity");
1259		else
1260			printf(", pltime=%lu", (unsigned long)p->pltime);
1261		if (p->expire == 0)
1262			printf(", expire=Never");
1263		else if (p->expire >= time.tv_sec)
1264			printf(", expire=%s",
1265			    sec2str(p->expire - time.tv_sec));
1266		else
1267			printf(", expired");
1268		printf(", ref=%d", p->refcnt);
1269		printf("\n");
1270		/*
1271		 * "advertising router" list is meaningful only if the prefix
1272		 * information is from RA.
1273		 */
1274		if (p->advrtrs) {
1275			int j;
1276			struct sockaddr_in6 *sin6;
1277
1278			sin6 = advrtr;
1279			printf("  advertised by\n");
1280			for (j = 0; j < p->advrtrs; j++) {
1281				struct in6_nbrinfo *nbi;
1282
1283				if (getnameinfo((struct sockaddr *)sin6,
1284				    sin6->sin6_len, namebuf, sizeof(namebuf),
1285				    NULL, 0, ninflags) != 0)
1286					strlcpy(namebuf, "?", sizeof(namebuf));
1287				printf("    %s", namebuf);
1288
1289				nbi = getnbrinfo(&sin6->sin6_addr,
1290				    p->if_index, 0);
1291				if (nbi) {
1292					switch (nbi->state) {
1293					case ND6_LLINFO_REACHABLE:
1294					case ND6_LLINFO_STALE:
1295					case ND6_LLINFO_DELAY:
1296					case ND6_LLINFO_PROBE:
1297						printf(" (reachable)\n");
1298						break;
1299					default:
1300						printf(" (unreachable)\n");
1301					}
1302				} else
1303					printf(" (no neighbor state)\n");
1304				sin6++;
1305			}
1306		} else
1307			printf("  No advertising router\n");
1308	}
1309	free(buf);
1310#else
1311	struct in6_prlist pr;
1312	int s, i;
1313	struct timeval time;
1314
1315	gettimeofday(&time, 0);
1316
1317	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
1318		err(1, "socket");
1319		/* NOTREACHED */
1320	}
1321	bzero(&pr, sizeof(pr));
1322	strlcpy(pr.ifname, "lo0", sizeof(pr.ifname)); /* dummy */
1323	if (ioctl(s, SIOCGPRLST_IN6, (caddr_t)&pr) < 0) {
1324		err(1, "ioctl(SIOCGPRLST_IN6)");
1325		/* NOTREACHED */
1326	}
1327#define PR pr.prefix[i]
1328	for (i = 0; PR.if_index && i < PRLSTSIZ ; i++) {
1329		struct sockaddr_in6 p6;
1330		char namebuf[NI_MAXHOST];
1331		int niflags;
1332
1333#ifdef NDPRF_ONLINK
1334		p6 = PR.prefix;
1335#else
1336		memset(&p6, 0, sizeof(p6));
1337		p6.sin6_family = AF_INET6;
1338		p6.sin6_len = sizeof(p6);
1339		p6.sin6_addr = PR.prefix;
1340#endif
1341
1342		/*
1343		 * copy link index to sin6_scope_id field.
1344		 * XXX: KAME specific.
1345		 */
1346		if (IN6_IS_ADDR_LINKLOCAL(&p6.sin6_addr)) {
1347			u_int16_t linkid;
1348
1349			memcpy(&linkid, &p6.sin6_addr.s6_addr[2],
1350			    sizeof(linkid));
1351			linkid = ntohs(linkid);
1352			p6.sin6_scope_id = linkid;
1353			p6.sin6_addr.s6_addr[2] = 0;
1354			p6.sin6_addr.s6_addr[3] = 0;
1355		}
1356
1357		niflags = NI_NUMERICHOST;
1358		if (getnameinfo((struct sockaddr *)&p6,
1359		    sizeof(p6), namebuf, sizeof(namebuf),
1360		    NULL, 0, niflags)) {
1361			warnx("getnameinfo failed");
1362			continue;
1363		}
1364		printf("%s/%d if=%s\n", namebuf, PR.prefixlen,
1365		    if_indextoname(PR.if_index, ifix_buf));
1366
1367		gettimeofday(&time, 0);
1368		/*
1369		 * meaning of fields, especially flags, is very different
1370		 * by origin.  notify the difference to the users.
1371		 */
1372#if 0
1373		printf("  %s",
1374		    PR.origin == PR_ORIG_RA ? "" : "advertise: ");
1375#endif
1376#ifdef NDPRF_ONLINK
1377		printf("flags=%s%s%s%s%s",
1378		    PR.raflags.onlink ? "L" : "",
1379		    PR.raflags.autonomous ? "A" : "",
1380		    (PR.flags & NDPRF_ONLINK) != 0 ? "O" : "",
1381		    (PR.flags & NDPRF_DETACHED) != 0 ? "D" : "",
1382#ifdef NDPRF_HOME
1383		    (PR.flags & NDPRF_HOME) != 0 ? "H" : ""
1384#else
1385		    ""
1386#endif
1387		    );
1388#else
1389		printf("flags=%s%s",
1390		    PR.raflags.onlink ? "L" : "",
1391		    PR.raflags.autonomous ? "A" : "");
1392#endif
1393		if (PR.vltime == ND6_INFINITE_LIFETIME)
1394			printf(" vltime=infinity");
1395		else
1396			printf(" vltime=%lu", PR.vltime);
1397		if (PR.pltime == ND6_INFINITE_LIFETIME)
1398			printf(", pltime=infinity");
1399		else
1400			printf(", pltime=%lu", PR.pltime);
1401		if (PR.expire == 0)
1402			printf(", expire=Never");
1403		else if (PR.expire >= time.tv_sec)
1404			printf(", expire=%s",
1405			    sec2str(PR.expire - time.tv_sec));
1406		else
1407			printf(", expired");
1408#ifdef NDPRF_ONLINK
1409		printf(", ref=%d", PR.refcnt);
1410#endif
1411#if 0
1412		switch (PR.origin) {
1413		case PR_ORIG_RA:
1414			printf(", origin=RA");
1415			break;
1416		case PR_ORIG_RR:
1417			printf(", origin=RR");
1418			break;
1419		case PR_ORIG_STATIC:
1420			printf(", origin=static");
1421			break;
1422		case PR_ORIG_KERNEL:
1423			printf(", origin=kernel");
1424			break;
1425		default:
1426			printf(", origin=?");
1427			break;
1428		}
1429#endif
1430		printf("\n");
1431		/*
1432		 * "advertising router" list is meaningful only if the prefix
1433		 * information is from RA.
1434		 */
1435		if (0 &&	/* prefix origin is almost obsolted */
1436		    PR.origin != PR_ORIG_RA)
1437			;
1438		else if (PR.advrtrs) {
1439			int j;
1440			printf("  advertised by\n");
1441			for (j = 0; j < PR.advrtrs; j++) {
1442				struct sockaddr_in6 sin6;
1443				struct in6_nbrinfo *nbi;
1444
1445				bzero(&sin6, sizeof(sin6));
1446				sin6.sin6_family = AF_INET6;
1447				sin6.sin6_len = sizeof(sin6);
1448				sin6.sin6_addr = PR.advrtr[j];
1449				sin6.sin6_scope_id = PR.if_index; /* XXX */
1450				getnameinfo((struct sockaddr *)&sin6,
1451				    sin6.sin6_len, host_buf,
1452				    sizeof(host_buf), NULL, 0,
1453				    (nflag ? NI_NUMERICHOST : 0));
1454				printf("    %s", host_buf);
1455
1456				nbi = getnbrinfo(&sin6.sin6_addr,
1457				    PR.if_index, 0);
1458				if (nbi) {
1459					switch (nbi->state) {
1460					case ND6_LLINFO_REACHABLE:
1461					case ND6_LLINFO_STALE:
1462					case ND6_LLINFO_DELAY:
1463					case ND6_LLINFO_PROBE:
1464						 printf(" (reachable)\n");
1465						 break;
1466					default:
1467						 printf(" (unreachable)\n");
1468					}
1469				} else
1470					printf(" (no neighbor state)\n");
1471			}
1472			if (PR.advrtrs > DRLSTSIZ)
1473				printf("    and %d routers\n",
1474				    PR.advrtrs - DRLSTSIZ);
1475		} else
1476			printf("  No advertising router\n");
1477	}
1478#undef PR
1479	close(s);
1480#endif
1481}
1482
1483void
1484pfx_flush()
1485{
1486	char dummyif[IFNAMSIZ+8];
1487	int s;
1488
1489	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1490		err(1, "socket");
1491	strlcpy(dummyif, "lo0", sizeof(dummyif)); /* dummy */
1492	if (ioctl(s, SIOCSPFXFLUSH_IN6, (caddr_t)&dummyif) < 0)
1493		err(1, "ioctl(SIOCSPFXFLUSH_IN6)");
1494}
1495
1496void
1497rtr_flush()
1498{
1499	char dummyif[IFNAMSIZ+8];
1500	int s;
1501
1502	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1503		err(1, "socket");
1504	strlcpy(dummyif, "lo0", sizeof(dummyif)); /* dummy */
1505	if (ioctl(s, SIOCSRTRFLUSH_IN6, (caddr_t)&dummyif) < 0)
1506		err(1, "ioctl(SIOCSRTRFLUSH_IN6)");
1507
1508	close(s);
1509}
1510
1511void
1512harmonize_rtr()
1513{
1514	char dummyif[IFNAMSIZ+8];
1515	int s;
1516
1517	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1518		err(1, "socket");
1519	strlcpy(dummyif, "lo0", sizeof(dummyif)); /* dummy */
1520	if (ioctl(s, SIOCSNDFLUSH_IN6, (caddr_t)&dummyif) < 0)
1521		err(1, "ioctl(SIOCSNDFLUSH_IN6)");
1522
1523	close(s);
1524}
1525
1526#ifdef SIOCSDEFIFACE_IN6	/* XXX: check SIOCGDEFIFACE_IN6 as well? */
1527static void
1528setdefif(ifname)
1529	char *ifname;
1530{
1531	struct in6_ndifreq ndifreq;
1532	unsigned int ifindex;
1533
1534	if (strcasecmp(ifname, "delete") == 0)
1535		ifindex = 0;
1536	else {
1537		if ((ifindex = if_nametoindex(ifname)) == 0)
1538			err(1, "failed to resolve i/f index for %s", ifname);
1539	}
1540
1541	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1542		err(1, "socket");
1543
1544	strlcpy(ndifreq.ifname, "lo0", sizeof(ndifreq.ifname)); /* dummy */
1545	ndifreq.ifindex = ifindex;
1546
1547	if (ioctl(s, SIOCSDEFIFACE_IN6, (caddr_t)&ndifreq) < 0)
1548		err(1, "ioctl(SIOCSDEFIFACE_IN6)");
1549
1550	close(s);
1551}
1552
1553static void
1554getdefif()
1555{
1556	struct in6_ndifreq ndifreq;
1557	char ifname[IFNAMSIZ+8];
1558
1559	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1560		err(1, "socket");
1561
1562	memset(&ndifreq, 0, sizeof(ndifreq));
1563	strlcpy(ndifreq.ifname, "lo0", sizeof(ndifreq.ifname)); /* dummy */
1564
1565	if (ioctl(s, SIOCGDEFIFACE_IN6, (caddr_t)&ndifreq) < 0)
1566		err(1, "ioctl(SIOCGDEFIFACE_IN6)");
1567
1568	if (ndifreq.ifindex == 0)
1569		printf("No default interface.\n");
1570	else {
1571		if ((if_indextoname(ndifreq.ifindex, ifname)) == NULL)
1572			err(1, "failed to resolve ifname for index %lu",
1573			    ndifreq.ifindex);
1574		printf("ND default interface = %s\n", ifname);
1575	}
1576
1577	close(s);
1578}
1579#endif
1580
1581static char *
1582sec2str(total)
1583	time_t total;
1584{
1585	static char result[256];
1586	int days, hours, mins, secs;
1587	int first = 1;
1588	char *p = result;
1589	char *ep = &result[sizeof(result)];
1590	int n;
1591
1592	days = total / 3600 / 24;
1593	hours = (total / 3600) % 24;
1594	mins = (total / 60) % 60;
1595	secs = total % 60;
1596
1597	if (days) {
1598		first = 0;
1599		n = snprintf(p, ep - p, "%dd", days);
1600		if (n < 0 || n >= ep - p)
1601			return "?";
1602		p += n;
1603	}
1604	if (!first || hours) {
1605		first = 0;
1606		n = snprintf(p, ep - p, "%dh", hours);
1607		if (n < 0 || n >= ep - p)
1608			return "?";
1609		p += n;
1610	}
1611	if (!first || mins) {
1612		first = 0;
1613		n = snprintf(p, ep - p, "%dm", mins);
1614		if (n < 0 || n >= ep - p)
1615			return "?";
1616		p += n;
1617	}
1618	snprintf(p, ep - p, "%ds", secs);
1619
1620	return(result);
1621}
1622
1623/*
1624 * Print the timestamp
1625 * from tcpdump/util.c
1626 */
1627static void
1628ts_print(tvp)
1629	const struct timeval *tvp;
1630{
1631	int s;
1632
1633	/* Default */
1634	s = (tvp->tv_sec + thiszone) % 86400;
1635	(void)printf("%02d:%02d:%02d.%06u ",
1636	    s / 3600, (s % 3600) / 60, s % 60, (u_int32_t)tvp->tv_usec);
1637}
1638
1639#undef NEXTADDR
1640