xref: /freebsd/bin/timeout/timeout.c (revision c5cdc13045650a9daf33dd6316ef57496e4a5dbc)
1 /*-
2  * Copyright (c) 2014 Baptiste Daroussin <bapt@FreeBSD.org>
3  * Copyright (c) 2014 Vsevolod Stakhov <vsevolod@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer
11  *    in this position and unchanged.
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  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 #include <sys/procctl.h>
30 #include <sys/time.h>
31 #include <sys/wait.h>
32 
33 #include <err.h>
34 #include <errno.h>
35 #include <getopt.h>
36 #include <signal.h>
37 #include <stdbool.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 
43 #define EXIT_TIMEOUT	124
44 #define EXIT_INVALID	125
45 #define EXIT_CMD_ERROR	126
46 #define EXIT_CMD_NOENT	127
47 
48 static volatile sig_atomic_t sig_chld = 0;
49 static volatile sig_atomic_t sig_term = 0;
50 static volatile sig_atomic_t sig_alrm = 0;
51 static volatile sig_atomic_t sig_ign = 0;
52 static const char *command = NULL;
53 static bool verbose = false;
54 
55 static void __dead2
56 usage(void)
57 {
58 	fprintf(stderr,
59 		"Usage: %s [--foreground] [-k time | --kill-after time]"
60 		" [--preserve-status] [-s signal | --signal signal] "
61 		" [-v | --verbose] <duration> <command> [arg ...]\n",
62 		getprogname());
63 	exit(EXIT_FAILURE);
64 }
65 
66 static double
67 parse_duration(const char *duration)
68 {
69 	double ret;
70 	char *suffix;
71 
72 	ret = strtod(duration, &suffix);
73 	if (suffix == duration)
74 		errx(EXIT_INVALID, "duration is not a number");
75 
76 	if (*suffix == '\0')
77 		return (ret);
78 
79 	if (suffix[1] != '\0')
80 		errx(EXIT_INVALID, "duration unit suffix too long");
81 
82 	switch (*suffix) {
83 	case 's':
84 		break;
85 	case 'm':
86 		ret *= 60;
87 		break;
88 	case 'h':
89 		ret *= 60 * 60;
90 		break;
91 	case 'd':
92 		ret *= 60 * 60 * 24;
93 		break;
94 	default:
95 		errx(EXIT_INVALID, "duration unit suffix invalid");
96 	}
97 
98 	if (ret < 0 || ret >= 100000000UL)
99 		errx(EXIT_INVALID, "duration out of range");
100 
101 	return (ret);
102 }
103 
104 static int
105 parse_signal(const char *str)
106 {
107 	int sig, i;
108 	const char *errstr;
109 
110 	sig = strtonum(str, 1, sys_nsig - 1, &errstr);
111 	if (errstr == NULL)
112 		return (sig);
113 
114 	if (strncasecmp(str, "SIG", 3) == 0)
115 		str += 3;
116 	for (i = 1; i < sys_nsig; i++) {
117 		if (strcasecmp(str, sys_signame[i]) == 0)
118 			return (i);
119 	}
120 
121 	errx(EXIT_INVALID, "invalid signal");
122 }
123 
124 static void
125 sig_handler(int signo)
126 {
127 	if (sig_ign != 0 && signo == sig_ign) {
128 		sig_ign = 0;
129 		return;
130 	}
131 
132 	switch (signo) {
133 	case SIGINT:
134 	case SIGHUP:
135 	case SIGQUIT:
136 	case SIGTERM:
137 		sig_term = signo;
138 		break;
139 	case SIGCHLD:
140 		sig_chld = 1;
141 		break;
142 	case SIGALRM:
143 		sig_alrm = 1;
144 		break;
145 	}
146 }
147 
148 static void
149 send_sig(pid_t pid, int signo)
150 {
151 	if (verbose) {
152 		warnx("sending signal %s(%d) to command '%s'",
153 		      sys_signame[signo], signo, command);
154 	}
155 	kill(pid, signo);
156 }
157 
158 static void
159 set_interval(double iv)
160 {
161 	struct itimerval tim;
162 
163 	memset(&tim, 0, sizeof(tim));
164 	if (iv > 0) {
165 		tim.it_value.tv_sec = (time_t)iv;
166 		iv -= (double)(time_t)iv;
167 		tim.it_value.tv_usec = (suseconds_t)(iv * 1000000UL);
168 	}
169 
170 	if (setitimer(ITIMER_REAL, &tim, NULL) == -1)
171 		err(EXIT_FAILURE, "setitimer()");
172 }
173 
174 int
175 main(int argc, char **argv)
176 {
177 	int ch, status, sig;
178 	int foreground, preserve;
179 	int pstat = 0;
180 	int killsig = SIGTERM;
181 	size_t i;
182 	pid_t pid, cpid;
183 	double first_kill;
184 	double second_kill;
185 	bool timedout = false;
186 	bool do_second_kill = false;
187 	bool child_done = false;
188 	struct sigaction signals;
189 	struct procctl_reaper_status info;
190 	struct procctl_reaper_kill killemall;
191 	int signums[] = {
192 		-1,
193 		SIGTERM,
194 		SIGINT,
195 		SIGHUP,
196 		SIGCHLD,
197 		SIGALRM,
198 		SIGQUIT,
199 	};
200 
201 	foreground = preserve = 0;
202 	second_kill = 0;
203 
204 	const struct option longopts[] = {
205 		{ "foreground",      no_argument,       &foreground,  1  },
206 		{ "help",            no_argument,       NULL,        'h' },
207 		{ "kill-after",      required_argument, NULL,        'k' },
208 		{ "preserve-status", no_argument,       &preserve,    1  },
209 		{ "signal",          required_argument, NULL,        's' },
210 		{ "verbose",         no_argument,       NULL,        'v' },
211 		{ NULL,              0,                 NULL,         0  },
212 	};
213 
214 	while ((ch = getopt_long(argc, argv, "+k:s:vh", longopts, NULL)) != -1) {
215 		switch (ch) {
216 		case 'k':
217 			do_second_kill = true;
218 			second_kill = parse_duration(optarg);
219 			break;
220 		case 's':
221 			killsig = parse_signal(optarg);
222 			break;
223 		case 'v':
224 			verbose = true;
225 			break;
226 		case 0:
227 			break;
228 		default:
229 			usage();
230 		}
231 	}
232 
233 	argc -= optind;
234 	argv += optind;
235 	if (argc < 2)
236 		usage();
237 
238 	first_kill = parse_duration(argv[0]);
239 	argc--;
240 	argv++;
241 	command = argv[0];
242 
243 	if (!foreground) {
244 		/* Acquire a reaper */
245 		if (procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) == -1)
246 			err(EXIT_FAILURE, "procctl(PROC_REAP_ACQUIRE)");
247 	}
248 
249 	memset(&signals, 0, sizeof(signals));
250 	sigemptyset(&signals.sa_mask);
251 
252 	if (killsig != SIGKILL && killsig != SIGSTOP)
253 		signums[0] = killsig;
254 
255 	for (i = 0; i < sizeof(signums) / sizeof(signums[0]); i++)
256 		sigaddset(&signals.sa_mask, signums[i]);
257 
258 	signals.sa_handler = sig_handler;
259 	signals.sa_flags = SA_RESTART;
260 
261 	for (i = 0; i < sizeof(signums) / sizeof(signums[0]); i++) {
262 		if (signums[i] > 0 &&
263 		    sigaction(signums[i], &signals, NULL) == -1)
264 			err(EXIT_FAILURE, "sigaction()");
265 	}
266 
267 	/* Don't stop if background child needs TTY */
268 	signal(SIGTTIN, SIG_IGN);
269 	signal(SIGTTOU, SIG_IGN);
270 
271 	pid = fork();
272 	if (pid == -1) {
273 		err(EXIT_FAILURE, "fork()");
274 	} else if (pid == 0) {
275 		/* child process */
276 		signal(SIGTTIN, SIG_DFL);
277 		signal(SIGTTOU, SIG_DFL);
278 
279 		execvp(argv[0], argv);
280 		warn("exec(%s)", argv[0]);
281 		_exit(errno == ENOENT ? EXIT_CMD_NOENT : EXIT_CMD_ERROR);
282 	}
283 
284 	/* parent continues here */
285 
286 	if (sigprocmask(SIG_BLOCK, &signals.sa_mask, NULL) == -1)
287 		err(EXIT_FAILURE, "sigprocmask()");
288 
289 	set_interval(first_kill);
290 	sigemptyset(&signals.sa_mask);
291 
292 	for (;;) {
293 		sigsuspend(&signals.sa_mask);
294 
295 		if (sig_chld) {
296 			sig_chld = 0;
297 
298 			while ((cpid = waitpid(-1, &status, WNOHANG)) != 0) {
299 				if (cpid < 0) {
300 					if (errno != EINTR)
301 						break;
302 				} else if (cpid == pid) {
303 					pstat = status;
304 					child_done = true;
305 				}
306 			}
307 			if (child_done) {
308 				if (foreground) {
309 					break;
310 				} else {
311 					procctl(P_PID, getpid(),
312 					    	PROC_REAP_STATUS, &info);
313 					if (info.rs_children == 0)
314 						break;
315 				}
316 			}
317 		} else if (sig_alrm || sig_term) {
318 			if (sig_alrm) {
319 				sig = killsig;
320 				sig_alrm = 0;
321 				timedout = true;
322 			} else {
323 				sig = sig_term;
324 				sig_term = 0;
325 			}
326 
327 			if (foreground) {
328 				send_sig(pid, sig);
329 			} else {
330 				killemall.rk_sig = sig;
331 				killemall.rk_flags = 0;
332 				procctl(P_PID, getpid(), PROC_REAP_KILL,
333 					&killemall);
334 			}
335 
336 			if (do_second_kill) {
337 				set_interval(second_kill);
338 				do_second_kill = false;
339 				sig_ign = killsig;
340 				killsig = SIGKILL;
341 			} else {
342 				break;
343 			}
344 		}
345 	}
346 
347 	while (!child_done && wait(&pstat) == -1) {
348 		if (errno != EINTR)
349 			err(EXIT_FAILURE, "wait()");
350 	}
351 
352 	if (!foreground)
353 		procctl(P_PID, getpid(), PROC_REAP_RELEASE, NULL);
354 
355 	if (timedout && !preserve) {
356 		pstat = EXIT_TIMEOUT;
357 	} else {
358 		if (WIFEXITED(pstat))
359 			pstat = WEXITSTATUS(pstat);
360 		else if (WIFSIGNALED(pstat))
361 			pstat = 128 + WTERMSIG(pstat);
362 	}
363 
364 	return (pstat);
365 }
366