xref: /freebsd/bin/timeout/timeout.c (revision 15e4b8d5ef845066819c4cbb5d03b63148688298)
1 /*-
2  * Copyright (c) 2014 Baptiste Daroussin <bapt@FreeBSD.org>
3  * Copyright (c) 2014 Vsevolod Stakhov <vsevolod@FreeBSD.org>
4  * Copyright (c) 2025 Aaron LI <aly@aaronly.me>
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  *    in this position and unchanged.
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(S) ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include <sys/procctl.h>
31 #include <sys/resource.h>
32 #include <sys/time.h>
33 #include <sys/wait.h>
34 
35 #include <err.h>
36 #include <errno.h>
37 #include <getopt.h>
38 #include <signal.h>
39 #include <stdarg.h>
40 #include <stdbool.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 #define EXIT_TIMEOUT	124
47 #define EXIT_INVALID	125
48 #define EXIT_CMD_ERROR	126
49 #define EXIT_CMD_NOENT	127
50 
51 static volatile sig_atomic_t sig_chld = 0;
52 static volatile sig_atomic_t sig_alrm = 0;
53 static volatile sig_atomic_t sig_term = 0; /* signal to terminate children */
54 static volatile sig_atomic_t sig_other = 0; /* signal to propagate */
55 static int killsig = SIGTERM; /* signal to kill children */
56 static const char *command = NULL;
57 static bool verbose = false;
58 
59 static void __dead2
60 usage(void)
61 {
62 	fprintf(stderr,
63 		"Usage: %s [-f | --foreground] [-k time | --kill-after time]"
64 		" [-p | --preserve-status] [-s signal | --signal signal] "
65 		" [-v | --verbose] <duration> <command> [arg ...]\n",
66 		getprogname());
67 	exit(EXIT_FAILURE);
68 }
69 
70 static void
71 logv(const char *fmt, ...)
72 {
73 	va_list ap;
74 
75 	if (!verbose)
76 		return;
77 
78 	va_start(ap, fmt);
79 	vwarnx(fmt, ap);
80 	va_end(ap);
81 }
82 
83 static double
84 parse_duration(const char *duration)
85 {
86 	double ret;
87 	char *suffix;
88 
89 	ret = strtod(duration, &suffix);
90 	if (suffix == duration)
91 		errx(EXIT_INVALID, "duration is not a number");
92 
93 	if (*suffix == '\0')
94 		return (ret);
95 
96 	if (suffix[1] != '\0')
97 		errx(EXIT_INVALID, "duration unit suffix too long");
98 
99 	switch (*suffix) {
100 	case 's':
101 		break;
102 	case 'm':
103 		ret *= 60;
104 		break;
105 	case 'h':
106 		ret *= 60 * 60;
107 		break;
108 	case 'd':
109 		ret *= 60 * 60 * 24;
110 		break;
111 	default:
112 		errx(EXIT_INVALID, "duration unit suffix invalid");
113 	}
114 
115 	if (ret < 0 || ret >= 100000000UL)
116 		errx(EXIT_INVALID, "duration out of range");
117 
118 	return (ret);
119 }
120 
121 static int
122 parse_signal(const char *str)
123 {
124 	int sig, i;
125 	const char *errstr;
126 
127 	sig = strtonum(str, 1, sys_nsig - 1, &errstr);
128 	if (errstr == NULL)
129 		return (sig);
130 
131 	if (strncasecmp(str, "SIG", 3) == 0)
132 		str += 3;
133 	for (i = 1; i < sys_nsig; i++) {
134 		if (strcasecmp(str, sys_signame[i]) == 0)
135 			return (i);
136 	}
137 
138 	errx(EXIT_INVALID, "invalid signal");
139 }
140 
141 static void
142 sig_handler(int signo)
143 {
144 	if (signo == killsig) {
145 		sig_term = signo;
146 		return;
147 	}
148 
149 	switch (signo) {
150 	case SIGCHLD:
151 		sig_chld = 1;
152 		break;
153 	case SIGALRM:
154 		sig_alrm = 1;
155 		break;
156 	case SIGHUP:
157 	case SIGINT:
158 	case SIGQUIT:
159 	case SIGILL:
160 	case SIGTRAP:
161 	case SIGABRT:
162 	case SIGEMT:
163 	case SIGFPE:
164 	case SIGBUS:
165 	case SIGSEGV:
166 	case SIGSYS:
167 	case SIGPIPE:
168 	case SIGTERM:
169 	case SIGXCPU:
170 	case SIGXFSZ:
171 	case SIGVTALRM:
172 	case SIGPROF:
173 	case SIGUSR1:
174 	case SIGUSR2:
175 		/*
176 		 * Signals with default action to terminate the process.
177 		 * See the sigaction(2) man page.
178 		 */
179 		sig_term = signo;
180 		break;
181 	default:
182 		sig_other = signo;
183 		break;
184 	}
185 }
186 
187 static void
188 send_sig(pid_t pid, int signo, bool foreground)
189 {
190 	struct procctl_reaper_kill rk;
191 	int error;
192 
193 	logv("sending signal %s(%d) to command '%s'",
194 	     sys_signame[signo], signo, command);
195 	if (foreground) {
196 		if (kill(pid, signo) == -1) {
197 			if (errno != ESRCH)
198 				warnx("kill(%d, %s)", (int)pid,
199 				    sys_signame[signo]);
200 		}
201 	} else {
202 		memset(&rk, 0, sizeof(rk));
203 		rk.rk_sig = signo;
204 		error = procctl(P_PID, getpid(), PROC_REAP_KILL, &rk);
205 		if (error == 0 || (error == -1 && errno == ESRCH))
206 			;
207 		else if (error == -1)
208 			warnx("procctl(PROC_REAP_KILL)");
209 		else if (rk.rk_fpid > 0)
210 			warnx("failed to signal some processes: first pid=%d",
211 			      (int)rk.rk_fpid);
212 		logv("signaled %u processes", rk.rk_killed);
213 	}
214 
215 	/*
216 	 * If the child process was stopped by a signal, POSIX.1-2024
217 	 * requires to send a SIGCONT signal.  However, the standard also
218 	 * allows to send a SIGCONT regardless of the stop state, as we
219 	 * are doing here.
220 	 */
221 	if (signo != SIGKILL && signo != SIGSTOP && signo != SIGCONT) {
222 		logv("sending signal %s(%d) to command '%s'",
223 		     sys_signame[SIGCONT], SIGCONT, command);
224 		if (foreground) {
225 			kill(pid, SIGCONT);
226 		} else {
227 			memset(&rk, 0, sizeof(rk));
228 			rk.rk_sig = SIGCONT;
229 			procctl(P_PID, getpid(), PROC_REAP_KILL, &rk);
230 		}
231 	}
232 }
233 
234 static void
235 set_interval(double iv)
236 {
237 	struct itimerval tim;
238 
239 	memset(&tim, 0, sizeof(tim));
240 	if (iv > 0) {
241 		tim.it_value.tv_sec = (time_t)iv;
242 		iv -= (double)(time_t)iv;
243 		tim.it_value.tv_usec = (suseconds_t)(iv * 1000000UL);
244 	}
245 
246 	if (setitimer(ITIMER_REAL, &tim, NULL) == -1)
247 		err(EXIT_FAILURE, "setitimer()");
248 }
249 
250 /*
251  * In order to avoid any possible ambiguity that a shell may not set '$?' to
252  * '128+signal_number', POSIX.1-2024 requires that timeout mimic the wait
253  * status of the child process by terminating itself with the same signal,
254  * while disabling core generation.
255  */
256 static void __dead2
257 kill_self(int signo)
258 {
259 	sigset_t mask;
260 	struct rlimit rl;
261 
262 	/* Reset the signal disposition and make sure it's unblocked. */
263 	signal(signo, SIG_DFL);
264 	sigfillset(&mask);
265 	sigdelset(&mask, signo);
266 	sigprocmask(SIG_SETMASK, &mask, NULL);
267 
268 	/* Disable core generation. */
269 	memset(&rl, 0, sizeof(rl));
270 	setrlimit(RLIMIT_CORE, &rl);
271 
272 	logv("killing self with signal %s(%d)", sys_signame[signo], signo);
273 	kill(getpid(), signo);
274 	err(128 + signo, "signal %s(%d) failed to kill self",
275 	    sys_signame[signo], signo);
276 }
277 
278 int
279 main(int argc, char **argv)
280 {
281 	int ch, status, sig;
282 	int pstat = 0;
283 	pid_t pid, cpid;
284 	double first_kill;
285 	double second_kill = 0;
286 	bool foreground = false;
287 	bool preserve = false;
288 	bool timedout = false;
289 	bool do_second_kill = false;
290 	bool child_done = false;
291 	sigset_t zeromask, allmask, oldmask;
292 	struct sigaction sa;
293 	struct procctl_reaper_status info;
294 
295 	const char optstr[] = "+fhk:ps:v";
296 	const struct option longopts[] = {
297 		{ "foreground",      no_argument,       NULL, 'f' },
298 		{ "help",            no_argument,       NULL, 'h' },
299 		{ "kill-after",      required_argument, NULL, 'k' },
300 		{ "preserve-status", no_argument,       NULL, 'p' },
301 		{ "signal",          required_argument, NULL, 's' },
302 		{ "verbose",         no_argument,       NULL, 'v' },
303 		{ NULL,              0,                 NULL,  0  },
304 	};
305 
306 	while ((ch = getopt_long(argc, argv, optstr, longopts, NULL)) != -1) {
307 		switch (ch) {
308 		case 'f':
309 			foreground = true;
310 			break;
311 		case 'k':
312 			do_second_kill = true;
313 			second_kill = parse_duration(optarg);
314 			break;
315 		case 'p':
316 			preserve = true;
317 			break;
318 		case 's':
319 			killsig = parse_signal(optarg);
320 			break;
321 		case 'v':
322 			verbose = true;
323 			break;
324 		case 0:
325 			break;
326 		default:
327 			usage();
328 		}
329 	}
330 
331 	argc -= optind;
332 	argv += optind;
333 	if (argc < 2)
334 		usage();
335 
336 	first_kill = parse_duration(argv[0]);
337 	argc--;
338 	argv++;
339 	command = argv[0];
340 
341 	if (!foreground) {
342 		/* Acquire a reaper */
343 		if (procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) == -1)
344 			err(EXIT_FAILURE, "procctl(PROC_REAP_ACQUIRE)");
345 	}
346 
347 	/* Block all signals to avoid racing against the child. */
348 	sigfillset(&allmask);
349 	if (sigprocmask(SIG_BLOCK, &allmask, &oldmask) == -1)
350 		err(EXIT_FAILURE, "sigprocmask()");
351 
352 	pid = fork();
353 	if (pid == -1) {
354 		err(EXIT_FAILURE, "fork()");
355 	} else if (pid == 0) {
356 		/*
357 		 * child process
358 		 *
359 		 * POSIX.1-2024 requires that the child process inherit the
360 		 * same signal dispositions as the timeout(1) utility
361 		 * inherited, except for the signal to be sent upon timeout.
362 		 */
363 		signal(killsig, SIG_DFL);
364 		if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1)
365 			err(EXIT_FAILURE, "sigprocmask(oldmask)");
366 
367 		execvp(argv[0], argv);
368 		warn("exec(%s)", argv[0]);
369 		_exit(errno == ENOENT ? EXIT_CMD_NOENT : EXIT_CMD_ERROR);
370 	}
371 
372 	/* parent continues here */
373 
374 	/* Catch all signals in order to propagate them. */
375 	memset(&sa, 0, sizeof(sa));
376 	sigfillset(&sa.sa_mask);
377 	sa.sa_handler = sig_handler;
378 	sa.sa_flags = SA_RESTART;
379 	for (sig = 1; sig < sys_nsig; sig++) {
380 		if (sig == SIGKILL || sig == SIGSTOP || sig == SIGCONT ||
381 		    sig == SIGTTIN || sig == SIGTTOU)
382 			continue;
383 		if (sigaction(sig, &sa, NULL) == -1)
384 			err(EXIT_FAILURE, "sigaction(%d)", sig);
385 	}
386 
387 	/* Don't stop if background child needs TTY */
388 	signal(SIGTTIN, SIG_IGN);
389 	signal(SIGTTOU, SIG_IGN);
390 
391 	set_interval(first_kill);
392 	sigemptyset(&zeromask);
393 
394 	for (;;) {
395 		sigsuspend(&zeromask);
396 
397 		if (sig_chld) {
398 			sig_chld = 0;
399 
400 			while ((cpid = waitpid(-1, &status, WNOHANG)) != 0) {
401 				if (cpid < 0) {
402 					if (errno != EINTR)
403 						break;
404 				} else if (cpid == pid) {
405 					pstat = status;
406 					child_done = true;
407 					logv("child terminated: pid=%d, "
408 					     "exit=%d, signal=%d",
409 					     (int)pid, WEXITSTATUS(status),
410 					     WTERMSIG(status));
411 				} else {
412 					/*
413 					 * Collect grandchildren zombies.
414 					 * Only effective if we're a reaper.
415 					 */
416 					logv("collected zombie: pid=%d, "
417 					     "exit=%d, signal=%d",
418 					     (int)cpid, WEXITSTATUS(status),
419 					     WTERMSIG(status));
420 				}
421 			}
422 			if (child_done) {
423 				if (foreground) {
424 					break;
425 				} else {
426 					procctl(P_PID, getpid(),
427 					    	PROC_REAP_STATUS, &info);
428 					if (info.rs_children == 0)
429 						break;
430 				}
431 			}
432 		} else if (sig_alrm || sig_term) {
433 			if (sig_alrm) {
434 				sig = killsig;
435 				sig_alrm = 0;
436 				timedout = true;
437 				logv("time limit reached or received SIGALRM");
438 			} else {
439 				sig = sig_term;
440 				sig_term = 0;
441 				logv("received terminating signal %s(%d)",
442 				     sys_signame[sig], sig);
443 			}
444 
445 			send_sig(pid, sig, foreground);
446 
447 			if (do_second_kill) {
448 				set_interval(second_kill);
449 				do_second_kill = false;
450 				killsig = SIGKILL;
451 			}
452 
453 		} else if (sig_other) {
454 			/* Propagate any other signals. */
455 			sig = sig_other;
456 			sig_other = 0;
457 			logv("received signal %s(%d)", sys_signame[sig], sig);
458 
459 			send_sig(pid, sig, foreground);
460 		}
461 	}
462 
463 	if (!foreground)
464 		procctl(P_PID, getpid(), PROC_REAP_RELEASE, NULL);
465 
466 	if (timedout && !preserve) {
467 		pstat = EXIT_TIMEOUT;
468 	} else {
469 		if (WIFSIGNALED(pstat))
470 			kill_self(WTERMSIG(pstat));
471 			/* NOTREACHED */
472 
473 		if (WIFEXITED(pstat))
474 			pstat = WEXITSTATUS(pstat);
475 	}
476 
477 	return (pstat);
478 }
479