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 if (!regexec(&classicalre, s, 0, NULL, 0)) {
162 retval = regexec(&excsre, s, 0, NULL, 0);
170 void run_part(char *progname)
174 int pout[2], perr[2];
178 if (report_mode && (pipe(pout) || pipe(perr))) {
179 error("pipe: %s", strerror(errno));
182 if ((pid = fork()) < 0) {
183 error("failed to fork: %s", strerror(errno));
188 if (new_session_mode)
191 if (dup2(pout[1], STDOUT_FILENO) == -1 ||
192 dup2(perr[1], STDERR_FILENO) == -1) {
193 error("dup2: %s", strerror(errno));
202 execv(progname, args);
203 error("failed to exec %s: %s", progname, strerror(errno));
210 struct timespec zero_timeout;
211 struct timespec *the_timeout;
216 sigemptyset(&tempmask);
217 sigprocmask(0, NULL, &tempmask);
218 sigdelset(&tempmask, SIGCHLD);
220 memset(&zero_timeout, 0, sizeof(zero_timeout));
225 max = pout[0] > perr[0] ? pout[0] + 1 : perr[0] + 1;
228 while (pout[0] >= 0 || perr[0] >= 0) {
230 r = waitpid(pid, &result, WNOHANG);
232 error("waitpid: %s", strerror(errno));
235 if (r != 0 && (WIFEXITED(result) || WIFSIGNALED(result))) {
236 /* If the process dies, set a zero timeout. Rarely, some processes
237 * leak file descriptors (e.g., by starting a naughty daemon).
238 * select() would wait forever since the pipes wouldn't close.
239 * We loop, with a zero timeout, until there's no data left, then
240 * give up. This shouldn't affect non-leaky processes. */
242 the_timeout = &zero_timeout;
248 FD_SET(pout[0], &set);
250 FD_SET(perr[0], &set);
251 r = pselect(max, &set, 0, 0, the_timeout, &tempmask);
257 error("select: %s", strerror(errno));
261 /* If STDOUT or STDERR get closed / full, we still run to completion
262 * (and just ignore that we can't output process output any more).
263 * Perhaps we should instead kill the child process we are running
265 * For now partial writes are not retried to complete - that can
266 * and should be done, but needs care to ensure that we don't hang
267 * if the fd doesn't accept more data ever - or we need to decide that
268 * waiting is the appropriate thing to do.
271 if (pout[0] >= 0 && FD_ISSET(pout[0], &set)) {
272 c = read(pout[0], buf, sizeof(buf));
275 printf("%s:\n", progname);
279 ignored = write(STDOUT_FILENO, buf, c);
288 error("failed to read from stdout pipe: %s", strerror (errno));
291 if (perr[0] >= 0 && FD_ISSET(perr[0], &set)) {
292 c = read(perr[0], buf, sizeof(buf));
295 fprintf(stderr, "%s:\n", progname);
299 ignored = write(STDERR_FILENO, buf, c);
308 error("failed to read from error pipe: %s", strerror (errno));
312 else if (r == 0 && waited) {
313 /* Zero timeout, no data left. */
320 /* assert(FALSE): select was called with infinite timeout, so
321 it either returns successfully or is interrupted */
327 r = waitpid(pid, &result, 0);
330 error("waitpid: %s", strerror(errno));
335 if (WIFEXITED(result) && WEXITSTATUS(result)) {
336 error("%s exited with return code %d", progname, WEXITSTATUS(result));
339 else if (WIFSIGNALED(result)) {
340 error("%s exited because of uncaught signal %d", progname,
346 static void handle_signal(int s)
351 /* Catch SIGCHLD with an empty function to interrupt select() */
352 static void catch_signals()
354 struct sigaction act;
357 memset(&act, 0, sizeof(act));
358 act.sa_handler = handle_signal;
359 act.sa_flags = SA_NOCLDSTOP;
360 sigaction(SIGCHLD, &act, NULL);
363 sigaddset(&set, SIGCHLD);
364 sigprocmask(SIG_BLOCK, &set, NULL);
367 /* Unblock signals before execing a child */
368 static void restore_signals()
372 sigaddset(&set, SIGCHLD);
373 sigprocmask(SIG_UNBLOCK, &set, NULL);
376 /* Find the parts to run & call run_part() */
377 void run_parts(char *dirname)
379 struct dirent **namelist;
381 size_t filename_length, dirname_length;
382 int entries, i, result;
386 dirname_length = strlen(dirname) + 1;
387 /* dirname + "/" + ".." + "\0" (This will save one realloc.) */
388 filename_length = dirname_length + 2 + 1;
389 if (!(filename = malloc(filename_length))) {
390 error("failed to allocate memory for path: %s", strerror(errno));
393 strcpy(filename, dirname);
394 strcat(filename, "/");
396 /* scandir() isn't POSIX, but it makes things easy. */
397 entries = scandir(dirname, &namelist, valid_name, alphasort);
399 error("failed to open directory %s: %s", dirname, strerror(errno));
403 i = reverse_mode ? 0 : entries;
404 for (i = reverse_mode ? (entries - 1) : 0;
405 reverse_mode ? (i >= 0) : (i < entries); reverse_mode ? i-- : i++) {
406 if (filename_length < dirname_length + strlen(namelist[i]->d_name) + 1) {
407 filename_length = dirname_length + strlen(namelist[i]->d_name) + 1;
408 if (!(filename = realloc(filename, filename_length))) {
409 error("failed to reallocate memory for path: %s", strerror(errno));
413 strcpy(filename + dirname_length, namelist[i]->d_name);
415 strcpy(filename, dirname);
416 strcat(filename, "/");
417 strcat(filename, namelist[i]->d_name);
419 result = stat(filename, &st);
421 error("failed to stat component %s: %s", filename, strerror(errno));
422 if (exit_on_error_mode) {
429 if (S_ISREG(st.st_mode)) {
430 if (!access(filename, X_OK)) {
432 printf("%s\n", filename);
434 else if (list_mode) {
435 if (!access(filename, R_OK))
436 printf("%s\n", filename);
443 fprintf(stderr, "run-parts: executing %s", filename);
445 fprintf(stderr, " %s", *a);
446 fprintf(stderr, "\n");
448 fprintf(stderr, "run-parts: executing %s\n", filename);
451 if (exitstatus != 0 && exit_on_error_mode) return;
454 else if (!access(filename, R_OK)) {
456 printf("%s\n", filename);
459 else if (S_ISLNK(st.st_mode)) {
461 error("run-parts: component %s is a broken symbolic link\n",filename);
466 else if (!S_ISDIR(st.st_mode)) {
468 error("run-parts: component %s is not an executable plain file\n",
480 /* Process options */
481 int main(int argc, char *argv[])
489 int option_index = 0;
491 static struct option long_options[] = {
492 {"test", 0, &test_mode, 1},
493 {"list", 0, &list_mode, 1},
494 {"verbose", 0, 0, 'v'},
495 {"report", 0, &report_mode, 1},
496 {"reverse", 0, &reverse_mode, 1},
497 {"umask", 1, 0, 'u'},
500 {"version", 0, 0, 'V'},
501 {"lsbsysinit", 0, ®ex_mode, RUNPARTS_LSBSYSINIT},
502 {"regex", 1, ®ex_mode, RUNPARTS_ERE},
503 {"exit-on-error", 0, &exit_on_error_mode, 1},
504 {"new-session", 0, &new_session_mode, 1},
508 c = getopt_long(argc, argv, "u:ha:vV", long_options, &option_index);
513 if(option_index==10) { /* hardcoding this will lead to trouble */
514 custom_ere = strdup(optarg);
521 add_argument(optarg);
533 fprintf(stderr, "Try `run-parts --help' for more information.\n");
538 /* We require exactly one argument: the directory name */
539 if (optind != (argc - 1)) {
540 error("missing operand");
541 fprintf(stderr, "Try `run-parts --help' for more information.\n");
543 } else if (list_mode && test_mode) {
544 error("--list and --test can not be used together");
545 fprintf(stderr, "Try `run-parts --help' for more information.\n");
549 regex_compile_pattern();
550 run_parts(argv[optind]);
561 * Compile patterns used by the application
563 * In order for a string to be matched by a pattern, this pattern must be
564 * compiled with the regcomp function. If an error occurs, the application
565 * exits and displays the error.
568 regex_compile_pattern (void)
573 if (regex_mode == RUNPARTS_ERE) {
575 if ((err = regcomp(&customre, custom_ere,
576 REG_EXTENDED | REG_NOSUB)) != 0)
577 pt_regex = &customre;
579 } else if (regex_mode == RUNPARTS_LSBSYSINIT) {
581 if ( (err = regcomp(&hierre, "^_?([a-z0-9_.]+-)+[a-z0-9]+$",
582 REG_EXTENDED | REG_NOSUB)) != 0)
585 else if ( (err = regcomp(&excsre, "^[a-z0-9-].*(\.rpm(save|new|orig)|~|,v)$",
586 REG_EXTENDED | REG_NOSUB)) != 0)
589 else if ( (err = regcomp(&tradre, "^[a-z0-9][a-z0-9-]*$", REG_NOSUB))
593 } else if ( (err = regcomp(&classicalre, "^.+$",
594 REG_EXTENDED | REG_NOSUB)) != 0)
595 pt_regex = &classicalre;
596 else if ( (err = regcomp(&excsre, "^[.]|(\.rpm(save|new|orig)|~|,v)$",
597 REG_EXTENDED | REG_NOSUB)) != 0)
601 fprintf(stderr, "Unable to build regexp: %s", \
602 regex_get_error(err, pt_regex));
610 * This function allocates a buffer to store the regex error description.
611 * If a buffer cannot be allocated, then the use of xmalloc will end the
614 * @errcode: return error code from a one of the regex functions
615 * @compiled: compile pattern which causes the failure
617 * It returns a pointer on the current regex error description.
620 regex_get_error(int errcode, regex_t *compiled)
625 length = regerror(errcode, compiled, NULL, 0);
626 buf = malloc(length);
628 error("Virtual memory exhausted\n");
632 regerror(errcode, compiled, buf, length);
638 * Clean the compiled patterns according to the current regex_mode
643 if (regex_mode == RUNPARTS_ERE)
646 else if (regex_mode == RUNPARTS_LSBSYSINIT) {
652 regfree(&classicalre);