1 /* run-parts: run a bunch of scripts in a directory
3 * Debian run-parts program
4 * Copyright (C) 1996 Jeff Noxon <jeff@router.patch.net>,
5 * Copyright (C) 1996-1999 Guy Maor <maor@debian.org>
6 * Copyright (C) 2002-2012 Clint Adams <clint@debian.org>
8 * This is free software; see the GNU General Public License version 2
9 * or later for copying conditions. There is NO warranty.
11 * Based on run-parts.pl version 0.2, Copyright (C) 1994 Ian Jackson.
18 #include <sys/types.h>
26 #endif /* HAVE_GETOPT_H */
34 #define RUNPARTS_NORMAL 0
35 #define RUNPARTS_ERE 1
36 #define RUNPARTS_LSBSYSINIT 100
45 int exit_on_error_mode = 0;
46 int new_session_mode = 0;
48 int argcount = 0, argsize = 0;
52 regex_t hierre, tradre, excsre, classicalre, customre;
54 static void catch_signals();
55 static void restore_signals();
57 static char* regex_get_error(int errcode, regex_t *compiled);
58 static void regex_compile_pattern(void);
59 static void regex_clean(void);
61 void error(char *format, ...)
65 fprintf(stderr, "run-parts: ");
68 vfprintf(stderr, format, ap);
71 fprintf(stderr, "\n");
77 fprintf(stderr, "Debian run-parts program, version " PACKAGE_VERSION
78 "\nCopyright (C) 1994 Ian Jackson, Copyright (C) 1996 Jeff Noxon.\n"
79 "Copyright (C) 1996,1997,1998,1999 Guy Maor\n"
80 "Copyright (C) 2002-2012 Clint Adams\n"
81 "This is free software; see the GNU General Public License version 2\n"
82 "or later for copying conditions. There is NO warranty.\n");
89 fprintf(stderr, "Usage: run-parts [OPTION]... DIRECTORY\n"
90 " --test print script names which would run, but don't run them.\n"
91 " --list print names of all valid files (can not be used with\n"
93 " -v, --verbose print script names before running them.\n"
94 " --report print script names if they produce output.\n"
95 " --reverse reverse execution order of scripts.\n"
96 " --exit-on-error exit as soon as a script returns with a non-zero exit\n"
98 " --lsbsysinit validate filenames based on LSB sysinit specs.\n"
99 " --new-session run each script in a separate process session\n"
100 " --regex=PATTERN validate filenames based on POSIX ERE pattern PATTERN.\n"
101 " -u, --umask=UMASK sets umask to UMASK (octal), default is 022.\n"
102 " -a, --arg=ARGUMENT pass ARGUMENT to scripts, use once for each argument.\n"
103 " -V, --version output version information and exit.\n"
104 " -h, --help display this help and exit.\n");
109 /* The octal conversion in libc is not foolproof; it will take the 8 and 9
110 * digits under some circumstances. We'll just have to live with it.
116 result = sscanf(optarg, "%o", &mask);
117 if ((result != 1) || (mask > 07777) || (mask < 0)) {
118 error("bad umask value");
125 /* Add an argument to the commands that we will call. Called once for
127 void add_argument(char *newarg)
129 if (argcount + 1 >= argsize) {
130 argsize = argsize ? argsize * 2 : 4;
131 args = realloc(args, argsize * (sizeof(char *)));
133 error("failed to reallocate memory for arguments: %s", strerror(errno));
137 args[argcount++] = newarg;
141 /* True or false? Is this a valid filename? */
142 int valid_name(const struct dirent *d)
147 s = (char *)&(d->d_name);
149 if (regex_mode == RUNPARTS_ERE)
150 retval = !regexec(&customre, s, 0, NULL, 0);
152 else if (regex_mode == RUNPARTS_LSBSYSINIT) {
154 if (!regexec(&hierre, s, 0, NULL, 0))
155 retval = regexec(&excsre, s, 0, NULL, 0);
158 retval = !regexec(&tradre, s, 0, NULL, 0);
161 retval = !regexec(&classicalre, s, 0, NULL, 0);
167 void run_part(char *progname)
171 int pout[2], perr[2];
175 if (report_mode && (pipe(pout) || pipe(perr))) {
176 error("pipe: %s", strerror(errno));
179 if ((pid = fork()) < 0) {
180 error("failed to fork: %s", strerror(errno));
185 if (new_session_mode)
188 if (dup2(pout[1], STDOUT_FILENO) == -1 ||
189 dup2(perr[1], STDERR_FILENO) == -1) {
190 error("dup2: %s", strerror(errno));
199 execv(progname, args);
200 error("failed to exec %s: %s", progname, strerror(errno));
207 struct timespec zero_timeout;
208 struct timespec *the_timeout;
213 sigemptyset(&tempmask);
214 sigprocmask(0, NULL, &tempmask);
215 sigdelset(&tempmask, SIGCHLD);
217 memset(&zero_timeout, 0, sizeof(zero_timeout));
222 max = pout[0] > perr[0] ? pout[0] + 1 : perr[0] + 1;
225 while (pout[0] >= 0 || perr[0] >= 0) {
227 r = waitpid(pid, &result, WNOHANG);
229 error("waitpid: %s", strerror(errno));
232 if (r != 0 && (WIFEXITED(result) || WIFSIGNALED(result))) {
233 /* If the process dies, set a zero timeout. Rarely, some processes
234 * leak file descriptors (e.g., by starting a naughty daemon).
235 * select() would wait forever since the pipes wouldn't close.
236 * We loop, with a zero timeout, until there's no data left, then
237 * give up. This shouldn't affect non-leaky processes. */
239 the_timeout = &zero_timeout;
245 FD_SET(pout[0], &set);
247 FD_SET(perr[0], &set);
248 r = pselect(max, &set, 0, 0, the_timeout, &tempmask);
254 error("select: %s", strerror(errno));
258 /* If STDOUT or STDERR get closed / full, we still run to completion
259 * (and just ignore that we can't output process output any more).
260 * Perhaps we should instead kill the child process we are running
262 * For now partial writes are not retried to complete - that can
263 * and should be done, but needs care to ensure that we don't hang
264 * if the fd doesn't accept more data ever - or we need to decide that
265 * waiting is the appropriate thing to do.
268 if (pout[0] >= 0 && FD_ISSET(pout[0], &set)) {
269 c = read(pout[0], buf, sizeof(buf));
272 printf("%s:\n", progname);
276 ignored = write(STDOUT_FILENO, buf, c);
285 error("failed to read from stdout pipe: %s", strerror (errno));
288 if (perr[0] >= 0 && FD_ISSET(perr[0], &set)) {
289 c = read(perr[0], buf, sizeof(buf));
292 fprintf(stderr, "%s:\n", progname);
296 ignored = write(STDERR_FILENO, buf, c);
305 error("failed to read from error pipe: %s", strerror (errno));
309 else if (r == 0 && waited) {
310 /* Zero timeout, no data left. */
317 /* assert(FALSE): select was called with infinite timeout, so
318 it either returns successfully or is interrupted */
324 r = waitpid(pid, &result, 0);
327 error("waitpid: %s", strerror(errno));
332 if (WIFEXITED(result) && WEXITSTATUS(result)) {
333 error("%s exited with return code %d", progname, WEXITSTATUS(result));
336 else if (WIFSIGNALED(result)) {
337 error("%s exited because of uncaught signal %d", progname,
343 static void handle_signal(int s)
348 /* Catch SIGCHLD with an empty function to interrupt select() */
349 static void catch_signals()
351 struct sigaction act;
354 memset(&act, 0, sizeof(act));
355 act.sa_handler = handle_signal;
356 act.sa_flags = SA_NOCLDSTOP;
357 sigaction(SIGCHLD, &act, NULL);
360 sigaddset(&set, SIGCHLD);
361 sigprocmask(SIG_BLOCK, &set, NULL);
364 /* Unblock signals before execing a child */
365 static void restore_signals()
369 sigaddset(&set, SIGCHLD);
370 sigprocmask(SIG_UNBLOCK, &set, NULL);
373 /* Find the parts to run & call run_part() */
374 void run_parts(char *dirname)
376 struct dirent **namelist;
378 size_t filename_length, dirname_length;
379 int entries, i, result;
383 dirname_length = strlen(dirname) + 1;
384 /* dirname + "/" + ".." + "\0" (This will save one realloc.) */
385 filename_length = dirname_length + 2 + 1;
386 if (!(filename = malloc(filename_length))) {
387 error("failed to allocate memory for path: %s", strerror(errno));
390 strcpy(filename, dirname);
391 strcat(filename, "/");
393 /* scandir() isn't POSIX, but it makes things easy. */
394 entries = scandir(dirname, &namelist, valid_name, alphasort);
396 error("failed to open directory %s: %s", dirname, strerror(errno));
400 i = reverse_mode ? 0 : entries;
401 for (i = reverse_mode ? (entries - 1) : 0;
402 reverse_mode ? (i >= 0) : (i < entries); reverse_mode ? i-- : i++) {
403 if (filename_length < dirname_length + strlen(namelist[i]->d_name) + 1) {
404 filename_length = dirname_length + strlen(namelist[i]->d_name) + 1;
405 if (!(filename = realloc(filename, filename_length))) {
406 error("failed to reallocate memory for path: %s", strerror(errno));
410 strcpy(filename + dirname_length, namelist[i]->d_name);
412 strcpy(filename, dirname);
413 strcat(filename, "/");
414 strcat(filename, namelist[i]->d_name);
416 result = stat(filename, &st);
418 error("failed to stat component %s: %s", filename, strerror(errno));
419 if (exit_on_error_mode) {
426 if (S_ISREG(st.st_mode)) {
427 if (!access(filename, X_OK)) {
429 printf("%s\n", filename);
431 else if (list_mode) {
432 if (!access(filename, R_OK))
433 printf("%s\n", filename);
440 fprintf(stderr, "run-parts: executing %s", filename);
442 fprintf(stderr, " %s", *a);
443 fprintf(stderr, "\n");
445 fprintf(stderr, "run-parts: executing %s\n", filename);
448 if (exitstatus != 0 && exit_on_error_mode) return;
451 else if (!access(filename, R_OK)) {
453 printf("%s\n", filename);
456 else if (S_ISLNK(st.st_mode)) {
458 error("run-parts: component %s is a broken symbolic link\n",filename);
463 else if (!S_ISDIR(st.st_mode)) {
465 error("run-parts: component %s is not an executable plain file\n",
477 /* Process options */
478 int main(int argc, char *argv[])
486 int option_index = 0;
488 static struct option long_options[] = {
489 {"test", 0, &test_mode, 1},
490 {"list", 0, &list_mode, 1},
491 {"verbose", 0, 0, 'v'},
492 {"report", 0, &report_mode, 1},
493 {"reverse", 0, &reverse_mode, 1},
494 {"umask", 1, 0, 'u'},
497 {"version", 0, 0, 'V'},
498 {"lsbsysinit", 0, ®ex_mode, RUNPARTS_LSBSYSINIT},
499 {"regex", 1, ®ex_mode, RUNPARTS_ERE},
500 {"exit-on-error", 0, &exit_on_error_mode, 1},
501 {"new-session", 0, &new_session_mode, 1},
505 c = getopt_long(argc, argv, "u:ha:vV", long_options, &option_index);
510 if(option_index==10) { /* hardcoding this will lead to trouble */
511 custom_ere = strdup(optarg);
518 add_argument(optarg);
530 fprintf(stderr, "Try `run-parts --help' for more information.\n");
535 /* We require exactly one argument: the directory name */
536 if (optind != (argc - 1)) {
537 error("missing operand");
538 fprintf(stderr, "Try `run-parts --help' for more information.\n");
540 } else if (list_mode && test_mode) {
541 error("--list and --test can not be used together");
542 fprintf(stderr, "Try `run-parts --help' for more information.\n");
546 regex_compile_pattern();
547 run_parts(argv[optind]);
558 * Compile patterns used by the application
560 * In order for a string to be matched by a pattern, this pattern must be
561 * compiled with the regcomp function. If an error occurs, the application
562 * exits and displays the error.
565 regex_compile_pattern (void)
570 if (regex_mode == RUNPARTS_ERE) {
572 if ((err = regcomp(&customre, custom_ere,
573 REG_EXTENDED | REG_NOSUB)) != 0)
574 pt_regex = &customre;
576 } else if (regex_mode == RUNPARTS_LSBSYSINIT) {
578 if ( (err = regcomp(&hierre, "^_?([a-z0-9_.]+-)+[a-z0-9]+$",
579 REG_EXTENDED | REG_NOSUB)) != 0)
582 else if ( (err = regcomp(&excsre, "^[a-z0-9-].*dpkg-(old|dist|new|tmp)$",
583 REG_EXTENDED | REG_NOSUB)) != 0)
586 else if ( (err = regcomp(&tradre, "^[a-z0-9][a-z0-9-]*$", REG_NOSUB))
590 } else if ( (err = regcomp(&classicalre, "^[a-zA-Z0-9_-]+$",
591 REG_EXTENDED | REG_NOSUB)) != 0)
592 pt_regex = &classicalre;
595 fprintf(stderr, "Unable to build regexp: %s", \
596 regex_get_error(err, pt_regex));
604 * This function allocates a buffer to store the regex error description.
605 * If a buffer cannot be allocated, then the use of xmalloc will end the
608 * @errcode: return error code from a one of the regex functions
609 * @compiled: compile pattern which causes the failure
611 * It returns a pointer on the current regex error description.
614 regex_get_error(int errcode, regex_t *compiled)
619 length = regerror(errcode, compiled, NULL, 0);
620 buf = malloc(length);
622 error("Virtual memory exhausted\n");
626 regerror(errcode, compiled, buf, length);
632 * Clean the compiled patterns according to the current regex_mode
637 if (regex_mode == RUNPARTS_ERE)
640 else if (regex_mode == RUNPARTS_LSBSYSINIT) {
646 regfree(&classicalre);