1 /* timeout -- run a command with bounded time
2 Copyright (C) 2008-2023 Free Software Foundation, Inc.
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
16
17
18 /* timeout - Start a command, and kill it if the specified timeout expires
19
20 We try to behave like a shell starting a single (foreground) job,
21 and will kill the job if we receive the alarm signal we setup.
22 The exit status of the job is returned, or one of these errors:
23 EXIT_TIMEDOUT 124 job timed out
24 EXIT_CANCELED 125 internal error
25 EXIT_CANNOT_INVOKE 126 error executing job
26 EXIT_ENOENT 127 couldn't find job to exec
27
28 Caveats:
29 If user specifies the KILL (9) signal is to be sent on timeout,
30 the monitor is killed and so exits with 128+9 rather than 124.
31
32 If you start a command in the background, which reads from the tty
33 and so is immediately sent SIGTTIN to stop, then the timeout
34 process will ignore this so it can timeout the command as expected.
35 This can be seen with 'timeout 10 dd&' for example.
36 However if one brings this group to the foreground with the 'fg'
37 command before the timer expires, the command will remain
38 in the stop state as the shell doesn't send a SIGCONT
39 because the timeout process (group leader) is already running.
40 To get the command running again one can Ctrl-Z, and do fg again.
41 Note one can Ctrl-C the whole job when in this state.
42 I think this could be fixed but I'm not sure the extra
43 complication is justified for this scenario.
44
45 Written by Pádraig Brady. */
46
47 #include <config.h>
48 #include <getopt.h>
49 #include <stdio.h>
50 #include <sys/types.h>
51 #include <signal.h>
52 #if HAVE_PRCTL
53 # include <sys/prctl.h>
54 #endif
55 #include <sys/wait.h>
56
57 #include "system.h"
58 #include "cl-strtod.h"
59 #include "xstrtod.h"
60 #include "sig2str.h"
61 #include "operand2sig.h"
62 #include "quote.h"
63
64 #if HAVE_SETRLIMIT
65 /* FreeBSD 5.0 at least needs <sys/types.h> and <sys/time.h> included
66 before <sys/resource.h>. Currently "system.h" includes <sys/time.h>. */
67 # include <sys/resource.h>
68 #endif
69
70 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt. */
71 #ifndef SA_RESTART
72 # define SA_RESTART 0
73 #endif
74
75 #define PROGRAM_NAME "timeout"
76
77 #define AUTHORS proper_name_lite ("Padraig Brady", "P\303\241draig Brady")
78
79 static int timed_out;
80 static int term_signal = SIGTERM; /* same default as kill command. */
81 static pid_t monitored_pid;
82 static double kill_after;
83 static bool foreground; /* whether to use another program group. */
84 static bool preserve_status; /* whether to use a timeout status or not. */
85 static bool verbose; /* whether to diagnose timeouts or not. */
86 static char const *command;
87
88 /* for long options with no corresponding short option, use enum */
89 enum
90 {
91 FOREGROUND_OPTION = CHAR_MAX + 1,
92 PRESERVE_STATUS_OPTION
93 };
94
95 static struct option const long_options[] =
96 {
97 {"kill-after", required_argument, nullptr, 'k'},
98 {"signal", required_argument, nullptr, 's'},
99 {"verbose", no_argument, nullptr, 'v'},
100 {"foreground", no_argument, nullptr, FOREGROUND_OPTION},
101 {"preserve-status", no_argument, nullptr, PRESERVE_STATUS_OPTION},
102 {GETOPT_HELP_OPTION_DECL},
103 {GETOPT_VERSION_OPTION_DECL},
104 {nullptr, 0, nullptr, 0}
105 };
106
107 /* Start the timeout after which we'll receive a SIGALRM.
108 Round DURATION up to the next representable value.
109 Treat out-of-range values as if they were maximal,
110 as that's more useful in practice than reporting an error.
111 '0' means don't timeout. */
112 static void
settimeout(double duration,bool warn)113 settimeout (double duration, bool warn)
114 {
115
116 #if HAVE_TIMER_SETTIME
117 /* timer_settime() provides potentially nanosecond resolution. */
118
119 struct timespec ts = dtotimespec (duration);
120 struct itimerspec its = {.it_interval = {0}, .it_value = ts};
121 timer_t timerid;
122 if (timer_create (CLOCK_REALTIME, nullptr, &timerid) == 0)
123 {
124 if (timer_settime (timerid, 0, &its, nullptr) == 0)
125 return;
126 else
127 {
128 if (warn)
129 error (0, errno, _("warning: timer_settime"));
130 timer_delete (timerid);
131 }
132 }
133 else if (warn && errno != ENOSYS)
134 error (0, errno, _("warning: timer_create"));
135
136 #elif HAVE_SETITIMER
137 /* setitimer() is more portable (to Darwin for example),
138 but only provides microsecond resolution. */
139
140 struct timeval tv;
141 struct timespec ts = dtotimespec (duration);
142 tv.tv_sec = ts.tv_sec;
143 tv.tv_usec = (ts.tv_nsec + 999) / 1000;
144 if (tv.tv_usec == 1000 * 1000)
145 {
146 if (tv.tv_sec != TYPE_MAXIMUM (time_t))
147 {
148 tv.tv_sec++;
149 tv.tv_usec = 0;
150 }
151 else
152 tv.tv_usec--;
153 }
154 struct itimerval it = {.it_interval = {0}, .it_value = tv };
155 if (setitimer (ITIMER_REAL, &it, nullptr) == 0)
156 return;
157 else
158 {
159 if (warn && errno != ENOSYS)
160 error (0, errno, _("warning: setitimer"));
161 }
162 #endif
163
164 /* fallback to single second resolution provided by alarm(). */
165
166 unsigned int timeint;
167 if (UINT_MAX <= duration)
168 timeint = UINT_MAX;
169 else
170 {
171 unsigned int duration_floor = duration;
172 timeint = duration_floor + (duration_floor < duration);
173 }
174 alarm (timeint);
175 }
176
177 /* send SIG avoiding the current process. */
178
179 static int
send_sig(pid_t where,int sig)180 send_sig (pid_t where, int sig)
181 {
182 /* If sending to the group, then ignore the signal,
183 so we don't go into a signal loop. Note that this will ignore any of the
184 signals registered in install_cleanup(), that are sent after we
185 propagate the first one, which hopefully won't be an issue. Note this
186 process can be implicitly multithreaded due to some timer_settime()
187 implementations, therefore a signal sent to the group, can be sent
188 multiple times to this process. */
189 if (where == 0)
190 signal (sig, SIG_IGN);
191 return kill (where, sig);
192 }
193
194 /* Signal handler which is required for sigsuspend() to be interrupted
195 whenever SIGCHLD is received. */
196 static void
chld(int sig)197 chld (int sig)
198 {
199 }
200
201
202 static void
cleanup(int sig)203 cleanup (int sig)
204 {
205 if (sig == SIGALRM)
206 {
207 timed_out = 1;
208 sig = term_signal;
209 }
210 if (monitored_pid)
211 {
212 if (kill_after)
213 {
214 int saved_errno = errno; /* settimeout may reset. */
215 /* Start a new timeout after which we'll send SIGKILL. */
216 term_signal = SIGKILL;
217 settimeout (kill_after, false);
218 kill_after = 0; /* Don't let later signals reset kill alarm. */
219 errno = saved_errno;
220 }
221
222 /* Send the signal directly to the monitored child,
223 in case it has itself become group leader,
224 or is not running in a separate group. */
225 if (verbose)
226 {
227 char signame[MAX (SIG2STR_MAX, INT_BUFSIZE_BOUND (int))];
228 if (sig2str (sig, signame) != 0)
229 snprintf (signame, sizeof signame, "%d", sig);
230 error (0, 0, _("sending signal %s to command %s"),
231 signame, quote (command));
232 }
233 send_sig (monitored_pid, sig);
234
235 /* The normal case is the job has remained in our
236 newly created process group, so send to all processes in that. */
237 if (!foreground)
238 {
239 send_sig (0, sig);
240 if (sig != SIGKILL && sig != SIGCONT)
241 {
242 send_sig (monitored_pid, SIGCONT);
243 send_sig (0, SIGCONT);
244 }
245 }
246 }
247 else /* we're the child or the child is not exec'd yet. */
248 _exit (128 + sig);
249 }
250
251 void
usage(int status)252 usage (int status)
253 {
254 if (status != EXIT_SUCCESS)
255 emit_try_help ();
256 else
257 {
258 printf (_("\
259 Usage: %s [OPTION] DURATION COMMAND [ARG]...\n\
260 or: %s [OPTION]\n"), program_name, program_name);
261
262 fputs (_("\
263 Start COMMAND, and kill it if still running after DURATION.\n\
264 "), stdout);
265
266 emit_mandatory_arg_note ();
267
268 fputs (_("\
269 --preserve-status\n\
270 exit with the same status as COMMAND, even when the\n\
271 command times out\n\
272 --foreground\n\
273 when not running timeout directly from a shell prompt,\n\
274 allow COMMAND to read from the TTY and get TTY signals;\n\
275 in this mode, children of COMMAND will not be timed out\n\
276 -k, --kill-after=DURATION\n\
277 also send a KILL signal if COMMAND is still running\n\
278 this long after the initial signal was sent\n\
279 -s, --signal=SIGNAL\n\
280 specify the signal to be sent on timeout;\n\
281 SIGNAL may be a name like 'HUP' or a number;\n\
282 see 'kill -l' for a list of signals\n"), stdout);
283 fputs (_("\
284 -v, --verbose diagnose to stderr any signal sent upon timeout\n"), stdout);
285
286 fputs (HELP_OPTION_DESCRIPTION, stdout);
287 fputs (VERSION_OPTION_DESCRIPTION, stdout);
288
289 fputs (_("\n\
290 DURATION is a floating point number with an optional suffix:\n\
291 's' for seconds (the default), 'm' for minutes, 'h' for hours or \
292 'd' for days.\nA duration of 0 disables the associated timeout.\n"), stdout);
293
294 fputs (_("\n\
295 Upon timeout, send the TERM signal to COMMAND, if no other SIGNAL specified.\n\
296 The TERM signal kills any process that does not block or catch that signal.\n\
297 It may be necessary to use the KILL signal, since this signal can't be caught.\
298 \n"), stdout);
299
300 fputs (_("\n\
301 Exit status:\n\
302 124 if COMMAND times out, and --preserve-status is not specified\n\
303 125 if the timeout command itself fails\n\
304 126 if COMMAND is found but cannot be invoked\n\
305 127 if COMMAND cannot be found\n\
306 137 if COMMAND (or timeout itself) is sent the KILL (9) signal (128+9)\n\
307 - the exit status of COMMAND otherwise\n\
308 "), stdout);
309
310 emit_ancillary_info (PROGRAM_NAME);
311 }
312 exit (status);
313 }
314
315 /* Given a floating point value *X, and a suffix character, SUFFIX_CHAR,
316 scale *X by the multiplier implied by SUFFIX_CHAR. SUFFIX_CHAR may
317 be the NUL byte or 's' to denote seconds, 'm' for minutes, 'h' for
318 hours, or 'd' for days. If SUFFIX_CHAR is invalid, don't modify *X
319 and return false. Otherwise return true. */
320
321 static bool
apply_time_suffix(double * x,char suffix_char)322 apply_time_suffix (double *x, char suffix_char)
323 {
324 int multiplier;
325
326 switch (suffix_char)
327 {
328 case 0:
329 case 's':
330 multiplier = 1;
331 break;
332 case 'm':
333 multiplier = 60;
334 break;
335 case 'h':
336 multiplier = 60 * 60;
337 break;
338 case 'd':
339 multiplier = 60 * 60 * 24;
340 break;
341 default:
342 return false;
343 }
344
345 *x *= multiplier;
346
347 return true;
348 }
349
350 static double
parse_duration(char const * str)351 parse_duration (char const *str)
352 {
353 double duration;
354 char const *ep;
355
356 if (! (xstrtod (str, &ep, &duration, cl_strtod) || errno == ERANGE)
357 /* Nonnegative interval. */
358 || ! (0 <= duration)
359 /* No extra chars after the number and an optional s,m,h,d char. */
360 || (*ep && *(ep + 1))
361 /* Check any suffix char and update timeout based on the suffix. */
362 || !apply_time_suffix (&duration, *ep))
363 {
364 error (0, 0, _("invalid time interval %s"), quote (str));
365 usage (EXIT_CANCELED);
366 }
367
368 return duration;
369 }
370
371 static void
unblock_signal(int sig)372 unblock_signal (int sig)
373 {
374 sigset_t unblock_set;
375 sigemptyset (&unblock_set);
376 sigaddset (&unblock_set, sig);
377 if (sigprocmask (SIG_UNBLOCK, &unblock_set, nullptr) != 0)
378 error (0, errno, _("warning: sigprocmask"));
379 }
380
381 static void
install_sigchld(void)382 install_sigchld (void)
383 {
384 struct sigaction sa;
385 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
386 sa.sa_handler = chld;
387 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
388 more likely to work cleanly. */
389
390 sigaction (SIGCHLD, &sa, nullptr);
391
392 /* We inherit the signal mask from our parent process,
393 so ensure SIGCHLD is not blocked. */
394 unblock_signal (SIGCHLD);
395 }
396
397 static void
install_cleanup(int sigterm)398 install_cleanup (int sigterm)
399 {
400 struct sigaction sa;
401 sigemptyset (&sa.sa_mask); /* Allow concurrent calls to handler */
402 sa.sa_handler = cleanup;
403 sa.sa_flags = SA_RESTART; /* Restart syscalls if possible, as that's
404 more likely to work cleanly. */
405
406 sigaction (SIGALRM, &sa, nullptr); /* our timeout. */
407 sigaction (SIGINT, &sa, nullptr); /* Ctrl-C at terminal for example. */
408 sigaction (SIGQUIT, &sa, nullptr); /* Ctrl-\ at terminal for example. */
409 sigaction (SIGHUP, &sa, nullptr); /* terminal closed for example. */
410 sigaction (SIGTERM, &sa, nullptr); /* if killed, stop monitored proc. */
411 sigaction (sigterm, &sa, nullptr); /* user specified termination signal. */
412 }
413
414 /* Block all signals which were registered with cleanup() as the signal
415 handler, so we never kill processes after waitpid() returns.
416 Also block SIGCHLD to ensure it doesn't fire between
417 waitpid() polling and sigsuspend() waiting for a signal.
418 Return original mask in OLD_SET. */
419 static void
block_cleanup_and_chld(int sigterm,sigset_t * old_set)420 block_cleanup_and_chld (int sigterm, sigset_t *old_set)
421 {
422 sigset_t block_set;
423 sigemptyset (&block_set);
424
425 sigaddset (&block_set, SIGALRM);
426 sigaddset (&block_set, SIGINT);
427 sigaddset (&block_set, SIGQUIT);
428 sigaddset (&block_set, SIGHUP);
429 sigaddset (&block_set, SIGTERM);
430 sigaddset (&block_set, sigterm);
431
432 sigaddset (&block_set, SIGCHLD);
433
434 if (sigprocmask (SIG_BLOCK, &block_set, old_set) != 0)
435 error (0, errno, _("warning: sigprocmask"));
436 }
437
438 /* Try to disable core dumps for this process.
439 Return TRUE if successful, FALSE otherwise. */
440 static bool
disable_core_dumps(void)441 disable_core_dumps (void)
442 {
443 #if HAVE_PRCTL && defined PR_SET_DUMPABLE
444 if (prctl (PR_SET_DUMPABLE, 0) == 0)
445 return true;
446
447 #elif HAVE_SETRLIMIT && defined RLIMIT_CORE
448 /* Note this doesn't disable processing by a filter in
449 /proc/sys/kernel/core_pattern on Linux. */
450 if (setrlimit (RLIMIT_CORE, &(struct rlimit) {0}) == 0)
451 return true;
452
453 #else
454 return false;
455 #endif
456
457 error (0, errno, _("warning: disabling core dumps failed"));
458 return false;
459 }
460
461 int
main(int argc,char ** argv)462 main (int argc, char **argv)
463 {
464 double timeout;
465 char signame[SIG2STR_MAX];
466 int c;
467
468 initialize_main (&argc, &argv);
469 set_program_name (argv[0]);
470 setlocale (LC_ALL, "");
471 bindtextdomain (PACKAGE, LOCALEDIR);
472 textdomain (PACKAGE);
473
474 initialize_exit_failure (EXIT_CANCELED);
475 atexit (close_stdout);
476
477 while ((c = getopt_long (argc, argv, "+k:s:v", long_options, nullptr)) != -1)
478 {
479 switch (c)
480 {
481 case 'k':
482 kill_after = parse_duration (optarg);
483 break;
484
485 case 's':
486 term_signal = operand2sig (optarg, signame);
487 if (term_signal == -1)
488 usage (EXIT_CANCELED);
489 break;
490
491 case 'v':
492 verbose = true;
493 break;
494
495 case FOREGROUND_OPTION:
496 foreground = true;
497 break;
498
499 case PRESERVE_STATUS_OPTION:
500 preserve_status = true;
501 break;
502
503 case_GETOPT_HELP_CHAR;
504
505 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
506
507 default:
508 usage (EXIT_CANCELED);
509 break;
510 }
511 }
512
513 if (argc - optind < 2)
514 usage (EXIT_CANCELED);
515
516 timeout = parse_duration (argv[optind++]);
517
518 argv += optind;
519 command = argv[0];
520
521 /* Ensure we're in our own group so all subprocesses can be killed.
522 Note we don't just put the child in a separate group as
523 then we would need to worry about foreground and background groups
524 and propagating signals between them. */
525 if (!foreground)
526 setpgid (0, 0);
527
528 /* Setup handlers before fork() so that we
529 handle any signals caused by child, without races. */
530 install_cleanup (term_signal);
531 signal (SIGTTIN, SIG_IGN); /* Don't stop if background child needs tty. */
532 signal (SIGTTOU, SIG_IGN); /* Don't stop if background child needs tty. */
533 install_sigchld (); /* Interrupt sigsuspend() when child exits. */
534
535 monitored_pid = fork ();
536 if (monitored_pid == -1)
537 {
538 error (0, errno, _("fork system call failed"));
539 return EXIT_CANCELED;
540 }
541 else if (monitored_pid == 0)
542 { /* child */
543 /* exec doesn't reset SIG_IGN -> SIG_DFL. */
544 signal (SIGTTIN, SIG_DFL);
545 signal (SIGTTOU, SIG_DFL);
546
547 execvp (argv[0], argv);
548
549 /* exit like sh, env, nohup, ... */
550 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
551 error (0, errno, _("failed to run command %s"), quote (command));
552 return exit_status;
553 }
554 else
555 {
556 pid_t wait_result;
557 int status;
558
559 /* We configure timers so that SIGALRM is sent on expiry.
560 Therefore ensure we don't inherit a mask blocking SIGALRM. */
561 unblock_signal (SIGALRM);
562
563 settimeout (timeout, true);
564
565 /* Ensure we don't cleanup() after waitpid() reaps the child,
566 to avoid sending signals to a possibly different process. */
567 sigset_t cleanup_set;
568 block_cleanup_and_chld (term_signal, &cleanup_set);
569
570 while ((wait_result = waitpid (monitored_pid, &status, WNOHANG)) == 0)
571 sigsuspend (&cleanup_set); /* Wait with cleanup signals unblocked. */
572
573 if (wait_result < 0)
574 {
575 /* shouldn't happen. */
576 error (0, errno, _("error waiting for command"));
577 status = EXIT_CANCELED;
578 }
579 else
580 {
581 if (WIFEXITED (status))
582 status = WEXITSTATUS (status);
583 else if (WIFSIGNALED (status))
584 {
585 int sig = WTERMSIG (status);
586 if (WCOREDUMP (status))
587 error (0, 0, _("the monitored command dumped core"));
588 if (!timed_out && disable_core_dumps ())
589 {
590 /* exit with the signal flag set. */
591 signal (sig, SIG_DFL);
592 unblock_signal (sig);
593 raise (sig);
594 }
595 /* Allow users to distinguish if command was forcibly killed.
596 Needed with --foreground where we don't send SIGKILL to
597 the timeout process itself. */
598 if (timed_out && sig == SIGKILL)
599 preserve_status = true;
600 status = sig + 128; /* what sh returns for signaled processes. */
601 }
602 else
603 {
604 /* shouldn't happen. */
605 error (0, 0, _("unknown status from command (%d)"), status);
606 status = EXIT_FAILURE;
607 }
608 }
609
610 if (timed_out && !preserve_status)
611 status = EXIT_TIMEDOUT;
612 return status;
613 }
614 }
615