xref: /openbsd-src/usr.sbin/ndp/ndp.c (revision b99ef4df7fac99f3475b694d6cd4990521c99ae6)
1 /*	$OpenBSD: ndp.c,v 1.102 2021/01/24 08:57:10 florian Exp $	*/
2 /*	$KAME: ndp.c,v 1.101 2002/07/17 08:46:33 itojun Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 /*
33  * Copyright (c) 1984, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * This code is derived from software contributed to Berkeley by
37  * Sun Microsystems, Inc.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  * 3. Neither the name of the University nor the names of its contributors
48  *    may be used to endorse or promote products derived from this software
49  *    without specific prior written permission.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61  * SUCH DAMAGE.
62  */
63 
64 /*
65  * Based on:
66  * "@(#) Copyright (c) 1984, 1993\n\
67  *	The Regents of the University of California.  All rights reserved.\n";
68  *
69  * "@(#)arp.c	8.2 (Berkeley) 1/2/94";
70  */
71 
72 /*
73  * ndp - display, set, delete and flush neighbor cache
74  */
75 
76 
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 
90 #include <netinet/icmp6.h>
91 #include <netinet6/in6_var.h>
92 #include <netinet6/nd6.h>
93 
94 #include <arpa/inet.h>
95 
96 #include <stdio.h>
97 #include <errno.h>
98 #include <fcntl.h>
99 #include <netdb.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <limits.h>
104 #include <err.h>
105 
106 /* packing rule for routing socket */
107 #define ROUNDUP(a) \
108 	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
109 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
110 
111 static pid_t pid;
112 static int nflag;
113 static int tflag;
114 static int rtsock = -1;
115 static int repeat = 0;
116 
117 char host_buf[NI_MAXHOST];		/* getnameinfo() */
118 char ifix_buf[IFNAMSIZ];		/* if_indextoname() */
119 
120 int file(char *);
121 void getsocket(void);
122 int parse_host(const char *, struct sockaddr_in6 *);
123 int set(int, char **);
124 void get(const char *);
125 int delete(const char *);
126 void dump(struct sockaddr_in6 *, int);
127 static struct in6_nbrinfo *getnbrinfo(struct in6_addr *, int, int);
128 static char *ether_str(struct sockaddr_dl *);
129 int ndp_ether_aton(const char *, u_char *);
130 void usage(void);
131 int rtmsg(int);
132 int rtget(struct sockaddr_in6 **, struct sockaddr_dl **);
133 void ifinfo(const char *);
134 static char *sec2str(time_t);
135 static void ts_print(const struct timeval *);
136 static int rdomain;
137 
138 int
139 main(int argc, char *argv[])
140 {
141 	int		 ch;
142 	int		 mode = 0;
143 	char		*arg = NULL;
144 	const char	*errstr;
145 
146 	pid = getpid();
147 	rdomain = getrtable();
148 	while ((ch = getopt(argc, argv, "acd:f:i:nstA:V:")) != -1) {
149 		switch (ch) {
150 		case 'a':
151 		case 'c':
152 		case 'p':
153 		case 'r':
154 		case 'P':
155 		case 's':
156 			if (mode) {
157 				usage();
158 			}
159 			mode = ch;
160 			arg = NULL;
161 			break;
162 		case 'd':
163 		case 'f':
164 		case 'i' :
165 			if (mode) {
166 				usage();
167 			}
168 			mode = ch;
169 			arg = optarg;
170 			break;
171 		case 'n':
172 			nflag = 1;
173 			break;
174 		case 't':
175 			tflag = 1;
176 			break;
177 		case 'A':
178 			if (mode) {
179 				usage();
180 			}
181 			mode = 'a';
182 			repeat = strtonum(optarg, 1, INT_MAX, &errstr);
183 			if (errstr) {
184 				usage();
185 			}
186 			break;
187 		case 'V':
188 			rdomain = strtonum(optarg, 0, RT_TABLEID_MAX, &errstr);
189 			if (errstr != NULL) {
190 				warn("bad rdomain: %s", errstr);
191 				usage();
192 			}
193 			break;
194 		default:
195 			usage();
196 		}
197 	}
198 	argc -= optind;
199 	argv += optind;
200 
201 	switch (mode) {
202 	case 'a':
203 	case 'c':
204 		if (argc != 0) {
205 			usage();
206 		}
207 		dump(NULL, mode == 'c');
208 		break;
209 	case 'd':
210 		if (argc != 0) {
211 			usage();
212 		}
213 		delete(arg);
214 		break;
215 	case 'f':
216 		if (argc != 0)
217 			usage();
218 		file(arg);
219 		break;
220 	case 'i':
221 		if (argc != 0)
222 			usage();
223 		ifinfo(arg);
224 		break;
225 	case 's':
226 		if (argc < 2 || argc > 4)
227 			usage();
228 		exit(set(argc, argv) ? 1 : 0);
229 	case 0:
230 		if (argc != 1) {
231 			usage();
232 		}
233 		get(argv[0]);
234 		break;
235 	}
236 	exit(0);
237 }
238 
239 /*
240  * Process a file to set standard ndp entries
241  */
242 int
243 file(char *name)
244 {
245 	FILE *fp;
246 	int i, retval;
247 	char line[100], arg[5][50], *args[5];
248 
249 	if ((fp = fopen(name, "r")) == NULL) {
250 		err(1, "cannot open %s", name);
251 	}
252 	args[0] = &arg[0][0];
253 	args[1] = &arg[1][0];
254 	args[2] = &arg[2][0];
255 	args[3] = &arg[3][0];
256 	args[4] = &arg[4][0];
257 	retval = 0;
258 	while (fgets(line, sizeof(line), fp) != NULL) {
259 		i = sscanf(line, "%49s %49s %49s %49s %49s",
260 		    arg[0], arg[1], arg[2], arg[3], arg[4]);
261 		if (i < 2) {
262 			warnx("bad line: %s", line);
263 			retval = 1;
264 			continue;
265 		}
266 		if (set(i, args))
267 			retval = 1;
268 	}
269 	fclose(fp);
270 	return (retval);
271 }
272 
273 void
274 getsocket(void)
275 {
276 	socklen_t len = sizeof(rdomain);
277 
278 	if (rtsock >= 0)
279 		return;
280 	rtsock = socket(AF_ROUTE, SOCK_RAW, 0);
281 	if (rtsock == -1)
282 		err(1, "routing socket");
283 	if (setsockopt(rtsock, AF_ROUTE, ROUTE_TABLEFILTER, &rdomain, len) == -1)
284 		err(1, "ROUTE_TABLEFILTER");
285 
286 	if (pledge("stdio dns", NULL) == -1)
287 		err(1, "pledge");
288 }
289 
290 int
291 parse_host(const char *host, struct sockaddr_in6 *sin6)
292 {
293 	struct addrinfo hints, *res;
294 	int gai_error;
295 
296 	bzero(&hints, sizeof(hints));
297 	hints.ai_family = AF_INET6;
298 	if (nflag)
299 		hints.ai_flags = AI_NUMERICHOST;
300 
301 	gai_error = getaddrinfo(host, NULL, &hints, &res);
302 	if (gai_error) {
303 		warnx("%s: %s", host, gai_strerror(gai_error));
304 		return 1;
305 	}
306 	*sin6 = *(struct sockaddr_in6 *)res->ai_addr;
307 	freeaddrinfo(res);
308 	return 0;
309 }
310 
311 struct	sockaddr_in6 so_mask = {sizeof(so_mask), AF_INET6 };
312 struct	sockaddr_in6 blank_sin = {sizeof(blank_sin), AF_INET6 }, sin_m;
313 struct	sockaddr_dl blank_sdl = {sizeof(blank_sdl), AF_LINK }, sdl_m;
314 struct	sockaddr_dl ifp_m = { sizeof(ifp_m), AF_LINK };
315 time_t	expire_time;
316 int	flags, found_entry;
317 struct	{
318 	struct	rt_msghdr m_rtm;
319 	char	m_space[512];
320 }	m_rtmsg;
321 
322 /*
323  * Set an individual neighbor cache entry
324  */
325 int
326 set(int argc, char *argv[])
327 {
328 	struct sockaddr_in6 *sin = &sin_m;
329 	struct sockaddr_dl *sdl;
330 	struct rt_msghdr *rtm = &(m_rtmsg.m_rtm);
331 	u_char *ea;
332 	const char *host = argv[0], *eaddr = argv[1];
333 
334 	getsocket();
335 	argc -= 2;
336 	argv += 2;
337 	sdl_m = blank_sdl;
338 	sin_m = blank_sin;
339 
340 	if (parse_host(host, sin))
341 		return 1;
342 	ea = (u_char *)LLADDR(&sdl_m);
343 	if (ndp_ether_aton(eaddr, ea) == 0)
344 		sdl_m.sdl_alen = 6;
345 	expire_time = 0;
346 	flags = 0;
347 	while (argc-- > 0) {
348 		if (strncmp(argv[0], "temp", 4) == 0) {
349 			struct timeval now;
350 
351 			gettimeofday(&now, 0);
352 			expire_time = now.tv_sec + 20 * 60;
353 		} else if (strncmp(argv[0], "proxy", 5) == 0)
354 			flags |= RTF_ANNOUNCE;
355 		argv++;
356 	}
357 
358 	if (rtget(&sin, &sdl)) {
359 		errx(1, "RTM_GET(%s) failed", host);
360 	}
361 
362 	if (IN6_ARE_ADDR_EQUAL(&sin->sin6_addr, &sin_m.sin6_addr) &&
363 	    sin->sin6_scope_id == sin_m.sin6_scope_id) {
364 		if (sdl->sdl_family == AF_LINK &&
365 		    (rtm->rtm_flags & RTF_LLINFO) &&
366 		    !(rtm->rtm_flags & RTF_GATEWAY)) {
367 			switch (sdl->sdl_type) {
368 			case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023:
369 			case IFT_ISO88024: case IFT_ISO88025:
370 				goto overwrite;
371 			}
372 		}
373 		/*
374 		 * IPv4 arp command retries with sin_other = SIN_PROXY here.
375 		 */
376 		warnx("set: cannot configure a new entry");
377 		return 1;
378 	}
379 
380 overwrite:
381 	if (sdl->sdl_family != AF_LINK) {
382 		printf("cannot intuit interface index and type for %s\n", host);
383 		return (1);
384 	}
385 	sdl_m.sdl_type = sdl->sdl_type;
386 	sdl_m.sdl_index = sdl->sdl_index;
387 	return (rtmsg(RTM_ADD));
388 }
389 
390 /*
391  * Display an individual neighbor cache entry
392  */
393 void
394 get(const char *host)
395 {
396 	struct sockaddr_in6 *sin = &sin_m;
397 
398 	sin_m = blank_sin;
399 	if (parse_host(host, sin))
400 		return;
401 
402 	dump(sin, 0);
403 	if (found_entry == 0) {
404 		getnameinfo((struct sockaddr *)sin, sin->sin6_len, host_buf,
405 		    sizeof(host_buf), NULL ,0,
406 		    (nflag ? NI_NUMERICHOST : 0));
407 		printf("%s (%s) -- no entry\n", host, host_buf);
408 		exit(1);
409 	}
410 }
411 
412 /*
413  * Delete a neighbor cache entry
414  */
415 int
416 delete(const char *host)
417 {
418 	struct sockaddr_in6 *sin = &sin_m;
419 	struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
420 	struct sockaddr_dl *sdl;
421 
422 	getsocket();
423 	sin_m = blank_sin;
424 	if (parse_host(host, sin))
425 		return 1;
426 	if (rtget(&sin, &sdl)) {
427 		errx(1, "RTM_GET(%s) failed", host);
428 	}
429 
430 	if (IN6_ARE_ADDR_EQUAL(&sin->sin6_addr, &sin_m.sin6_addr) &&
431 	    sin->sin6_scope_id == sin_m.sin6_scope_id) {
432 		if (sdl->sdl_family == AF_LINK && rtm->rtm_flags & RTF_LLINFO) {
433 			if (rtm->rtm_flags & RTF_LOCAL)
434 				return (0);
435 			if (!(rtm->rtm_flags & RTF_GATEWAY))
436 				goto delete;
437 		}
438 		/*
439 		 * IPv4 arp command retries with sin_other = SIN_PROXY here.
440 		 */
441 		warnx("delete: cannot delete non-NDP entry");
442 		return 1;
443 	}
444 
445 delete:
446 	if (sdl->sdl_family != AF_LINK) {
447 		printf("cannot locate %s\n", host);
448 		return (1);
449 	}
450 	if (rtmsg(RTM_DELETE) == 0) {
451 		getnameinfo((struct sockaddr *)sin,
452 		    sin->sin6_len, host_buf,
453 		    sizeof(host_buf), NULL, 0,
454 		    (nflag ? NI_NUMERICHOST : 0));
455 		printf("%s (%s) deleted\n", host, host_buf);
456 	}
457 
458 	return 0;
459 }
460 
461 #define W_ADDR	36
462 #define W_LL	17
463 #define W_IF	7
464 
465 /*
466  * Dump the entire neighbor cache
467  */
468 void
469 dump(struct sockaddr_in6 *addr, int cflag)
470 {
471 	int mib[7];
472 	size_t needed;
473 	char *lim, *buf = NULL, *next;
474 	struct rt_msghdr *rtm;
475 	struct sockaddr_in6 *sin;
476 	struct sockaddr_dl *sdl;
477 	struct in6_nbrinfo *nbi;
478 	struct timeval now;
479 	int addrwidth;
480 	int llwidth;
481 	int ifwidth;
482 	char *ifname;
483 
484 	/* Print header */
485 	if (!tflag && !cflag)
486 		printf("%-*.*s %-*.*s %*.*s %-9.9s %1s %5s\n",
487 		    W_ADDR, W_ADDR, "Neighbor", W_LL, W_LL, "Linklayer Address",
488 		    W_IF, W_IF, "Netif", "Expire", "S", "Flags");
489 
490 again:;
491 	lim = NULL;
492 	mib[0] = CTL_NET;
493 	mib[1] = PF_ROUTE;
494 	mib[2] = 0;
495 	mib[3] = AF_INET6;
496 	mib[4] = NET_RT_FLAGS;
497 	mib[5] = RTF_LLINFO;
498 	mib[6] = rdomain;
499 	while (1) {
500 		if (sysctl(mib, 7, NULL, &needed, NULL, 0) == -1)
501 			err(1, "sysctl(PF_ROUTE estimate)");
502 		if (needed == 0)
503 			break;
504 		if ((buf = realloc(buf, needed)) == NULL)
505 			err(1, "realloc");
506 		if (sysctl(mib, 7, buf, &needed, NULL, 0) == -1) {
507 			if (errno == ENOMEM)
508 				continue;
509 			err(1, "sysctl(PF_ROUTE, NET_RT_FLAGS)");
510 		}
511 		lim = buf + needed;
512 		break;
513 	}
514 
515 	for (next = buf; next && lim && next < lim; next += rtm->rtm_msglen) {
516 		int isrouter = 0, prbs = 0;
517 
518 		rtm = (struct rt_msghdr *)next;
519 		if (rtm->rtm_version != RTM_VERSION)
520 			continue;
521 		sin = (struct sockaddr_in6 *)(next + rtm->rtm_hdrlen);
522 #ifdef __KAME__
523 		{
524 			struct in6_addr *in6 = &sin->sin6_addr;
525 			if ((IN6_IS_ADDR_LINKLOCAL(in6) ||
526 			    IN6_IS_ADDR_MC_LINKLOCAL(in6) ||
527 			    IN6_IS_ADDR_MC_INTFACELOCAL(in6)) &&
528 			    sin->sin6_scope_id == 0) {
529 				sin->sin6_scope_id = (u_int32_t)
530 				    ntohs(*(u_short *)&in6->s6_addr[2]);
531 				*(u_short *)&in6->s6_addr[2] = 0;
532 			}
533 		}
534 #endif
535 		sdl = (struct sockaddr_dl *)((char *)sin + ROUNDUP(sin->sin6_len));
536 
537 		/*
538 		 * Some OSes can produce a route that has the LINK flag but
539 		 * has a non-AF_LINK gateway (e.g. fe80::xx%lo0 on FreeBSD
540 		 * and BSD/OS, where xx is not the interface identifier on
541 		 * lo0).  Such routes entry would annoy getnbrinfo() below,
542 		 * so we skip them.
543 		 * XXX: such routes should have the GATEWAY flag, not the
544 		 * LINK flag.  However, there is rotten routing software
545 		 * that advertises all routes that have the GATEWAY flag.
546 		 * Thus, KAME kernel intentionally does not set the LINK flag.
547 		 * What is to be fixed is not ndp, but such routing software
548 		 * (and the kernel workaround)...
549 		 */
550 		if (sdl->sdl_family != AF_LINK)
551 			continue;
552 
553 		if (!(rtm->rtm_flags & RTF_HOST))
554 			continue;
555 
556 		if (addr) {
557 			if (!IN6_ARE_ADDR_EQUAL(&addr->sin6_addr,
558 			    &sin->sin6_addr) || addr->sin6_scope_id !=
559 			    sin->sin6_scope_id)
560 				continue;
561 			found_entry = 1;
562 		} else if (IN6_IS_ADDR_MULTICAST(&sin->sin6_addr))
563 			continue;
564 		getnameinfo((struct sockaddr *)sin, sin->sin6_len, host_buf,
565 		    sizeof(host_buf), NULL, 0, (nflag ? NI_NUMERICHOST : 0));
566 		if (cflag) {
567 			if (rtm->rtm_flags & RTF_CLONED)
568 				delete(host_buf);
569 			continue;
570 		}
571 		gettimeofday(&now, 0);
572 		if (tflag) {
573 			char buf[sizeof("00:00:00")];
574 			struct tm *tm;
575 
576 			tm = localtime(&now.tv_sec);
577 			if (tm != NULL) {
578 				strftime(buf, sizeof(buf), "%H:%M:%S", tm);
579 				printf("%s.%06ld ", buf, now.tv_usec);
580 			}
581 		}
582 
583 		addrwidth = strlen(host_buf);
584 		if (addrwidth < W_ADDR)
585 			addrwidth = W_ADDR;
586 		llwidth = strlen(ether_str(sdl));
587 		if (W_ADDR + W_LL - addrwidth > llwidth)
588 			llwidth = W_ADDR + W_LL - addrwidth;
589 		ifname = if_indextoname(sdl->sdl_index, ifix_buf);
590 		if (!ifname)
591 			ifname = "?";
592 		ifwidth = strlen(ifname);
593 		if (W_ADDR + W_LL + W_IF - addrwidth - llwidth > ifwidth)
594 			ifwidth = W_ADDR + W_LL + W_IF - addrwidth - llwidth;
595 
596 		printf("%-*.*s %-*.*s %*.*s", addrwidth, addrwidth, host_buf,
597 		    llwidth, llwidth, ether_str(sdl), ifwidth, ifwidth, ifname);
598 
599 		/* Print neighbor discovery specific informations */
600 		nbi = getnbrinfo(&sin->sin6_addr, sdl->sdl_index, 1);
601 		if (nbi) {
602 			if (nbi->expire > now.tv_sec) {
603 				printf(" %-9.9s",
604 				    sec2str(nbi->expire - now.tv_sec));
605 			} else if (nbi->expire == 0)
606 				printf(" %-9.9s", "permanent");
607 			else
608 				printf(" %-9.9s", "expired");
609 
610 			switch (nbi->state) {
611 			case ND6_LLINFO_NOSTATE:
612 				 printf(" N");
613 				 break;
614 			case ND6_LLINFO_INCOMPLETE:
615 				 printf(" I");
616 				 break;
617 			case ND6_LLINFO_REACHABLE:
618 				 printf(" R");
619 				 break;
620 			case ND6_LLINFO_STALE:
621 				 printf(" S");
622 				 break;
623 			case ND6_LLINFO_DELAY:
624 				 printf(" D");
625 				 break;
626 			case ND6_LLINFO_PROBE:
627 				 printf(" P");
628 				 break;
629 			default:
630 				 printf(" ?");
631 				 break;
632 			}
633 
634 			isrouter = nbi->isrouter;
635 			prbs = nbi->asked;
636 		} else {
637 			warnx("failed to get neighbor information");
638 			printf("  ");
639 		}
640 
641 		printf(" %s%s%s",
642 		    (rtm->rtm_flags & RTF_LOCAL) ? "l" : "",
643 		    isrouter ? "R" : "",
644 		    (rtm->rtm_flags & RTF_ANNOUNCE) ? "p" : "");
645 
646 		if (prbs)
647 			printf(" %d", prbs);
648 
649 		printf("\n");
650 	}
651 
652 	if (repeat) {
653 		printf("\n");
654 		fflush(stdout);
655 		sleep(repeat);
656 		goto again;
657 	}
658 
659 	free(buf);
660 }
661 
662 static struct in6_nbrinfo *
663 getnbrinfo(struct in6_addr *addr, int ifindex, int warning)
664 {
665 	static struct in6_nbrinfo nbi;
666 	int s;
667 
668 	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) == -1)
669 		err(1, "socket");
670 
671 	bzero(&nbi, sizeof(nbi));
672 	if_indextoname(ifindex, nbi.ifname);
673 	nbi.addr = *addr;
674 	if (ioctl(s, SIOCGNBRINFO_IN6, (caddr_t)&nbi) == -1) {
675 		if (warning)
676 			warn("ioctl(SIOCGNBRINFO_IN6)");
677 		close(s);
678 		return(NULL);
679 	}
680 
681 	close(s);
682 	return(&nbi);
683 }
684 
685 static char *
686 ether_str(struct sockaddr_dl *sdl)
687 {
688 	static char hbuf[NI_MAXHOST];
689 	u_char *cp;
690 
691 	if (sdl->sdl_alen) {
692 		cp = (u_char *)LLADDR(sdl);
693 		snprintf(hbuf, sizeof(hbuf), "%02x:%02x:%02x:%02x:%02x:%02x",
694 		    cp[0], cp[1], cp[2], cp[3], cp[4], cp[5]);
695 	} else
696 		snprintf(hbuf, sizeof(hbuf), "(incomplete)");
697 
698 	return(hbuf);
699 }
700 
701 int
702 ndp_ether_aton(const char *a, u_char *n)
703 {
704 	int i, o[6];
705 
706 	i = sscanf(a, "%x:%x:%x:%x:%x:%x", &o[0], &o[1], &o[2],
707 	    &o[3], &o[4], &o[5]);
708 	if (i != 6) {
709 		warnx("invalid Ethernet address '%s'", a);
710 		return (1);
711 	}
712 	for (i = 0; i < 6; i++)
713 		n[i] = o[i];
714 	return (0);
715 }
716 
717 void
718 usage(void)
719 {
720 	printf("usage: ndp [-acnt] ");
721 	printf("[-A wait] [-d hostname] [-f filename] [-i interface]\n");
722 	printf("\t[-s nodename ether_addr [temp] [proxy]] ");
723 	printf("[-V rdomain] [hostname]\n");
724 	exit(1);
725 }
726 
727 int
728 rtmsg(int cmd)
729 {
730 	static int seq;
731 	int rlen;
732 	struct rt_msghdr *rtm = &m_rtmsg.m_rtm;
733 	char *cp = m_rtmsg.m_space;
734 	int l;
735 
736 	errno = 0;
737 	if (cmd == RTM_DELETE)
738 		goto doit;
739 	bzero((char *)&m_rtmsg, sizeof(m_rtmsg));
740 	rtm->rtm_flags = flags;
741 	rtm->rtm_version = RTM_VERSION;
742 	rtm->rtm_tableid = rdomain;
743 
744 	switch (cmd) {
745 	default:
746 		errx(1, "internal wrong cmd");
747 	case RTM_ADD:
748 		rtm->rtm_addrs |= RTA_GATEWAY;
749 		if (expire_time) {
750 			rtm->rtm_rmx.rmx_expire = expire_time;
751 			rtm->rtm_inits = RTV_EXPIRE;
752 		}
753 		rtm->rtm_flags |= (RTF_HOST | RTF_STATIC);
754 #if 0	/* we don't support ipv6addr/128 type proxying. */
755 		if (rtm->rtm_flags & RTF_ANNOUNCE) {
756 			rtm->rtm_flags &= ~RTF_HOST;
757 			rtm->rtm_addrs |= RTA_NETMASK;
758 		}
759 #endif
760 		/* FALLTHROUGH */
761 	case RTM_GET:
762 		rtm->rtm_addrs |= (RTA_DST | RTA_IFP);
763 	}
764 
765 #define NEXTADDR(w, s)							\
766 	if (rtm->rtm_addrs & (w)) {					\
767 		memcpy(cp, &(s), sizeof(s));				\
768 		ADVANCE(cp, (struct sockaddr *)&(s));			\
769 	}
770 
771 #ifdef __KAME__
772 	{
773 		struct sockaddr_in6 sin6 = sin_m;
774 		struct in6_addr *in6 = &sin6.sin6_addr;
775 		if (IN6_IS_ADDR_LINKLOCAL(in6) ||
776 		    IN6_IS_ADDR_MC_LINKLOCAL(in6) ||
777 		    IN6_IS_ADDR_MC_INTFACELOCAL(in6)) {
778 			*(u_int16_t *)& in6->s6_addr[2] =
779 			    htons(sin6.sin6_scope_id);
780 			sin6.sin6_scope_id = 0;
781 		}
782 		NEXTADDR(RTA_DST, sin6);
783 	}
784 #else
785 	NEXTADDR(RTA_DST, sin_m);
786 #endif
787 	NEXTADDR(RTA_GATEWAY, sdl_m);
788 #if 0	/* we don't support ipv6addr/128 type proxying. */
789 	memset(&so_mask.sin6_addr, 0xff, sizeof(so_mask.sin6_addr));
790 	NEXTADDR(RTA_NETMASK, so_mask);
791 #endif
792 	NEXTADDR(RTA_IFP, ifp_m);
793 
794 	rtm->rtm_msglen = cp - (char *)&m_rtmsg;
795 doit:
796 	l = rtm->rtm_msglen;
797 	rtm->rtm_seq = ++seq;
798 	rtm->rtm_type = cmd;
799 	if ((rlen = write(rtsock, (char *)&m_rtmsg, l)) == -1) {
800 		if (errno != ESRCH || cmd != RTM_DELETE) {
801 			err(1, "writing to routing socket");
802 		}
803 	}
804 	do {
805 		l = read(rtsock, (char *)&m_rtmsg, sizeof(m_rtmsg));
806 	} while (l > 0 && (rtm->rtm_version != RTM_VERSION ||
807 	    rtm->rtm_seq != seq || rtm->rtm_pid != pid));
808 	if (l == -1)
809 		warn("read from routing socket");
810 	return (0);
811 }
812 
813 int
814 rtget(struct sockaddr_in6 **sinp, struct sockaddr_dl **sdlp)
815 {
816 	struct rt_msghdr *rtm = &(m_rtmsg.m_rtm);
817 	struct sockaddr_in6 *sin = NULL;
818 	struct sockaddr_dl *sdl = NULL;
819 	struct sockaddr *sa;
820 	char *cp;
821 	unsigned int i;
822 
823 	if (rtmsg(RTM_GET) < 0)
824 		return (1);
825 
826 	if (rtm->rtm_addrs) {
827 		cp = ((char *)rtm + rtm->rtm_hdrlen);
828 		for (i = 1; i; i <<= 1) {
829 			if (i & rtm->rtm_addrs) {
830 				sa = (struct sockaddr *)cp;
831 				switch (i) {
832 				case RTA_DST:
833 					sin = (struct sockaddr_in6 *)sa;
834 					break;
835 				case RTA_IFP:
836 					sdl = (struct sockaddr_dl *)sa;
837 					break;
838 				default:
839 					break;
840 				}
841 				ADVANCE(cp, sa);
842 			}
843 		}
844 	}
845 
846 	if (sin == NULL || sdl == NULL)
847 		return (1);
848 
849 #ifdef __KAME__
850 	{
851 		static struct sockaddr_in6 ksin;
852 		struct in6_addr *in6;
853 
854 		/* do not damage the route message, we need it for delete */
855 		ksin = *sin;
856 		sin = &ksin;
857 		in6 = &sin->sin6_addr;
858 
859 		if ((IN6_IS_ADDR_LINKLOCAL(in6) ||
860 		    IN6_IS_ADDR_MC_LINKLOCAL(in6) ||
861 		    IN6_IS_ADDR_MC_INTFACELOCAL(in6)) &&
862 		    sin->sin6_scope_id == 0) {
863 			sin->sin6_scope_id = (u_int32_t)ntohs(*(u_short *)
864 			    &in6->s6_addr[2]);
865 			*(u_short *)&in6->s6_addr[2] = 0;
866 		}
867 	}
868 #endif
869 	*sinp = sin;
870 	*sdlp = sdl;
871 
872 	return (0);
873 }
874 
875 void
876 ifinfo(const char *ifname)
877 {
878 	struct in6_ndireq nd;
879 	int s;
880 
881 	if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) == -1) {
882 		err(1, "socket");
883 	}
884 	bzero(&nd, sizeof(nd));
885 	strlcpy(nd.ifname, ifname, sizeof(nd.ifname));
886 	if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) == -1)
887 		err(1, "ioctl(SIOCGIFINFO_IN6)");
888 
889 	if (!nd.ndi.initialized)
890 		errx(1, "%s: not initialized yet", ifname);
891 
892 	printf("basereachable=%ds%dms",
893 	    nd.ndi.basereachable / 1000, nd.ndi.basereachable % 1000);
894 	printf(", reachable=%ds", nd.ndi.reachable);
895 	printf(", retrans=%ds%dms\n", nd.ndi.retrans / 1000,
896 	    nd.ndi.retrans % 1000);
897 
898 	close(s);
899 }
900 
901 static char *
902 sec2str(time_t total)
903 {
904 	static char result[256];
905 	int days, hours, mins, secs;
906 	int first = 1;
907 	char *p = result;
908 	char *ep = &result[sizeof(result)];
909 	int n;
910 
911 	days = total / 3600 / 24;
912 	hours = (total / 3600) % 24;
913 	mins = (total / 60) % 60;
914 	secs = total % 60;
915 
916 	if (days) {
917 		first = 0;
918 		n = snprintf(p, ep - p, "%dd", days);
919 		if (n < 0 || n >= ep - p)
920 			return "?";
921 		p += n;
922 	}
923 	if (!first || hours) {
924 		first = 0;
925 		n = snprintf(p, ep - p, "%dh", hours);
926 		if (n < 0 || n >= ep - p)
927 			return "?";
928 		p += n;
929 	}
930 	if (!first || mins) {
931 		first = 0;
932 		n = snprintf(p, ep - p, "%dm", mins);
933 		if (n < 0 || n >= ep - p)
934 			return "?";
935 		p += n;
936 	}
937 	snprintf(p, ep - p, "%ds", secs);
938 
939 	return(result);
940 }
941