]> git.pld-linux.org Git - projects/rc-scripts.git/blame - src/run-parts.c
set DHCP_HOSTNAME only basename, domain part is filled by dhcp server
[projects/rc-scripts.git] / src / run-parts.c
CommitLineData
868bbbe0
ER
1/* run-parts: run a bunch of scripts in a directory
2 *
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>
7 *
8 * This is free software; see the GNU General Public License version 2
9 * or later for copying conditions. There is NO warranty.
10 *
11 * Based on run-parts.pl version 0.2, Copyright (C) 1994 Ian Jackson.
12 *
13 */
14
15#include <stdio.h>
16#include <stdarg.h>
17#include <stdlib.h>
18#include <sys/types.h>
19#include <sys/wait.h>
20#include <dirent.h>
21#include <sys/stat.h>
22#include <unistd.h>
23#include <fcntl.h>
24#ifdef HAVE_GETOPT_H
25#include <getopt.h>
26#endif /* HAVE_GETOPT_H */
27#include <string.h>
28#include <errno.h>
29#include <ctype.h>
30#include <signal.h>
31#include <sys/time.h>
32#include <regex.h>
33
34#define RUNPARTS_NORMAL 0
35#define RUNPARTS_ERE 1
36#define RUNPARTS_LSBSYSINIT 100
37
38int test_mode = 0;
39int list_mode = 0;
40int verbose_mode = 0;
41int report_mode = 0;
42int reverse_mode = 0;
43int exitstatus = 0;
44int regex_mode = 0;
45int exit_on_error_mode = 0;
46int new_session_mode = 0;
47
48int argcount = 0, argsize = 0;
49char **args = 0;
50
51char *custom_ere;
52regex_t hierre, tradre, excsre, classicalre, customre;
53
54static void catch_signals();
55static void restore_signals();
56
57static char* regex_get_error(int errcode, regex_t *compiled);
58static void regex_compile_pattern(void);
59static void regex_clean(void);
60
61void error(char *format, ...)
62{
63 va_list ap;
64
65 fprintf(stderr, "run-parts: ");
66
67 va_start(ap, format);
68 vfprintf(stderr, format, ap);
69 va_end(ap);
70
71 fprintf(stderr, "\n");
72}
73
74
75void version()
76{
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");
83 exit(0);
84}
85
86
87void usage()
88{
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"
92 " --test)\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"
97 " code.\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");
105 exit(0);
106}
107
108
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.
111 */
112void set_umask()
113{
114 int mask, result;
115
116 result = sscanf(optarg, "%o", &mask);
117 if ((result != 1) || (mask > 07777) || (mask < 0)) {
118 error("bad umask value");
119 exit(1);
120 }
121
122 umask(mask);
123}
124
125/* Add an argument to the commands that we will call. Called once for
126 every argument. */
127void add_argument(char *newarg)
128{
129 if (argcount + 1 >= argsize) {
130 argsize = argsize ? argsize * 2 : 4;
131 args = realloc(args, argsize * (sizeof(char *)));
132 if (!args) {
133 error("failed to reallocate memory for arguments: %s", strerror(errno));
134 exit(1);
135 }
136 }
137 args[argcount++] = newarg;
138 args[argcount] = 0;
139}
140
141/* True or false? Is this a valid filename? */
142int valid_name(const struct dirent *d)
143{
144 char *s;
145 unsigned int retval;
146
147 s = (char *)&(d->d_name);
148
149 if (regex_mode == RUNPARTS_ERE)
150 retval = !regexec(&customre, s, 0, NULL, 0);
151
152 else if (regex_mode == RUNPARTS_LSBSYSINIT) {
153
154 if (!regexec(&hierre, s, 0, NULL, 0))
155 retval = regexec(&excsre, s, 0, NULL, 0);
156
157 else
158 retval = !regexec(&tradre, s, 0, NULL, 0);
159
160 } else
161 retval = !regexec(&classicalre, s, 0, NULL, 0);
162
163 return retval;
164}
165
166/* Execute a file */
167void run_part(char *progname)
168{
169 int result, waited;
170 int pid, r;
171 int pout[2], perr[2];
172
173 waited = 0;
174
175 if (report_mode && (pipe(pout) || pipe(perr))) {
176 error("pipe: %s", strerror(errno));
177 exit(1);
178 }
179 if ((pid = fork()) < 0) {
180 error("failed to fork: %s", strerror(errno));
181 exit(1);
182 }
183 else if (!pid) {
184 restore_signals();
185 if (new_session_mode)
186 setsid();
187 if (report_mode) {
188 if (dup2(pout[1], STDOUT_FILENO) == -1 ||
189 dup2(perr[1], STDERR_FILENO) == -1) {
190 error("dup2: %s", strerror(errno));
191 exit(1);
192 }
193 close(pout[0]);
194 close(perr[0]);
195 close(pout[1]);
196 close(perr[1]);
197 }
198 args[0] = progname;
199 execv(progname, args);
200 error("failed to exec %s: %s", progname, strerror(errno));
201 exit(1);
202 }
203
204 if (report_mode) {
205 fd_set set;
206 sigset_t tempmask;
207 struct timespec zero_timeout;
208 struct timespec *the_timeout;
209 int max, printflag;
210 ssize_t c;
211 char buf[4096];
212
213 sigemptyset(&tempmask);
214 sigprocmask(0, NULL, &tempmask);
215 sigdelset(&tempmask, SIGCHLD);
216
217 memset(&zero_timeout, 0, sizeof(zero_timeout));
218 the_timeout = NULL;
219
220 close(pout[1]);
221 close(perr[1]);
222 max = pout[0] > perr[0] ? pout[0] + 1 : perr[0] + 1;
223 printflag = 0;
224
225 while (pout[0] >= 0 || perr[0] >= 0) {
226 if (!waited) {
227 r = waitpid(pid, &result, WNOHANG);
228 if (r == -1) {
229 error("waitpid: %s", strerror(errno));
230 exit(1);
231 }
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. */
238 waited = 1;
239 the_timeout = &zero_timeout;
240 }
241 }
242
243 FD_ZERO(&set);
244 if (pout[0] >= 0)
245 FD_SET(pout[0], &set);
246 if (perr[0] >= 0)
247 FD_SET(perr[0], &set);
248 r = pselect(max, &set, 0, 0, the_timeout, &tempmask);
249
250 if (r < 0) {
251 if (errno == EINTR)
252 continue;
253
254 error("select: %s", strerror(errno));
255 exit(1);
256 }
257 else if (r > 0) {
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
261 * if that happens.
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.
266 */
267 int ignored;
268 if (pout[0] >= 0 && FD_ISSET(pout[0], &set)) {
269 c = read(pout[0], buf, sizeof(buf));
270 if (c > 0) {
271 if (!printflag) {
272 printf("%s:\n", progname);
273 fflush(stdout);
274 printflag = 1;
275 }
276 ignored = write(STDOUT_FILENO, buf, c);
277 }
278 else if (c == 0) {
279 close(pout[0]);
280 pout[0] = -1;
281 }
282 else if (c < 0) {
283 close(pout[0]);
284 pout[0] = -1;
285 error("failed to read from stdout pipe: %s", strerror (errno));
286 }
287 }
288 if (perr[0] >= 0 && FD_ISSET(perr[0], &set)) {
289 c = read(perr[0], buf, sizeof(buf));
290 if (c > 0) {
291 if (!printflag) {
292 fprintf(stderr, "%s:\n", progname);
293 fflush(stderr);
294 printflag = 1;
295 }
296 ignored = write(STDERR_FILENO, buf, c);
297 }
298 else if (c == 0) {
299 close(perr[0]);
300 perr[0] = -1;
301 }
302 else if (c < 0) {
303 close(perr[0]);
304 perr[0] = -1;
305 error("failed to read from error pipe: %s", strerror (errno));
306 }
307 }
308 }
309 else if (r == 0 && waited) {
310 /* Zero timeout, no data left. */
311 close(perr[0]);
312 perr[0] = -1;
313 close(pout[0]);
314 pout[0] = -1;
315 }
316 else {
317 /* assert(FALSE): select was called with infinite timeout, so
318 it either returns successfully or is interrupted */
319 } /*if */
320 } /*while */
321 }
322
323 if (!waited) {
324 r = waitpid(pid, &result, 0);
325
326 if (r == -1) {
327 error("waitpid: %s", strerror(errno));
328 exit(1);
329 }
330 }
331
332 if (WIFEXITED(result) && WEXITSTATUS(result)) {
333 error("%s exited with return code %d", progname, WEXITSTATUS(result));
334 exitstatus = 1;
335 }
336 else if (WIFSIGNALED(result)) {
337 error("%s exited because of uncaught signal %d", progname,
338 WTERMSIG(result));
339 exitstatus = 1;
340 }
341}
342
343static void handle_signal(int s)
344{
345 /* Do nothing */
346}
347
348/* Catch SIGCHLD with an empty function to interrupt select() */
349static void catch_signals()
350{
351 struct sigaction act;
352 sigset_t set;
353
354 memset(&act, 0, sizeof(act));
355 act.sa_handler = handle_signal;
356 act.sa_flags = SA_NOCLDSTOP;
357 sigaction(SIGCHLD, &act, NULL);
358
359 sigemptyset(&set);
360 sigaddset(&set, SIGCHLD);
361 sigprocmask(SIG_BLOCK, &set, NULL);
362}
363
364/* Unblock signals before execing a child */
365static void restore_signals()
366{
367 sigset_t set;
368 sigemptyset(&set);
369 sigaddset(&set, SIGCHLD);
370 sigprocmask(SIG_UNBLOCK, &set, NULL);
371}
372
373/* Find the parts to run & call run_part() */
374void run_parts(char *dirname)
375{
376 struct dirent **namelist;
377 char *filename;
378 size_t filename_length, dirname_length;
379 int entries, i, result;
380 struct stat st;
381
382 /* dirname + "/" */
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));
388 exit(1);
389 }
390 strcpy(filename, dirname);
391 strcat(filename, "/");
392
393 /* scandir() isn't POSIX, but it makes things easy. */
394 entries = scandir(dirname, &namelist, valid_name, alphasort);
395 if (entries < 0) {
396 error("failed to open directory %s: %s", dirname, strerror(errno));
397 exit(1);
398 }
399
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));
407 exit(1);
408 }
409 }
410 strcpy(filename + dirname_length, namelist[i]->d_name);
411
412 strcpy(filename, dirname);
413 strcat(filename, "/");
414 strcat(filename, namelist[i]->d_name);
415
416 result = stat(filename, &st);
417 if (result < 0) {
418 error("failed to stat component %s: %s", filename, strerror(errno));
419 if (exit_on_error_mode) {
420 exit(1);
421 }
422 else
423 continue;
424 }
425
426 if (S_ISREG(st.st_mode)) {
427 if (!access(filename, X_OK)) {
428 if (test_mode) {
429 printf("%s\n", filename);
430 }
431 else if (list_mode) {
432 if (!access(filename, R_OK))
433 printf("%s\n", filename);
434 }
435 else {
436 if (verbose_mode)
437 if (argcount) {
438 char **a = args;
439
440 fprintf(stderr, "run-parts: executing %s", filename);
441 while(*(++a))
442 fprintf(stderr, " %s", *a);
443 fprintf(stderr, "\n");
444 } else {
445 fprintf(stderr, "run-parts: executing %s\n", filename);
446 }
447 run_part(filename);
448 if (exitstatus != 0 && exit_on_error_mode) return;
449 }
450 }
451 else if (!access(filename, R_OK)) {
452 if (list_mode) {
453 printf("%s\n", filename);
454 }
455 }
456 else if (S_ISLNK(st.st_mode)) {
457 if (!list_mode) {
458 error("run-parts: component %s is a broken symbolic link\n",filename);
459 exitstatus = 1;
460 }
461 }
462 }
463 else if (!S_ISDIR(st.st_mode)) {
464 if (!list_mode) {
465 error("run-parts: component %s is not an executable plain file\n",
466 filename);
467 exitstatus = 1;
468 }
469 }
470
471 free(namelist[i]);
472 }
473 free(namelist);
474 free(filename);
475}
476
477/* Process options */
478int main(int argc, char *argv[])
479{
480 custom_ere = NULL;
481 umask(022);
482 add_argument(0);
483
484 for (;;) {
485 int c;
486 int option_index = 0;
487
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'},
495 {"arg", 1, 0, 'a'},
496 {"help", 0, 0, 'h'},
497 {"version", 0, 0, 'V'},
498 {"lsbsysinit", 0, &regex_mode, RUNPARTS_LSBSYSINIT},
499 {"regex", 1, &regex_mode, RUNPARTS_ERE},
500 {"exit-on-error", 0, &exit_on_error_mode, 1},
501 {"new-session", 0, &new_session_mode, 1},
502 {0, 0, 0, 0}
503 };
504
505 c = getopt_long(argc, argv, "u:ha:vV", long_options, &option_index);
506 if (c == EOF)
507 break;
508 switch (c) {
509 case 0:
510 if(option_index==10) { /* hardcoding this will lead to trouble */
511 custom_ere = strdup(optarg);
512 }
513 break;
514 case 'u':
515 set_umask();
516 break;
517 case 'a':
518 add_argument(optarg);
519 break;
520 case 'h':
521 usage();
522 break;
523 case 'v':
524 verbose_mode = 1;
525 break;
526 case 'V':
527 version();
528 break;
529 default:
530 fprintf(stderr, "Try `run-parts --help' for more information.\n");
531 exit(1);
532 }
533 }
534
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");
539 exit(1);
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");
543 exit(1);
544 } else {
545 catch_signals();
546 regex_compile_pattern();
547 run_parts(argv[optind]);
548 regex_clean();
549
550 free(args);
551 free(custom_ere);
552
553 return exitstatus;
554 }
555}
556
557/*
558 * Compile patterns used by the application
559 *
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.
563 */
564static void
565regex_compile_pattern (void)
566{
567 int err;
568 regex_t *pt_regex;
569
570 if (regex_mode == RUNPARTS_ERE) {
571
572 if ((err = regcomp(&customre, custom_ere,
573 REG_EXTENDED | REG_NOSUB)) != 0)
574 pt_regex = &customre;
575
576 } else if (regex_mode == RUNPARTS_LSBSYSINIT) {
577
578 if ( (err = regcomp(&hierre, "^_?([a-z0-9_.]+-)+[a-z0-9]+$",
579 REG_EXTENDED | REG_NOSUB)) != 0)
580 pt_regex = &hierre;
581
582 else if ( (err = regcomp(&excsre, "^[a-z0-9-].*dpkg-(old|dist|new|tmp)$",
583 REG_EXTENDED | REG_NOSUB)) != 0)
584 pt_regex = &excsre;
585
586 else if ( (err = regcomp(&tradre, "^[a-z0-9][a-z0-9-]*$", REG_NOSUB))
587 != 0)
588 pt_regex = &tradre;
589
590 } else if ( (err = regcomp(&classicalre, "^[a-zA-Z0-9_-]+$",
591 REG_EXTENDED | REG_NOSUB)) != 0)
592 pt_regex = &classicalre;
593
594 if (err != 0) {
595 fprintf(stderr, "Unable to build regexp: %s", \
596 regex_get_error(err, pt_regex));
597 exit(1);
598 }
599}
600
601/*
602 * Get a regex error.
603 *
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
606 * program.
607 *
608 * @errcode: return error code from a one of the regex functions
609 * @compiled: compile pattern which causes the failure
610 *
611 * It returns a pointer on the current regex error description.
612 */
613static char *
614regex_get_error(int errcode, regex_t *compiled)
615{
616 size_t length;
617 char *buf;
618
619 length = regerror(errcode, compiled, NULL, 0);
620 buf = malloc(length);
621 if (buf == 0) {
622 error("Virtual memory exhausted\n");
623 exit(1);
624 }
625
626 regerror(errcode, compiled, buf, length);
627
628 return buf;
629}
630
631/*
632 * Clean the compiled patterns according to the current regex_mode
633 */
634static void
635regex_clean(void)
636{
637 if (regex_mode == RUNPARTS_ERE)
638 regfree(&customre);
639
640 else if (regex_mode == RUNPARTS_LSBSYSINIT) {
641 regfree(&hierre);
642 regfree(&excsre);
643 regfree(&tradre);
644
645 } else
646 regfree(&classicalre);
647}
This page took 0.116453 seconds and 4 git commands to generate.