rtsold.c revision 290149
1/*	$KAME: rtsold.c,v 1.67 2003/05/17 18:16:15 itojun Exp $	*/
2
3/*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * $FreeBSD: stable/10/usr.sbin/rtsold/rtsold.c 290149 2015-10-29 16:53:34Z delphij $
32 */
33
34#include <sys/types.h>
35#include <sys/ioctl.h>
36#include <sys/socket.h>
37#include <sys/param.h>
38
39#include <net/if.h>
40#include <net/if_dl.h>
41#include <net/if_var.h>
42
43#include <netinet/in.h>
44#include <netinet/icmp6.h>
45#include <netinet/in_var.h>
46#include <arpa/inet.h>
47
48#include <netinet6/nd6.h>
49
50#include <signal.h>
51#include <unistd.h>
52#include <syslog.h>
53#include <string.h>
54#include <stdlib.h>
55#include <stdio.h>
56#include <time.h>
57#include <errno.h>
58#include <err.h>
59#include <stdarg.h>
60#include <ifaddrs.h>
61#ifdef HAVE_POLL_H
62#include <poll.h>
63#endif
64
65#include "rtsold.h"
66
67#define RTSOL_DUMPFILE	"/var/run/rtsold.dump";
68#define RTSOL_PIDFILE	"/var/run/rtsold.pid";
69
70struct timespec tm_max;
71static int log_upto = 999;
72static int fflag = 0;
73
74int Fflag = 0;	/* force setting sysctl parameters */
75int aflag = 0;
76int dflag = 0;
77int uflag = 0;
78
79const char *otherconf_script;
80const char *resolvconf_script = "/sbin/resolvconf";
81
82/* protocol constants */
83#define MAX_RTR_SOLICITATION_DELAY	1 /* second */
84#define RTR_SOLICITATION_INTERVAL	4 /* seconds */
85#define MAX_RTR_SOLICITATIONS		3 /* times */
86
87/*
88 * implementation dependent constants in seconds
89 * XXX: should be configurable
90 */
91#define PROBE_INTERVAL 60
92
93/* static variables and functions */
94static int mobile_node = 0;
95static const char *pidfilename = RTSOL_PIDFILE;
96
97#ifndef SMALL
98static int do_dump;
99static const char *dumpfilename = RTSOL_DUMPFILE;
100#endif
101
102#if 0
103static int ifreconfig(char *);
104#endif
105
106static int make_packet(struct ifinfo *);
107static struct timespec *rtsol_check_timer(void);
108
109#ifndef SMALL
110static void rtsold_set_dump_file(int);
111#endif
112static void usage(void);
113
114int
115main(int argc, char **argv)
116{
117	int s, ch, once = 0;
118	struct timespec *timeout;
119	const char *opts;
120#ifdef HAVE_POLL_H
121	struct pollfd set[2];
122#else
123	fd_set *fdsetp, *selectfdp;
124	int fdmasks;
125	int maxfd;
126#endif
127	int rtsock;
128	char *argv0;
129
130#ifndef SMALL
131	/* rtsold */
132	opts = "adDfFm1O:p:R:u";
133#else
134	/* rtsol */
135	opts = "adDFO:R:u";
136	fflag = 1;
137	once = 1;
138#endif
139	argv0 = argv[0];
140
141	while ((ch = getopt(argc, argv, opts)) != -1) {
142		switch (ch) {
143		case 'a':
144			aflag = 1;
145			break;
146		case 'd':
147			dflag += 1;
148			break;
149		case 'D':
150			dflag += 2;
151			break;
152		case 'f':
153			fflag = 1;
154			break;
155		case 'F':
156			Fflag = 1;
157			break;
158		case 'm':
159			mobile_node = 1;
160			break;
161		case '1':
162			once = 1;
163			break;
164		case 'O':
165			otherconf_script = optarg;
166			break;
167		case 'p':
168			pidfilename = optarg;
169			break;
170		case 'R':
171			resolvconf_script = optarg;
172			break;
173		case 'u':
174			uflag = 1;
175			break;
176		default:
177			usage();
178			exit(1);
179		}
180	}
181	argc -= optind;
182	argv += optind;
183
184	if ((!aflag && argc == 0) || (aflag && argc != 0)) {
185		usage();
186		exit(1);
187	}
188
189	/* Generate maximum time in timespec. */
190	tm_max.tv_sec = (-1) & ~((time_t)1 << ((sizeof(tm_max.tv_sec) * 8) - 1));
191	tm_max.tv_nsec = (-1) & ~((long)1 << ((sizeof(tm_max.tv_nsec) * 8) - 1));
192
193	/* set log level */
194	if (dflag > 1)
195		log_upto = LOG_DEBUG;
196	else if (dflag > 0)
197		log_upto = LOG_INFO;
198	else
199		log_upto = LOG_NOTICE;
200
201	if (!fflag) {
202		char *ident;
203
204		ident = strrchr(argv0, '/');
205		if (!ident)
206			ident = argv0;
207		else
208			ident++;
209		openlog(ident, LOG_NDELAY|LOG_PID, LOG_DAEMON);
210		if (log_upto >= 0)
211			setlogmask(LOG_UPTO(log_upto));
212	}
213
214	if (otherconf_script && *otherconf_script != '/') {
215		errx(1, "configuration script (%s) must be an absolute path",
216		    otherconf_script);
217	}
218	if (resolvconf_script && *resolvconf_script != '/') {
219		errx(1, "configuration script (%s) must be an absolute path",
220		    resolvconf_script);
221	}
222	if (pidfilename && *pidfilename != '/') {
223		errx(1, "pid filename (%s) must be an absolute path",
224		    pidfilename);
225	}
226
227#if (__FreeBSD_version < 900000)
228	if (Fflag) {
229		setinet6sysctl(IPV6CTL_FORWARDING, 0);
230	} else {
231		/* warn if forwarding is up */
232		if (getinet6sysctl(IPV6CTL_FORWARDING))
233			warnx("kernel is configured as a router, not a host");
234	}
235#endif
236
237#ifndef SMALL
238	/* initialization to dump internal status to a file */
239	signal(SIGUSR1, rtsold_set_dump_file);
240#endif
241
242	if (!fflag)
243		daemon(0, 0);		/* act as a daemon */
244
245	/*
246	 * Open a socket for sending RS and receiving RA.
247	 * This should be done before calling ifinit(), since the function
248	 * uses the socket.
249	 */
250	if ((s = sockopen()) < 0) {
251		warnmsg(LOG_ERR, __func__, "failed to open a socket");
252		exit(1);
253	}
254#ifdef HAVE_POLL_H
255	set[0].fd = s;
256	set[0].events = POLLIN;
257#else
258	maxfd = s;
259#endif
260
261#ifdef HAVE_POLL_H
262	set[1].fd = -1;
263#endif
264
265	if ((rtsock = rtsock_open()) < 0) {
266		warnmsg(LOG_ERR, __func__, "failed to open a socket");
267		exit(1);
268	}
269#ifdef HAVE_POLL_H
270	set[1].fd = rtsock;
271	set[1].events = POLLIN;
272#else
273	if (rtsock > maxfd)
274		maxfd = rtsock;
275#endif
276
277#ifndef HAVE_POLL_H
278	fdmasks = howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask);
279	if ((fdsetp = malloc(fdmasks)) == NULL) {
280		warnmsg(LOG_ERR, __func__, "malloc");
281		exit(1);
282	}
283	if ((selectfdp = malloc(fdmasks)) == NULL) {
284		warnmsg(LOG_ERR, __func__, "malloc");
285		exit(1);
286	}
287#endif
288
289	/* configuration per interface */
290	if (ifinit()) {
291		warnmsg(LOG_ERR, __func__,
292		    "failed to initialize interfaces");
293		exit(1);
294	}
295	if (aflag)
296		argv = autoifprobe();
297	while (argv && *argv) {
298		if (ifconfig(*argv)) {
299			warnmsg(LOG_ERR, __func__,
300			    "failed to initialize %s", *argv);
301			exit(1);
302		}
303		argv++;
304	}
305
306	/* setup for probing default routers */
307	if (probe_init()) {
308		warnmsg(LOG_ERR, __func__,
309		    "failed to setup for probing routers");
310		exit(1);
311		/*NOTREACHED*/
312	}
313
314	/* dump the current pid */
315	if (!once) {
316		pid_t pid = getpid();
317		FILE *fp;
318
319		if ((fp = fopen(pidfilename, "w")) == NULL)
320			warnmsg(LOG_ERR, __func__,
321			    "failed to open a pid log file(%s): %s",
322			    pidfilename, strerror(errno));
323		else {
324			fprintf(fp, "%d\n", pid);
325			fclose(fp);
326		}
327	}
328#ifndef HAVE_POLL_H
329	memset(fdsetp, 0, fdmasks);
330	FD_SET(s, fdsetp);
331	FD_SET(rtsock, fdsetp);
332#endif
333	while (1) {		/* main loop */
334		int e;
335
336#ifndef HAVE_POLL_H
337		memcpy(selectfdp, fdsetp, fdmasks);
338#endif
339
340#ifndef SMALL
341		if (do_dump) {	/* SIGUSR1 */
342			do_dump = 0;
343			rtsold_dump_file(dumpfilename);
344		}
345#endif
346
347		timeout = rtsol_check_timer();
348
349		if (once) {
350			struct ifinfo *ifi;
351
352			/* if we have no timeout, we are done (or failed) */
353			if (timeout == NULL)
354				break;
355
356			/* if all interfaces have got RA packet, we are done */
357			TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
358				if (ifi->state != IFS_DOWN && ifi->racnt == 0)
359					break;
360			}
361			if (ifi == NULL)
362				break;
363		}
364#ifdef HAVE_POLL_H
365		e = poll(set, 2, timeout ? (timeout->tv_sec * 1000 + timeout->tv_nsec / 1000 / 1000) : INFTIM);
366#else
367		e = select(maxfd + 1, selectfdp, NULL, NULL, timeout);
368#endif
369		if (e < 1) {
370			if (e < 0 && errno != EINTR) {
371				warnmsg(LOG_ERR, __func__, "select: %s",
372				    strerror(errno));
373			}
374			continue;
375		}
376
377		/* packet reception */
378#ifdef HAVE_POLL_H
379		if (set[1].revents & POLLIN)
380#else
381		if (FD_ISSET(rtsock, selectfdp))
382#endif
383			rtsock_input(rtsock);
384#ifdef HAVE_POLL_H
385		if (set[0].revents & POLLIN)
386#else
387		if (FD_ISSET(s, selectfdp))
388#endif
389			rtsol_input(s);
390	}
391	/* NOTREACHED */
392
393	return (0);
394}
395
396int
397ifconfig(char *ifname)
398{
399	struct ifinfo *ifi;
400	struct sockaddr_dl *sdl;
401	int flags;
402
403	if ((sdl = if_nametosdl(ifname)) == NULL) {
404		warnmsg(LOG_ERR, __func__,
405		    "failed to get link layer information for %s", ifname);
406		return (-1);
407	}
408	if (find_ifinfo(sdl->sdl_index)) {
409		warnmsg(LOG_ERR, __func__,
410		    "interface %s was already configured", ifname);
411		free(sdl);
412		return (-1);
413	}
414
415	if (Fflag) {
416		struct in6_ndireq nd;
417		int s;
418
419		if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
420			warnmsg(LOG_ERR, __func__, "socket() failed.");
421			return (-1);
422		}
423		memset(&nd, 0, sizeof(nd));
424		strlcpy(nd.ifname, ifname, sizeof(nd.ifname));
425		if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
426			warnmsg(LOG_ERR, __func__,
427			    "cannot get accept_rtadv flag");
428			close(s);
429			return (-1);
430		}
431		nd.ndi.flags |= ND6_IFF_ACCEPT_RTADV;
432		if (ioctl(s, SIOCSIFINFO_IN6, (caddr_t)&nd) < 0) {
433			warnmsg(LOG_ERR, __func__,
434			    "cannot set accept_rtadv flag");
435			close(s);
436			return (-1);
437		}
438		close(s);
439	}
440
441	if ((ifi = malloc(sizeof(*ifi))) == NULL) {
442		warnmsg(LOG_ERR, __func__, "memory allocation failed");
443		free(sdl);
444		return (-1);
445	}
446	memset(ifi, 0, sizeof(*ifi));
447	ifi->sdl = sdl;
448	ifi->ifi_rdnss = IFI_DNSOPT_STATE_NOINFO;
449	ifi->ifi_dnssl = IFI_DNSOPT_STATE_NOINFO;
450	TAILQ_INIT(&ifi->ifi_rainfo);
451	strlcpy(ifi->ifname, ifname, sizeof(ifi->ifname));
452
453	/* construct a router solicitation message */
454	if (make_packet(ifi))
455		goto bad;
456
457	/* set link ID of this interface. */
458#ifdef HAVE_SCOPELIB
459	if (inet_zoneid(AF_INET6, 2, ifname, &ifi->linkid))
460		goto bad;
461#else
462	/* XXX: assume interface IDs as link IDs */
463	ifi->linkid = ifi->sdl->sdl_index;
464#endif
465
466	/*
467	 * check if the interface is available.
468	 * also check if SIOCGIFMEDIA ioctl is OK on the interface.
469	 */
470	ifi->mediareqok = 1;
471	ifi->active = interface_status(ifi);
472	if (!ifi->mediareqok) {
473		/*
474		 * probe routers periodically even if the link status
475		 * does not change.
476		 */
477		ifi->probeinterval = PROBE_INTERVAL;
478	}
479
480	/* activate interface: interface_up returns 0 on success */
481	flags = interface_up(ifi->ifname);
482	if (flags == 0)
483		ifi->state = IFS_DELAY;
484	else if (flags == IFS_TENTATIVE)
485		ifi->state = IFS_TENTATIVE;
486	else
487		ifi->state = IFS_DOWN;
488
489	rtsol_timer_update(ifi);
490
491	TAILQ_INSERT_TAIL(&ifinfo_head, ifi, ifi_next);
492	return (0);
493
494bad:
495	free(ifi->sdl);
496	free(ifi);
497	return (-1);
498}
499
500void
501iflist_init(void)
502{
503	struct ifinfo *ifi;
504
505	while ((ifi = TAILQ_FIRST(&ifinfo_head)) != NULL) {
506		TAILQ_REMOVE(&ifinfo_head, ifi, ifi_next);
507		if (ifi->sdl != NULL)
508			free(ifi->sdl);
509		if (ifi->rs_data != NULL)
510			free(ifi->rs_data);
511		free(ifi);
512	}
513}
514
515#if 0
516static int
517ifreconfig(char *ifname)
518{
519	struct ifinfo *ifi, *prev;
520	int rv;
521
522	prev = NULL;
523	TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
524		if (strncmp(ifi->ifname, ifname, sizeof(ifi->ifname)) == 0)
525			break;
526		prev = ifi;
527	}
528	prev->next = ifi->next;
529
530	rv = ifconfig(ifname);
531
532	/* reclaim it after ifconfig() in case ifname is pointer inside ifi */
533	if (ifi->rs_data)
534		free(ifi->rs_data);
535	free(ifi->sdl);
536	free(ifi);
537
538	return (rv);
539}
540#endif
541
542struct rainfo *
543find_rainfo(struct ifinfo *ifi, struct sockaddr_in6 *sin6)
544{
545	struct rainfo *rai;
546
547	TAILQ_FOREACH(rai, &ifi->ifi_rainfo, rai_next)
548		if (memcmp(&rai->rai_saddr.sin6_addr, &sin6->sin6_addr,
549		    sizeof(rai->rai_saddr.sin6_addr)) == 0)
550			return (rai);
551
552	return (NULL);
553}
554
555struct ifinfo *
556find_ifinfo(int ifindex)
557{
558	struct ifinfo *ifi;
559
560	TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
561		if (ifi->sdl->sdl_index == ifindex)
562			return (ifi);
563	}
564	return (NULL);
565}
566
567static int
568make_packet(struct ifinfo *ifi)
569{
570	size_t packlen = sizeof(struct nd_router_solicit), lladdroptlen = 0;
571	struct nd_router_solicit *rs;
572	char *buf;
573
574	if ((lladdroptlen = lladdropt_length(ifi->sdl)) == 0) {
575		warnmsg(LOG_INFO, __func__,
576		    "link-layer address option has null length"
577		    " on %s. Treat as not included.", ifi->ifname);
578	}
579	packlen += lladdroptlen;
580	ifi->rs_datalen = packlen;
581
582	/* allocate buffer */
583	if ((buf = malloc(packlen)) == NULL) {
584		warnmsg(LOG_ERR, __func__,
585		    "memory allocation failed for %s", ifi->ifname);
586		return (-1);
587	}
588	ifi->rs_data = buf;
589
590	/* fill in the message */
591	rs = (struct nd_router_solicit *)buf;
592	rs->nd_rs_type = ND_ROUTER_SOLICIT;
593	rs->nd_rs_code = 0;
594	rs->nd_rs_cksum = 0;
595	rs->nd_rs_reserved = 0;
596	buf += sizeof(*rs);
597
598	/* fill in source link-layer address option */
599	if (lladdroptlen)
600		lladdropt_fill(ifi->sdl, (struct nd_opt_hdr *)buf);
601
602	return (0);
603}
604
605static struct timespec *
606rtsol_check_timer(void)
607{
608	static struct timespec returnval;
609	struct timespec now, rtsol_timer;
610	struct ifinfo *ifi;
611	struct rainfo *rai;
612	struct ra_opt *rao;
613	int flags;
614
615	clock_gettime(CLOCK_MONOTONIC_FAST, &now);
616
617	rtsol_timer = tm_max;
618
619	TAILQ_FOREACH(ifi, &ifinfo_head, ifi_next) {
620		if (TS_CMP(&ifi->expire, &now, <=)) {
621			warnmsg(LOG_DEBUG, __func__, "timer expiration on %s, "
622			    "state = %d", ifi->ifname, ifi->state);
623
624			while((rai = TAILQ_FIRST(&ifi->ifi_rainfo)) != NULL) {
625				/* Remove all RA options. */
626				TAILQ_REMOVE(&ifi->ifi_rainfo, rai, rai_next);
627				while ((rao = TAILQ_FIRST(&rai->rai_ra_opt)) !=
628				    NULL) {
629					TAILQ_REMOVE(&rai->rai_ra_opt, rao,
630					    rao_next);
631					if (rao->rao_msg != NULL)
632						free(rao->rao_msg);
633					free(rao);
634				}
635				free(rai);
636			}
637			switch (ifi->state) {
638			case IFS_DOWN:
639			case IFS_TENTATIVE:
640				/* interface_up returns 0 on success */
641				flags = interface_up(ifi->ifname);
642				if (flags == 0)
643					ifi->state = IFS_DELAY;
644				else if (flags == IFS_TENTATIVE)
645					ifi->state = IFS_TENTATIVE;
646				else
647					ifi->state = IFS_DOWN;
648				break;
649			case IFS_IDLE:
650			{
651				int oldstatus = ifi->active;
652				int probe = 0;
653
654				ifi->active = interface_status(ifi);
655
656				if (oldstatus != ifi->active) {
657					warnmsg(LOG_DEBUG, __func__,
658					    "%s status is changed"
659					    " from %d to %d",
660					    ifi->ifname,
661					    oldstatus, ifi->active);
662					probe = 1;
663					ifi->state = IFS_DELAY;
664				} else if (ifi->probeinterval &&
665				    (ifi->probetimer -=
666				    ifi->timer.tv_sec) <= 0) {
667					/* probe timer expired */
668					ifi->probetimer =
669					    ifi->probeinterval;
670					probe = 1;
671					ifi->state = IFS_PROBE;
672				}
673
674				/*
675				 * If we need a probe, clear the previous
676				 * status wrt the "other" configuration.
677				 */
678				if (probe)
679					ifi->otherconfig = 0;
680
681				if (probe && mobile_node)
682					defrouter_probe(ifi);
683				break;
684			}
685			case IFS_DELAY:
686				ifi->state = IFS_PROBE;
687				sendpacket(ifi);
688				break;
689			case IFS_PROBE:
690				if (ifi->probes < MAX_RTR_SOLICITATIONS)
691					sendpacket(ifi);
692				else {
693					warnmsg(LOG_INFO, __func__,
694					    "No answer after sending %d RSs",
695					    ifi->probes);
696					ifi->probes = 0;
697					ifi->state = IFS_IDLE;
698				}
699				break;
700			}
701			rtsol_timer_update(ifi);
702		} else {
703			/* Expiration check for RA options. */
704			int expire = 0;
705
706			TAILQ_FOREACH(rai, &ifi->ifi_rainfo, rai_next) {
707				TAILQ_FOREACH(rao, &rai->rai_ra_opt, rao_next) {
708					warnmsg(LOG_DEBUG, __func__,
709					    "RA expiration timer: "
710					    "type=%d, msg=%s, expire=%s",
711					    rao->rao_type, (char *)rao->rao_msg,
712						sec2str(&rao->rao_expire));
713					if (TS_CMP(&now, &rao->rao_expire,
714					    >=)) {
715						warnmsg(LOG_DEBUG, __func__,
716						    "RA expiration timer: "
717						    "expired.");
718						TAILQ_REMOVE(&rai->rai_ra_opt,
719						    rao, rao_next);
720						if (rao->rao_msg != NULL)
721							free(rao->rao_msg);
722						free(rao);
723						expire = 1;
724					}
725				}
726			}
727			if (expire)
728				ra_opt_handler(ifi);
729		}
730		if (TS_CMP(&ifi->expire, &rtsol_timer, <))
731			rtsol_timer = ifi->expire;
732	}
733
734	if (TS_CMP(&rtsol_timer, &tm_max, ==)) {
735		warnmsg(LOG_DEBUG, __func__, "there is no timer");
736		return (NULL);
737	} else if (TS_CMP(&rtsol_timer, &now, <))
738		/* this may occur when the interval is too small */
739		returnval.tv_sec = returnval.tv_nsec = 0;
740	else
741		TS_SUB(&rtsol_timer, &now, &returnval);
742
743	now.tv_sec += returnval.tv_sec;
744	now.tv_nsec += returnval.tv_nsec;
745	warnmsg(LOG_DEBUG, __func__, "New timer is %s",
746	    sec2str(&now));
747
748	return (&returnval);
749}
750
751void
752rtsol_timer_update(struct ifinfo *ifi)
753{
754#define MILLION 1000000
755#define DADRETRY 10		/* XXX: adhoc */
756	long interval;
757	struct timespec now;
758
759	bzero(&ifi->timer, sizeof(ifi->timer));
760
761	switch (ifi->state) {
762	case IFS_DOWN:
763	case IFS_TENTATIVE:
764		if (++ifi->dadcount > DADRETRY) {
765			ifi->dadcount = 0;
766			ifi->timer.tv_sec = PROBE_INTERVAL;
767		} else
768			ifi->timer.tv_sec = 1;
769		break;
770	case IFS_IDLE:
771		if (mobile_node) {
772			/* XXX should be configurable */
773			ifi->timer.tv_sec = 3;
774		}
775		else
776			ifi->timer = tm_max;	/* stop timer(valid?) */
777		break;
778	case IFS_DELAY:
779		interval = arc4random_uniform(MAX_RTR_SOLICITATION_DELAY * MILLION);
780		ifi->timer.tv_sec = interval / MILLION;
781		ifi->timer.tv_nsec = (interval % MILLION) * 1000;
782		break;
783	case IFS_PROBE:
784		if (ifi->probes < MAX_RTR_SOLICITATIONS)
785			ifi->timer.tv_sec = RTR_SOLICITATION_INTERVAL;
786		else {
787			/*
788			 * After sending MAX_RTR_SOLICITATIONS solicitations,
789			 * we're just waiting for possible replies; there
790			 * will be no more solicitation.  Thus, we change
791			 * the timer value to MAX_RTR_SOLICITATION_DELAY based
792			 * on RFC 2461, Section 6.3.7.
793			 */
794			ifi->timer.tv_sec = MAX_RTR_SOLICITATION_DELAY;
795		}
796		break;
797	default:
798		warnmsg(LOG_ERR, __func__,
799		    "illegal interface state(%d) on %s",
800		    ifi->state, ifi->ifname);
801		return;
802	}
803
804	/* reset the timer */
805	if (TS_CMP(&ifi->timer, &tm_max, ==)) {
806		ifi->expire = tm_max;
807		warnmsg(LOG_DEBUG, __func__,
808		    "stop timer for %s", ifi->ifname);
809	} else {
810		clock_gettime(CLOCK_MONOTONIC_FAST, &now);
811		TS_ADD(&now, &ifi->timer, &ifi->expire);
812
813		now.tv_sec += ifi->timer.tv_sec;
814		now.tv_nsec += ifi->timer.tv_nsec;
815		warnmsg(LOG_DEBUG, __func__, "set timer for %s to %s",
816		    ifi->ifname, sec2str(&now));
817	}
818
819#undef MILLION
820}
821
822/* timer related utility functions */
823#define MILLION 1000000
824
825#ifndef SMALL
826static void
827rtsold_set_dump_file(int sig __unused)
828{
829	do_dump = 1;
830}
831#endif
832
833static void
834usage(void)
835{
836#ifndef SMALL
837	fprintf(stderr, "usage: rtsold [-adDfFm1] [-O script-name] "
838	    "[-P pidfile] [-R script-name] interfaces...\n");
839	fprintf(stderr, "usage: rtsold [-dDfFm1] [-O script-name] "
840	    "[-P pidfile] [-R script-name] -a\n");
841#else
842	fprintf(stderr, "usage: rtsol [-dDF] [-O script-name] "
843	    "[-P pidfile] [-R script-name] interfaces...\n");
844	fprintf(stderr, "usage: rtsol [-dDF] [-O script-name] "
845	    "[-P pidfile] [-R script-name] -a\n");
846#endif
847}
848
849void
850warnmsg(int priority, const char *func, const char *msg, ...)
851{
852	va_list ap;
853	char buf[BUFSIZ];
854
855	va_start(ap, msg);
856	if (fflag) {
857		if (priority <= log_upto) {
858			(void)vfprintf(stderr, msg, ap);
859			(void)fprintf(stderr, "\n");
860		}
861	} else {
862		snprintf(buf, sizeof(buf), "<%s> %s", func, msg);
863		msg = buf;
864		vsyslog(priority, msg, ap);
865	}
866	va_end(ap);
867}
868
869/*
870 * return a list of interfaces which is suitable to sending an RS.
871 */
872char **
873autoifprobe(void)
874{
875	static char **argv = NULL;
876	static int n = 0;
877	char **a;
878	int s = 0, i, found;
879	struct ifaddrs *ifap, *ifa;
880	struct in6_ndireq nd;
881
882	/* initialize */
883	while (n--)
884		free(argv[n]);
885	if (argv) {
886		free(argv);
887		argv = NULL;
888	}
889	n = 0;
890
891	if (getifaddrs(&ifap) != 0)
892		return (NULL);
893
894	if (!Fflag && (s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
895		warnmsg(LOG_ERR, __func__, "socket");
896		exit(1);
897	}
898
899	/* find an ethernet */
900	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
901		if ((ifa->ifa_flags & IFF_UP) == 0)
902			continue;
903		if ((ifa->ifa_flags & IFF_POINTOPOINT) != 0)
904			continue;
905		if ((ifa->ifa_flags & IFF_LOOPBACK) != 0)
906			continue;
907		if ((ifa->ifa_flags & IFF_MULTICAST) == 0)
908			continue;
909
910		if (ifa->ifa_addr->sa_family != AF_INET6)
911			continue;
912
913		found = 0;
914		for (i = 0; i < n; i++) {
915			if (strcmp(argv[i], ifa->ifa_name) == 0) {
916				found++;
917				break;
918			}
919		}
920		if (found)
921			continue;
922
923		/*
924		 * Skip the interfaces which IPv6 and/or accepting RA
925		 * is disabled.
926		 */
927		if (!Fflag) {
928			memset(&nd, 0, sizeof(nd));
929			strlcpy(nd.ifname, ifa->ifa_name, sizeof(nd.ifname));
930			if (ioctl(s, SIOCGIFINFO_IN6, (caddr_t)&nd) < 0) {
931				warnmsg(LOG_ERR, __func__,
932					"ioctl(SIOCGIFINFO_IN6)");
933				exit(1);
934			}
935			if ((nd.ndi.flags & ND6_IFF_IFDISABLED))
936				continue;
937			if (!(nd.ndi.flags & ND6_IFF_ACCEPT_RTADV))
938				continue;
939		}
940
941		/* if we find multiple candidates, just warn. */
942		if (n != 0 && dflag > 1)
943			warnmsg(LOG_WARNING, __func__,
944				"multiple interfaces found");
945
946		a = (char **)realloc(argv, (n + 1) * sizeof(char **));
947		if (a == NULL) {
948			warnmsg(LOG_ERR, __func__, "realloc");
949			exit(1);
950		}
951		argv = a;
952		argv[n] = strdup(ifa->ifa_name);
953		if (!argv[n]) {
954			warnmsg(LOG_ERR, __func__, "malloc");
955			exit(1);
956		}
957		n++;
958	}
959
960	if (n) {
961		a = (char **)realloc(argv, (n + 1) * sizeof(char **));
962		if (a == NULL) {
963			warnmsg(LOG_ERR, __func__, "realloc");
964			exit(1);
965		}
966		argv = a;
967		argv[n] = NULL;
968
969		if (dflag > 0) {
970			for (i = 0; i < n; i++)
971				warnmsg(LOG_WARNING, __func__, "probing %s",
972					argv[i]);
973		}
974	}
975	if (!Fflag)
976		close(s);
977	freeifaddrs(ifap);
978	return (argv);
979}
980