xref: /trueos/usr.sbin/watchdogd/watchdogd.c (revision e3ec0e5f11dfbc9fa15e05afb2d163a26364e778)
1 /*-
2  * Copyright (c) 2003-2004  Sean M. Kelly <smkelly@FreeBSD.org>
3  * Copyright (c) 2013 iXsystems.com,
4  *                    author: Alfred Perlstein <alfred@freebsd.org>
5  *
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  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * Software watchdog daemon.
32  */
33 
34 #include <sys/types.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include <sys/mman.h>
38 #include <sys/param.h>
39 #include <sys/rtprio.h>
40 #include <sys/stat.h>
41 #include <sys/time.h>
42 #include <sys/sysctl.h>
43 #include <sys/watchdog.h>
44 
45 #include <err.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <libutil.h>
49 #include <math.h>
50 #include <paths.h>
51 #include <signal.h>
52 #include <stdio.h>
53 #include <stdint.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <strings.h>
57 #include <sysexits.h>
58 #include <syslog.h>
59 #include <unistd.h>
60 
61 #include <getopt.h>
62 
63 static long	fetchtimeout(int opt,
64     const char *longopt, const char *myoptarg, int zero_ok);
65 static void	parseargs(int, char *[]);
66 static int	seconds_to_pow2ns(int);
67 static void	sighandler(int);
68 static void	watchdog_loop(void);
69 static int	watchdog_init(void);
70 static int	watchdog_onoff(int onoff);
71 static int	watchdog_patpat(u_int timeout);
72 static void	usage(void);
73 static int	tstotv(struct timeval *tv, struct timespec *ts);
74 static int	tvtohz(struct timeval *tv);
75 
76 static int debugging = 0;
77 static int end_program = 0;
78 static const char *pidfile = _PATH_VARRUN "watchdogd.pid";
79 static u_int timeout = WD_TO_128SEC;
80 static u_int pretimeout = 0;
81 static u_int timeout_sec;
82 static u_int passive = 0;
83 static int is_daemon = 0;
84 static int is_dry_run = 0;  /* do not arm the watchdog, only
85 			       report on timing of the watch
86 			       program */
87 static int do_timedog = 0;
88 static int do_syslog = 1;
89 static int fd = -1;
90 static int nap = 1;
91 static int carp_thresh_seconds = -1;
92 static char *test_cmd = NULL;
93 
94 static const char *getopt_shortopts;
95 
96 static int pretimeout_set;
97 static int pretimeout_act;
98 static int pretimeout_act_set;
99 
100 static int softtimeout_set;
101 static int softtimeout_act;
102 static int softtimeout_act_set;
103 
104 static struct option longopts[] = {
105 	{ "debug", no_argument, &debugging, 1 },
106 	{ "pretimeout", required_argument, &pretimeout_set, 1 },
107 	{ "pretimeout-action", required_argument, &pretimeout_act_set, 1 },
108 	{ "softtimeout", no_argument, &softtimeout_set, 1 },
109 	{ "softtimeout-action", required_argument, &softtimeout_act_set, 1 },
110 	{ NULL, 0, NULL, 0}
111 };
112 
113 /*
114  * Ask malloc() to map minimum-sized chunks of virtual address space at a time,
115  * so that mlockall() won't needlessly wire megabytes of unused memory into the
116  * process.  This must be done using the malloc_conf string so that it gets set
117  * up before the first allocation, which happens before entry to main().
118  */
119 const char * malloc_conf = "lg_chunk:0";
120 
121 /*
122  * Periodically pat the watchdog, preventing it from firing.
123  */
124 int
main(int argc,char * argv[])125 main(int argc, char *argv[])
126 {
127 	struct rtprio rtp;
128 	struct pidfh *pfh;
129 	pid_t otherpid;
130 
131 	if (getuid() != 0)
132 		errx(EX_SOFTWARE, "not super user");
133 
134 	parseargs(argc, argv);
135 
136 	if (do_syslog)
137 		openlog("watchdogd", LOG_CONS|LOG_NDELAY|LOG_PERROR,
138 		    LOG_DAEMON);
139 
140 	rtp.type = RTP_PRIO_REALTIME;
141 	rtp.prio = 0;
142 	if (rtprio(RTP_SET, 0, &rtp) == -1)
143 		err(EX_OSERR, "rtprio");
144 
145 	if (!is_dry_run && watchdog_init() == -1)
146 		errx(EX_SOFTWARE, "unable to initialize watchdog");
147 
148 	if (is_daemon) {
149 		if (watchdog_onoff(1) == -1)
150 			err(EX_OSERR, "patting the dog");
151 
152 		pfh = pidfile_open(pidfile, 0600, &otherpid);
153 		if (pfh == NULL) {
154 			if (errno == EEXIST) {
155 				watchdog_onoff(0);
156 				errx(EX_SOFTWARE, "%s already running, pid: %d",
157 				    getprogname(), otherpid);
158 			}
159 			warn("Cannot open or create pidfile");
160 		}
161 
162 		if (debugging == 0 && daemon(0, 0) == -1) {
163 			watchdog_onoff(0);
164 			pidfile_remove(pfh);
165 			err(EX_OSERR, "daemon");
166 		}
167 
168 		signal(SIGHUP, SIG_IGN);
169 		signal(SIGINT, sighandler);
170 		signal(SIGTERM, sighandler);
171 
172 		pidfile_write(pfh);
173 		if (madvise(0, 0, MADV_PROTECT) != 0)
174 			warn("madvise failed");
175 		if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0)
176 			warn("mlockall failed");
177 
178 		watchdog_loop();
179 
180 		/* exiting */
181 		pidfile_remove(pfh);
182 		return (EX_OK);
183 	} else {
184 		if (passive)
185 			timeout |= WD_PASSIVE;
186 		else
187 			timeout |= WD_ACTIVE;
188 		if (watchdog_patpat(timeout) < 0)
189 			err(EX_OSERR, "patting the dog");
190 		return (EX_OK);
191 	}
192 }
193 
194 static void
pow2ns_to_ts(int pow2ns,struct timespec * ts)195 pow2ns_to_ts(int pow2ns, struct timespec *ts)
196 {
197 	uint64_t ns;
198 
199 	ns = 1ULL << pow2ns;
200 	ts->tv_sec = ns / 1000000000ULL;
201 	ts->tv_nsec = ns % 1000000000ULL;
202 }
203 
204 /*
205  * Convert a timeout in seconds to N where 2^N nanoseconds is close to
206  * "seconds".
207  *
208  * The kernel expects the timeouts for watchdogs in "2^N nanosecond format".
209  */
210 static u_int
parse_timeout_to_pow2ns(char opt,const char * longopt,const char * myoptarg)211 parse_timeout_to_pow2ns(char opt, const char *longopt, const char *myoptarg)
212 {
213 	double a;
214 	u_int rv;
215 	struct timespec ts;
216 	struct timeval tv;
217 	int ticks;
218 	char shortopt[] = "- ";
219 
220 	if (!longopt)
221 		shortopt[1] = opt;
222 
223 	a = fetchtimeout(opt, longopt, myoptarg, 1);
224 
225 	if (a == 0)
226 		rv = WD_TO_NEVER;
227 	else
228 		rv = seconds_to_pow2ns(a);
229 	pow2ns_to_ts(rv, &ts);
230 	tstotv(&tv, &ts);
231 	ticks = tvtohz(&tv);
232 	if (debugging) {
233 		printf("Timeout for %s%s "
234 		    "is 2^%d nanoseconds "
235 		    "(in: %s sec -> out: %jd sec %ld ns -> %d ticks)\n",
236 		    longopt ? "-" : "", longopt ? longopt : shortopt,
237 		    rv,
238 		    myoptarg, (intmax_t)ts.tv_sec, ts.tv_nsec, ticks);
239 	}
240 	if (ticks <= 0) {
241 		errx(1, "Timeout for %s%s is too small, please choose a higher timeout.", longopt ? "-" : "", longopt ? longopt : shortopt);
242 	}
243 
244 	return (rv);
245 }
246 
247 /*
248  * Catch signals and begin shutdown process.
249  */
250 static void
sighandler(int signum)251 sighandler(int signum)
252 {
253 
254 	if (signum == SIGINT || signum == SIGTERM)
255 		end_program = 1;
256 }
257 
258 /*
259  * Open the watchdog device.
260  */
261 static int
watchdog_init(void)262 watchdog_init(void)
263 {
264 
265 	if (is_dry_run)
266 		return 0;
267 
268 	fd = open("/dev/" _PATH_WATCHDOG, O_RDWR);
269 	if (fd >= 0)
270 		return (0);
271 	warn("Could not open watchdog device");
272 	return (-1);
273 }
274 
275 /*
276  * If we are doing timing, then get the time.
277  */
278 static int
watchdog_getuptime(struct timespec * tp)279 watchdog_getuptime(struct timespec *tp)
280 {
281 	int error;
282 
283 	if (!do_timedog)
284 		return 0;
285 
286 	error = clock_gettime(CLOCK_UPTIME_FAST, tp);
287 	if (error)
288 		warn("clock_gettime");
289 	return (error);
290 }
291 
292 static long
watchdog_check_dogfunction_time(struct timespec * tp_start,struct timespec * tp_end)293 watchdog_check_dogfunction_time(struct timespec *tp_start,
294     struct timespec *tp_end)
295 {
296 	struct timeval tv_start, tv_end, tv_now, tv;
297 	const char *cmd_prefix, *cmd;
298 	struct timespec tp_now;
299 	int sec;
300 
301 	if (!do_timedog)
302 		return (0);
303 
304 	TIMESPEC_TO_TIMEVAL(&tv_start, tp_start);
305 	TIMESPEC_TO_TIMEVAL(&tv_end, tp_end);
306 	timersub(&tv_end, &tv_start, &tv);
307 	sec = tv.tv_sec;
308 	if (sec < carp_thresh_seconds)
309 		return (sec);
310 
311 	if (test_cmd) {
312 		cmd_prefix = "Watchdog program";
313 		cmd = test_cmd;
314 	} else {
315 		cmd_prefix = "Watchdog operation";
316 		cmd = "stat(\"/etc\", &sb)";
317 	}
318 	if (do_syslog)
319 		syslog(LOG_CRIT, "%s: '%s' took too long: "
320 		    "%d.%06ld seconds >= %d seconds threshold",
321 		    cmd_prefix, cmd, sec, (long)tv.tv_usec,
322 		    carp_thresh_seconds);
323 	else
324 		warnx("%s: '%s' took too long: "
325 		    "%d.%06ld seconds >= %d seconds threshold",
326 		    cmd_prefix, cmd, sec, (long)tv.tv_usec,
327 		    carp_thresh_seconds);
328 
329 	/*
330 	 * Adjust the sleep interval again in case syslog(3) took a non-trivial
331 	 * amount of time to run.
332 	 */
333 	if (watchdog_getuptime(&tp_now))
334 		return (sec);
335 	TIMESPEC_TO_TIMEVAL(&tv_now, &tp_now);
336 	timersub(&tv_now, &tv_start, &tv);
337 	sec = tv.tv_sec;
338 
339 	return (sec);
340 }
341 
342 /*
343  * Main program loop which is iterated every second.
344  */
345 static void
watchdog_loop(void)346 watchdog_loop(void)
347 {
348 	struct timespec ts_start, ts_end;
349 	struct stat sb;
350 	long waited;
351 	int error, failed, retries = 0;
352 
353 	while (end_program != 2) {
354 		failed = 0;
355 
356 		error = watchdog_getuptime(&ts_start);
357 		if (error) {
358 			end_program = 1;
359 			goto try_end;
360 		}
361 
362 		if (test_cmd != NULL)
363 			failed = system(test_cmd);
364 		else
365 			failed = stat("/etc", &sb);
366 
367 		error = watchdog_getuptime(&ts_end);
368 		if (error) {
369 			end_program = 1;
370 			goto try_end;
371 		}
372 
373 		if (failed == 0)
374 			watchdog_patpat(timeout|WD_ACTIVE);
375 
376 		waited = watchdog_check_dogfunction_time(&ts_start, &ts_end);
377 		if (nap - waited > 0)
378 			sleep(nap - waited);
379 
380 try_end:
381 		if (end_program != 0) {
382 			error = watchdog_onoff(0);
383 			if (error == 0) {
384 				end_program = 2;
385 			} else if (retries < 2) {
386 				warnx("Could not stop the watchdog, retrying");
387 				syslog(LOG_CRIT, "Could not stop the watchdog, retrying");
388 				retries ++;
389 			} else {
390 				warnx("Retry exhausted, existing anyway");
391 				syslog(LOG_CRIT, "stop watchdog took too long");
392 				end_program = 2;
393 			}
394 		}
395 	}
396 }
397 
398 /*
399  * Reset the watchdog timer. This function must be called periodically
400  * to keep the watchdog from firing.
401  */
402 static int
watchdog_patpat(u_int t)403 watchdog_patpat(u_int t)
404 {
405 
406 	if (is_dry_run)
407 		return 0;
408 
409 	return ioctl(fd, WDIOCPATPAT, &t);
410 }
411 
412 /*
413  * Toggle the kernel's watchdog. This routine is used to enable and
414  * disable the watchdog.
415  */
416 static int
watchdog_onoff(int onoff)417 watchdog_onoff(int onoff)
418 {
419 	int error;
420 
421 	/* fake successful watchdog op if a dry run */
422 	if (is_dry_run)
423 		return 0;
424 
425 	if (onoff) {
426 		/*
427 		 * Call the WDIOC_SETSOFT regardless of softtimeout_set
428 		 * because we'll need to turn it off if someone had turned
429 		 * it on.
430 		 */
431 		error = ioctl(fd, WDIOC_SETSOFT, &softtimeout_set);
432 		if (error) {
433 			warn("setting WDIOC_SETSOFT %d", softtimeout_set);
434 			return (error);
435 		}
436 		error = watchdog_patpat((timeout|WD_ACTIVE));
437 		if (error) {
438 			warn("watchdog_patpat failed");
439 			goto failsafe;
440 		}
441 		if (softtimeout_act_set) {
442 			error = ioctl(fd, WDIOC_SETSOFTTIMEOUTACT,
443 			    &softtimeout_act);
444 			if (error) {
445 				warn("setting WDIOC_SETSOFTTIMEOUTACT %d",
446 				    softtimeout_act);
447 				goto failsafe;
448 			}
449 		}
450 		if (pretimeout_set) {
451 			error = ioctl(fd, WDIOC_SETPRETIMEOUT, &pretimeout);
452 			if (error) {
453 				warn("setting WDIOC_SETPRETIMEOUT %d",
454 				    pretimeout);
455 				goto failsafe;
456 			}
457 		}
458 		if (pretimeout_act_set) {
459 			error = ioctl(fd, WDIOC_SETPRETIMEOUTACT,
460 			    &pretimeout_act);
461 			if (error) {
462 				warn("setting WDIOC_SETPRETIMEOUTACT %d",
463 				    pretimeout_act);
464 				goto failsafe;
465 			}
466 		}
467 		/* pat one more time for good measure */
468 		return watchdog_patpat((timeout|WD_ACTIVE));
469 	 } else {
470 		return watchdog_patpat(0);
471 	 }
472 failsafe:
473 	watchdog_patpat(0);
474 	return (error);
475 }
476 
477 /*
478  * Tell user how to use the program.
479  */
480 static void
usage(void)481 usage(void)
482 {
483 	if (is_daemon)
484 		fprintf(stderr, "usage:\n"
485 "  watchdogd [-dnSw] [-e cmd] [-I file] [-s sleep] [-t timeout]\n"
486 "            [-T script_timeout]\n"
487 "            [--debug]\n"
488 "            [--pretimeout seconds] [-pretimeout-action action]\n"
489 "            [--softtimeout] [-softtimeout-action action]\n"
490 );
491 	else
492 		fprintf(stderr, "usage: watchdog [-d] [-t timeout]\n");
493 	exit(EX_USAGE);
494 }
495 
496 static long
fetchtimeout(int opt,const char * longopt,const char * myoptarg,int zero_ok)497 fetchtimeout(int opt, const char *longopt, const char *myoptarg, int zero_ok)
498 {
499 	const char *errstr;
500 	char *p;
501 	long rv;
502 
503 	errstr = NULL;
504 	p = NULL;
505 	errno = 0;
506 	rv = strtol(myoptarg, &p, 0);
507 	if ((p != NULL && *p != '\0') || errno != 0)
508 		errstr = "is not a number";
509 	if (rv < 0 || (!zero_ok && rv == 0))
510 		errstr = "must be greater than zero";
511 	if (errstr) {
512 		if (longopt)
513 			errx(EX_USAGE, "--%s argument %s", longopt, errstr);
514 		else
515 			errx(EX_USAGE, "-%c argument %s", opt, errstr);
516 	}
517 	return (rv);
518 }
519 
520 struct act_tbl {
521 	const char *at_act;
522 	int at_value;
523 };
524 
525 static const struct act_tbl act_tbl[] = {
526 	{ "panic", WD_SOFT_PANIC },
527 	{ "ddb", WD_SOFT_DDB },
528 	{ "log", WD_SOFT_LOG },
529 	{ "printf", WD_SOFT_PRINTF },
530 	{ NULL, 0 }
531 };
532 
533 static void
timeout_act_error(const char * lopt,const char * badact)534 timeout_act_error(const char *lopt, const char *badact)
535 {
536 	char *opts, *oldopts;
537 	int i;
538 
539 	opts = NULL;
540 	for (i = 0; act_tbl[i].at_act != NULL; i++) {
541 		oldopts = opts;
542 		if (asprintf(&opts, "%s%s%s",
543 		    oldopts == NULL ? "" : oldopts,
544 		    oldopts == NULL ? "" : ", ",
545 		    act_tbl[i].at_act) == -1)
546 			err(EX_OSERR, "malloc");
547 		free(oldopts);
548 	}
549 	warnx("bad --%s argument '%s' must be one of (%s).",
550 	    lopt, badact, opts);
551 	usage();
552 }
553 
554 /*
555  * Take a comma separated list of actions and or the flags
556  * together for the ioctl.
557  */
558 static int
timeout_act_str2int(const char * lopt,const char * acts)559 timeout_act_str2int(const char *lopt, const char *acts)
560 {
561 	int i;
562 	char *dupacts, *tofree;
563 	char *o;
564 	int rv = 0;
565 
566 	tofree = dupacts = strdup(acts);
567 	if (!tofree)
568 		err(EX_OSERR, "malloc");
569 	while ((o = strsep(&dupacts, ",")) != NULL) {
570 		for (i = 0; act_tbl[i].at_act != NULL; i++) {
571 			if (!strcmp(o, act_tbl[i].at_act)) {
572 				rv |= act_tbl[i].at_value;
573 				break;
574 			}
575 		}
576 		if (act_tbl[i].at_act == NULL)
577 			timeout_act_error(lopt, o);
578 	}
579 	free(tofree);
580 	return rv;
581 }
582 
583 int
tstotv(struct timeval * tv,struct timespec * ts)584 tstotv(struct timeval *tv, struct timespec *ts)
585 {
586 
587 	tv->tv_sec = ts->tv_sec;
588 	tv->tv_usec = ts->tv_nsec / 1000;
589 	return 0;
590 }
591 
592 /*
593  * Convert a timeval to a number of ticks.
594  * Mostly copied from the kernel.
595  */
596 int
tvtohz(struct timeval * tv)597 tvtohz(struct timeval *tv)
598 {
599 	register unsigned long ticks;
600 	register long sec, usec;
601 	int hz;
602 	size_t hzsize;
603 	int error;
604 	int tick;
605 
606 	hzsize = sizeof(hz);
607 
608 	error = sysctlbyname("kern.hz", &hz, &hzsize, NULL, 0);
609 	if (error)
610 		err(1, "sysctlbyname kern.hz");
611 
612 	tick = 1000000 / hz;
613 
614 	/*
615 	 * If the number of usecs in the whole seconds part of the time
616 	 * difference fits in a long, then the total number of usecs will
617 	 * fit in an unsigned long.  Compute the total and convert it to
618 	 * ticks, rounding up and adding 1 to allow for the current tick
619 	 * to expire.  Rounding also depends on unsigned long arithmetic
620 	 * to avoid overflow.
621 	 *
622 	 * Otherwise, if the number of ticks in the whole seconds part of
623 	 * the time difference fits in a long, then convert the parts to
624 	 * ticks separately and add, using similar rounding methods and
625 	 * overflow avoidance.  This method would work in the previous
626 	 * case but it is slightly slower and assumes that hz is integral.
627 	 *
628 	 * Otherwise, round the time difference down to the maximum
629 	 * representable value.
630 	 *
631 	 * If ints have 32 bits, then the maximum value for any timeout in
632 	 * 10ms ticks is 248 days.
633 	 */
634 	sec = tv->tv_sec;
635 	usec = tv->tv_usec;
636 	if (usec < 0) {
637 		sec--;
638 		usec += 1000000;
639 	}
640 	if (sec < 0) {
641 #ifdef DIAGNOSTIC
642 		if (usec > 0) {
643 			sec++;
644 			usec -= 1000000;
645 		}
646 		printf("tvotohz: negative time difference %ld sec %ld usec\n",
647 		    sec, usec);
648 #endif
649 		ticks = 1;
650 	} else if (sec <= LONG_MAX / 1000000)
651 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
652 		    / tick + 1;
653 	else if (sec <= LONG_MAX / hz)
654 		ticks = sec * hz
655 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
656 	else
657 		ticks = LONG_MAX;
658 	if (ticks > INT_MAX)
659 		ticks = INT_MAX;
660 	return ((int)ticks);
661 }
662 
663 static int
seconds_to_pow2ns(int seconds)664 seconds_to_pow2ns(int seconds)
665 {
666 	uint64_t power;
667 	uint64_t ns;
668 	uint64_t shifted;
669 
670 	if (seconds <= 0)
671 		errx(1, "seconds %d < 0", seconds);
672 	ns = ((uint64_t)seconds) * 1000000000ULL;
673 	power = flsll(ns);
674 	shifted = 1ULL << power;
675 	if (shifted <= ns) {
676 		power++;
677 	}
678 	if (debugging) {
679 		printf("shifted %lld\n", (long long)shifted);
680 		printf("seconds_to_pow2ns: seconds: %d, ns %lld, power %d\n",
681 		    seconds, (long long)ns, (int)power);
682 	}
683 	return (power);
684 }
685 
686 
687 /*
688  * Handle the few command line arguments supported.
689  */
690 static void
parseargs(int argc,char * argv[])691 parseargs(int argc, char *argv[])
692 {
693 	int longindex;
694 	int c;
695 	const char *lopt;
696 
697 	/*
698 	 * if we end with a 'd' aka 'watchdogd' then we are the daemon program,
699 	 * otherwise run as a command line utility.
700 	 */
701 	c = strlen(argv[0]);
702 	if (argv[0][c - 1] == 'd')
703 		is_daemon = 1;
704 
705 	if (is_daemon)
706 		getopt_shortopts = "I:de:ns:t:ST:w?";
707 	else
708 		getopt_shortopts = "dt:?";
709 
710 	while ((c = getopt_long(argc, argv, getopt_shortopts, longopts,
711 		    &longindex)) != -1) {
712 		switch (c) {
713 		case 'I':
714 			pidfile = optarg;
715 			break;
716 		case 'd':
717 			debugging = 1;
718 			break;
719 		case 'e':
720 			test_cmd = strdup(optarg);
721 			break;
722 		case 'n':
723 			is_dry_run = 1;
724 			break;
725 #ifdef notyet
726 		case 'p':
727 			passive = 1;
728 			break;
729 #endif
730 		case 's':
731 			nap = fetchtimeout(c, NULL, optarg, 0);
732 			break;
733 		case 'S':
734 			do_syslog = 0;
735 			break;
736 		case 't':
737 			timeout_sec = atoi(optarg);
738 			timeout = parse_timeout_to_pow2ns(c, NULL, optarg);
739  			if (debugging)
740  				printf("Timeout is 2^%d nanoseconds\n",
741  				    timeout);
742 			break;
743 		case 'T':
744 			carp_thresh_seconds =
745 			    fetchtimeout(c, "NULL", optarg, 0);
746 			break;
747 		case 'w':
748 			do_timedog = 1;
749 			break;
750 		case 0:
751 			lopt = longopts[longindex].name;
752 			if (!strcmp(lopt, "pretimeout")) {
753 				pretimeout = fetchtimeout(0, lopt, optarg, 0);
754 			} else if (!strcmp(lopt, "pretimeout-action")) {
755 				pretimeout_act = timeout_act_str2int(lopt,
756 				    optarg);
757 			} else if (!strcmp(lopt, "softtimeout-action")) {
758 				softtimeout_act = timeout_act_str2int(lopt,
759 				    optarg);
760 			} else {
761 		/*		warnx("bad option at index %d: %s", optind,
762 				    argv[optind]);
763 				usage();
764 				*/
765 			}
766 			break;
767 		case '?':
768 		default:
769 			usage();
770 			/* NOTREACHED */
771 		}
772 	}
773 
774 	if (carp_thresh_seconds == -1)
775 		carp_thresh_seconds = nap;
776 
777 	if (argc != optind)
778 		errx(EX_USAGE, "extra arguments.");
779 	if (is_daemon && timeout < WD_TO_1SEC)
780 		errx(EX_USAGE, "-t argument is less than one second.");
781 	if (pretimeout_set) {
782 		struct timespec ts;
783 
784 		pow2ns_to_ts(timeout, &ts);
785 		if (pretimeout >= (uintmax_t)ts.tv_sec) {
786 			errx(EX_USAGE,
787 			    "pretimeout (%d) >= timeout (%d -> %ld)\n"
788 			    "see manual section TIMEOUT RESOLUTION",
789 			    pretimeout, timeout_sec, (long)ts.tv_sec);
790 		}
791 	}
792 }
793