xref: /freebsd/bin/timeout/timeout.c (revision d633a7d12105a54551622882f4eee80a13a1445a)
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
usage(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
parse_duration(const char * duration)68 parse_duration(const char *duration)
69 {
70 	double ret;
71 	char *end;
72 
73 	ret = strtod(duration, &end);
74 	if (ret == 0 && end == duration)
75 		errx(EXIT_INVALID, "invalid duration");
76 
77 	if (end == NULL || *end == '\0')
78 		return (ret);
79 
80 	if (end != NULL && *(end + 1) != '\0')
81 		errx(EXIT_INVALID, "invalid duration");
82 
83 	switch (*end) {
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, "invalid duration");
97 	}
98 
99 	if (ret < 0 || ret >= 100000000UL)
100 		errx(EXIT_INVALID, "invalid duration");
101 
102 	return (ret);
103 }
104 
105 static int
parse_signal(const char * str)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
sig_handler(int signo)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
send_sig(pid_t pid,int signo)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
set_interval(double iv)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
main(int argc,char ** argv)177 main(int argc, char **argv)
178 {
179 	int ch;
180 	int foreground, preserve;
181 	int error, 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 		error = execvp(argv[0], argv);
284 		if (error == -1) {
285 			if (errno == ENOENT)
286 				err(EXIT_CMD_NOENT, "exec(%s)", argv[0]);
287 			else
288 				err(EXIT_CMD_ERROR, "exec(%s)", argv[0]);
289 		}
290 	}
291 
292 	if (sigprocmask(SIG_BLOCK, &signals.sa_mask, NULL) == -1)
293 		err(EXIT_FAILURE, "sigprocmask()");
294 
295 	/* parent continues here */
296 	set_interval(first_kill);
297 
298 	for (;;) {
299 		sigemptyset(&signals.sa_mask);
300 		sigsuspend(&signals.sa_mask);
301 
302 		if (sig_chld) {
303 			sig_chld = 0;
304 
305 			while ((cpid = waitpid(-1, &status, WNOHANG)) != 0) {
306 				if (cpid < 0) {
307 					if (errno == EINTR)
308 						continue;
309 					else
310 						break;
311 				} else if (cpid == pid) {
312 					pstat = status;
313 					child_done = true;
314 				}
315 			}
316 			if (child_done) {
317 				if (foreground) {
318 					break;
319 				} else {
320 					procctl(P_PID, getpid(),
321 					    	PROC_REAP_STATUS, &info);
322 					if (info.rs_children == 0)
323 						break;
324 				}
325 			}
326 		} else if (sig_alrm) {
327 			sig_alrm = 0;
328 
329 			timedout = true;
330 			if (!foreground) {
331 				killemall.rk_sig = killsig;
332 				killemall.rk_flags = 0;
333 				procctl(P_PID, getpid(), PROC_REAP_KILL,
334 				    &killemall);
335 			} else
336 				send_sig(pid, killsig);
337 
338 			if (do_second_kill) {
339 				set_interval(second_kill);
340 				do_second_kill = false;
341 				sig_ign = killsig;
342 				killsig = SIGKILL;
343 			} else
344 				break;
345 
346 		} else if (sig_term) {
347 			if (!foreground) {
348 				killemall.rk_sig = sig_term;
349 				killemall.rk_flags = 0;
350 				procctl(P_PID, getpid(), PROC_REAP_KILL,
351 				    &killemall);
352 			} else
353 				send_sig(pid, sig_term);
354 
355 			if (do_second_kill) {
356 				set_interval(second_kill);
357 				do_second_kill = false;
358 				sig_ign = killsig;
359 				killsig = SIGKILL;
360 			} else
361 				break;
362 		}
363 	}
364 
365 	while (!child_done && wait(&pstat) == -1) {
366 		if (errno != EINTR)
367 			err(EXIT_FAILURE, "waitpid()");
368 	}
369 
370 	if (!foreground)
371 		procctl(P_PID, getpid(), PROC_REAP_RELEASE, NULL);
372 
373 	if (WEXITSTATUS(pstat))
374 		pstat = WEXITSTATUS(pstat);
375 	else if (WIFSIGNALED(pstat))
376 		pstat = 128 + WTERMSIG(pstat);
377 
378 	if (timedout && !preserve)
379 		pstat = EXIT_TIMEOUT;
380 
381 	return (pstat);
382 }
383