xref: /freebsd/bin/timeout/timeout.c (revision 35503fe28eb51ef606cf4ae077a96b3c717199d3)
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 sig_atomic_t sig_chld = 0;
49 static sig_atomic_t sig_term = 0;
50 static sig_atomic_t sig_alrm = 0;
51 static sig_atomic_t sig_ign = 0;
52 static const char *command = NULL;
53 static bool verbose = false;
54 
55 static void
56 usage(void)
57 {
58 
59 	fprintf(stderr, "Usage: %s [-k time | --kill-after time]"
60 		" [-s sig | --signal sig] [-v | --verbose] [--foreground]"
61 		" [--preserve-status] <duration> <command> <arg ...>\n",
62 		getprogname());
63 
64 	exit(EXIT_FAILURE);
65 }
66 
67 static double
68 parse_duration(const char *duration)
69 {
70 	double ret;
71 	char *suffix;
72 
73 	ret = strtod(duration, &suffix);
74 	if (suffix == duration)
75 		errx(EXIT_INVALID, "duration is not a number");
76 
77 	if (*suffix == '\0')
78 		return (ret);
79 
80 	if (suffix[1] != '\0')
81 		errx(EXIT_INVALID, "duration unit suffix too long");
82 
83 	switch (*suffix) {
84 	case 's':
85 		break;
86 	case 'm':
87 		ret *= 60;
88 		break;
89 	case 'h':
90 		ret *= 60 * 60;
91 		break;
92 	case 'd':
93 		ret *= 60 * 60 * 24;
94 		break;
95 	default:
96 		errx(EXIT_INVALID, "duration unit suffix invalid");
97 	}
98 
99 	if (ret < 0 || ret >= 100000000UL)
100 		errx(EXIT_INVALID, "duration out of range");
101 
102 	return (ret);
103 }
104 
105 static int
106 parse_signal(const char *str)
107 {
108 	int sig, i;
109 	const char *errstr;
110 
111 	sig = strtonum(str, 1, sys_nsig - 1, &errstr);
112 
113 	if (errstr == NULL)
114 		return (sig);
115 
116 	if (strncasecmp(str, "SIG", 3) == 0)
117 		str += 3;
118 
119 	for (i = 1; i < sys_nsig; i++) {
120 		if (strcasecmp(str, sys_signame[i]) == 0)
121 			return (i);
122 	}
123 
124 	errx(EXIT_INVALID, "invalid signal");
125 }
126 
127 static void
128 sig_handler(int signo)
129 {
130 	if (sig_ign != 0 && signo == sig_ign) {
131 		sig_ign = 0;
132 		return;
133 	}
134 
135 	switch (signo) {
136 	case 0:
137 	case SIGINT:
138 	case SIGHUP:
139 	case SIGQUIT:
140 	case SIGTERM:
141 		sig_term = signo;
142 		break;
143 	case SIGCHLD:
144 		sig_chld = 1;
145 		break;
146 	case SIGALRM:
147 		sig_alrm = 1;
148 		break;
149 	}
150 }
151 
152 static void
153 send_sig(pid_t pid, int signo)
154 {
155 	if (verbose) {
156 		warnx("sending signal %s(%d) to command '%s'",
157 		sys_signame[signo], signo, command);
158 	}
159 	kill(pid, signo);
160 }
161 
162 static void
163 set_interval(double iv)
164 {
165 	struct itimerval tim;
166 
167 	memset(&tim, 0, sizeof(tim));
168 	tim.it_value.tv_sec = (time_t)iv;
169 	iv -= (double)tim.it_value.tv_sec;
170 	tim.it_value.tv_usec = (suseconds_t)(iv * 1000000UL);
171 
172 	if (setitimer(ITIMER_REAL, &tim, NULL) == -1)
173 		err(EXIT_FAILURE, "setitimer()");
174 }
175 
176 int
177 main(int argc, char **argv)
178 {
179 	int ch;
180 	int foreground, preserve;
181 	int pstat, status;
182 	int killsig = SIGTERM;
183 	size_t i;
184 	pid_t pid, cpid;
185 	double first_kill;
186 	double second_kill;
187 	bool timedout = false;
188 	bool do_second_kill = false;
189 	bool child_done = false;
190 	struct sigaction signals;
191 	struct procctl_reaper_status info;
192 	struct procctl_reaper_kill killemall;
193 	int signums[] = {
194 		-1,
195 		SIGTERM,
196 		SIGINT,
197 		SIGHUP,
198 		SIGCHLD,
199 		SIGALRM,
200 		SIGQUIT,
201 	};
202 
203 	foreground = preserve = 0;
204 	second_kill = 0;
205 
206 	const struct option longopts[] = {
207 		{ "preserve-status", no_argument,       &preserve,    1 },
208 		{ "foreground",      no_argument,       &foreground,  1 },
209 		{ "kill-after",      required_argument, NULL,        'k'},
210 		{ "signal",          required_argument, NULL,        's'},
211 		{ "help",            no_argument,       NULL,        'h'},
212 		{ "verbose",         no_argument,       NULL,        'v'},
213 		{ NULL,              0,                 NULL,         0 }
214 	};
215 
216 	while ((ch = getopt_long(argc, argv, "+k:s:vh", longopts, NULL)) != -1) {
217 		switch (ch) {
218 			case 'k':
219 				do_second_kill = true;
220 				second_kill = parse_duration(optarg);
221 				break;
222 			case 's':
223 				killsig = parse_signal(optarg);
224 				break;
225 			case 'v':
226 				verbose = true;
227 				break;
228 			case 0:
229 				break;
230 			case 'h':
231 			default:
232 				usage();
233 		}
234 	}
235 
236 	argc -= optind;
237 	argv += optind;
238 
239 	if (argc < 2)
240 		usage();
241 
242 	first_kill = parse_duration(argv[0]);
243 	argc--;
244 	argv++;
245 	command = argv[0];
246 
247 	if (!foreground) {
248 		/* Acquire a reaper */
249 		if (procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) == -1)
250 			err(EXIT_FAILURE, "Fail to acquire the reaper");
251 	}
252 
253 	memset(&signals, 0, sizeof(signals));
254 	sigemptyset(&signals.sa_mask);
255 
256 	if (killsig != SIGKILL && killsig != SIGSTOP)
257 		signums[0] = killsig;
258 
259 	for (i = 0; i < sizeof(signums) / sizeof(signums[0]); i++)
260 		sigaddset(&signals.sa_mask, signums[i]);
261 
262 	signals.sa_handler = sig_handler;
263 	signals.sa_flags = SA_RESTART;
264 
265 	for (i = 0; i < sizeof(signums) / sizeof(signums[0]); i++) {
266 		if (signums[i] != -1 && signums[i] != 0 &&
267 		    sigaction(signums[i], &signals, NULL) == -1)
268 			err(EXIT_FAILURE, "sigaction()");
269 	}
270 
271 	/* Don't stop if background child needs TTY */
272 	signal(SIGTTIN, SIG_IGN);
273 	signal(SIGTTOU, SIG_IGN);
274 
275 	pid = fork();
276 	if (pid == -1)
277 		err(EXIT_FAILURE, "fork()");
278 	else if (pid == 0) {
279 		/* child process */
280 		signal(SIGTTIN, SIG_DFL);
281 		signal(SIGTTOU, SIG_DFL);
282 
283 		execvp(argv[0], argv);
284 		warn("exec(%s)", argv[0]);
285 		_exit(errno == ENOENT ? EXIT_CMD_NOENT : EXIT_CMD_ERROR);
286 	}
287 
288 	if (sigprocmask(SIG_BLOCK, &signals.sa_mask, NULL) == -1)
289 		err(EXIT_FAILURE, "sigprocmask()");
290 
291 	/* parent continues here */
292 	set_interval(first_kill);
293 
294 	for (;;) {
295 		sigemptyset(&signals.sa_mask);
296 		sigsuspend(&signals.sa_mask);
297 
298 		if (sig_chld) {
299 			sig_chld = 0;
300 
301 			while ((cpid = waitpid(-1, &status, WNOHANG)) != 0) {
302 				if (cpid < 0) {
303 					if (errno == EINTR)
304 						continue;
305 					else
306 						break;
307 				} else if (cpid == pid) {
308 					pstat = status;
309 					child_done = true;
310 				}
311 			}
312 			if (child_done) {
313 				if (foreground) {
314 					break;
315 				} else {
316 					procctl(P_PID, getpid(),
317 					    	PROC_REAP_STATUS, &info);
318 					if (info.rs_children == 0)
319 						break;
320 				}
321 			}
322 		} else if (sig_alrm) {
323 			sig_alrm = 0;
324 
325 			timedout = true;
326 			if (!foreground) {
327 				killemall.rk_sig = killsig;
328 				killemall.rk_flags = 0;
329 				procctl(P_PID, getpid(), PROC_REAP_KILL,
330 				    &killemall);
331 			} else
332 				send_sig(pid, killsig);
333 
334 			if (do_second_kill) {
335 				set_interval(second_kill);
336 				do_second_kill = false;
337 				sig_ign = killsig;
338 				killsig = SIGKILL;
339 			} else
340 				break;
341 
342 		} else if (sig_term) {
343 			if (!foreground) {
344 				killemall.rk_sig = sig_term;
345 				killemall.rk_flags = 0;
346 				procctl(P_PID, getpid(), PROC_REAP_KILL,
347 				    &killemall);
348 			} else
349 				send_sig(pid, sig_term);
350 
351 			if (do_second_kill) {
352 				set_interval(second_kill);
353 				do_second_kill = false;
354 				sig_ign = killsig;
355 				killsig = SIGKILL;
356 			} else
357 				break;
358 		}
359 	}
360 
361 	while (!child_done && wait(&pstat) == -1) {
362 		if (errno != EINTR)
363 			err(EXIT_FAILURE, "waitpid()");
364 	}
365 
366 	if (!foreground)
367 		procctl(P_PID, getpid(), PROC_REAP_RELEASE, NULL);
368 
369 	if (WEXITSTATUS(pstat))
370 		pstat = WEXITSTATUS(pstat);
371 	else if (WIFSIGNALED(pstat))
372 		pstat = 128 + WTERMSIG(pstat);
373 
374 	if (timedout && !preserve)
375 		pstat = EXIT_TIMEOUT;
376 
377 	return (pstat);
378 }
379