Update menuconfig items with approximate applet sizes
[oweals/busybox.git] / debianutils / run_parts.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini run-parts implementation for busybox
4  *
5  * Copyright (C) 2007 Bernhard Reutner-Fischer
6  *
7  * Based on a older version that was in busybox which was 1k big.
8  *   Copyright (C) 2001 by Emanuele Aina <emanuele.aina@tiscali.it>
9  *
10  * Based on the Debian run-parts program, version 1.15
11  *   Copyright (C) 1996 Jeff Noxon <jeff@router.patch.net>,
12  *   Copyright (C) 1996-1999 Guy Maor <maor@debian.org>
13  *
14  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
15  */
16
17 /* This is my first attempt to write a program in C (well, this is my first
18  * attempt to write a program! :-) . */
19
20 /* This piece of code is heavily based on the original version of run-parts,
21  * taken from debian-utils. I've only removed the long options and the
22  * report mode. As the original run-parts support only long options, I've
23  * broken compatibility because the BusyBox policy doesn't allow them.
24  */
25 //config:config RUN_PARTS
26 //config:       bool "run-parts (5.6 kb)"
27 //config:       default y
28 //config:       help
29 //config:         run-parts is a utility designed to run all the scripts in a directory.
30 //config:
31 //config:         It is useful to set up a directory like cron.daily, where you need to
32 //config:         execute all the scripts in that directory.
33 //config:
34 //config:         In this implementation of run-parts some features (such as report
35 //config:         mode) are not implemented.
36 //config:
37 //config:         Unless you know that run-parts is used in some of your scripts
38 //config:         you can safely say N here.
39 //config:
40 //config:config FEATURE_RUN_PARTS_LONG_OPTIONS
41 //config:       bool "Enable long options"
42 //config:       default y
43 //config:       depends on RUN_PARTS && LONG_OPTS
44 //config:
45 //config:config FEATURE_RUN_PARTS_FANCY
46 //config:       bool "Support additional arguments"
47 //config:       default y
48 //config:       depends on RUN_PARTS
49 //config:       help
50 //config:         Support additional options:
51 //config:         -l --list print the names of the all matching files (not
52 //config:                   limited to executables), but don't actually run them.
53
54 //applet:IF_RUN_PARTS(APPLET_ODDNAME(run-parts, run_parts, BB_DIR_BIN, BB_SUID_DROP, run_parts))
55
56 //kbuild:lib-$(CONFIG_RUN_PARTS) += run_parts.o
57
58 //usage:#define run_parts_trivial_usage
59 //usage:       "[-a ARG]... [-u UMASK] "
60 //usage:       IF_FEATURE_RUN_PARTS_LONG_OPTIONS("[--reverse] [--test] [--exit-on-error] "IF_FEATURE_RUN_PARTS_FANCY("[--list] "))
61 //usage:       "DIRECTORY"
62 //usage:#define run_parts_full_usage "\n\n"
63 //usage:       "Run a bunch of scripts in DIRECTORY\n"
64 //usage:     "\n        -a ARG          Pass ARG as argument to scripts"
65 //usage:     "\n        -u UMASK        Set UMASK before running scripts"
66 //usage:        IF_FEATURE_RUN_PARTS_LONG_OPTIONS(
67 //usage:     "\n        --reverse       Reverse execution order"
68 //usage:     "\n        --test          Dry run"
69 //usage:     "\n        --exit-on-error Exit if a script exits with non-zero"
70 //usage:        IF_FEATURE_RUN_PARTS_FANCY(
71 //usage:     "\n        --list          Print names of matching files even if they are not executable"
72 //usage:        )
73 //usage:        )
74 //usage:
75 //usage:#define run_parts_example_usage
76 //usage:       "$ run-parts -a start /etc/init.d\n"
77 //usage:       "$ run-parts -a stop=now /etc/init.d\n\n"
78 //usage:       "Let's assume you have a script foo/dosomething:\n"
79 //usage:       "#!/bin/sh\n"
80 //usage:       "for i in $*; do eval $i; done; unset i\n"
81 //usage:       "case \"$1\" in\n"
82 //usage:       "start*) echo starting something;;\n"
83 //usage:       "stop*) set -x; shutdown -h $stop;;\n"
84 //usage:       "esac\n\n"
85 //usage:       "Running this yields:\n"
86 //usage:       "$run-parts -a stop=+4m foo/\n"
87 //usage:       "+ shutdown -h +4m"
88
89 #include "libbb.h"
90 #include "common_bufsiz.h"
91
92 struct globals {
93         char **names;
94         int    cur;
95         char  *cmd[2 /* using 1 provokes compiler warning */];
96 } FIX_ALIASING;
97 #define G (*(struct globals*)bb_common_bufsiz1)
98 #define names (G.names)
99 #define cur   (G.cur  )
100 #define cmd   (G.cmd  )
101 #define INIT_G() do { setup_common_bufsiz(); } while (0)
102
103 enum { NUM_CMD = (COMMON_BUFSIZE - sizeof(G)) / sizeof(cmd[0]) - 1 };
104
105 enum {
106         OPT_a = (1 << 0),
107         OPT_u = (1 << 1),
108         OPT_r = (1 << 2) * ENABLE_FEATURE_RUN_PARTS_LONG_OPTIONS,
109         OPT_t = (1 << 3) * ENABLE_FEATURE_RUN_PARTS_LONG_OPTIONS,
110         OPT_e = (1 << 4) * ENABLE_FEATURE_RUN_PARTS_LONG_OPTIONS,
111         OPT_l = (1 << 5) * ENABLE_FEATURE_RUN_PARTS_LONG_OPTIONS
112                         * ENABLE_FEATURE_RUN_PARTS_FANCY,
113 };
114
115 /* Is this a valid filename (upper/lower alpha, digits,
116  * underscores, and hyphens only?)
117  */
118 static bool invalid_name(const char *c)
119 {
120         c = bb_basename(c);
121
122         while (*c && (isalnum(*c) || *c == '_' || *c == '-'))
123                 c++;
124
125         return *c; /* TRUE (!0) if terminating NUL is not reached */
126 }
127
128 static int bb_alphasort(const void *p1, const void *p2)
129 {
130         int r = strcmp(*(char **) p1, *(char **) p2);
131         return (option_mask32 & OPT_r) ? -r : r;
132 }
133
134 static int FAST_FUNC act(const char *file, struct stat *statbuf, void *args UNUSED_PARAM, int depth)
135 {
136         if (depth == 1)
137                 return TRUE;
138
139         if (depth == 2
140          && (  !(statbuf->st_mode & (S_IFREG | S_IFLNK))
141             || invalid_name(file)
142             || (!(option_mask32 & OPT_l) && access(file, X_OK) != 0))
143         ) {
144                 return SKIP;
145         }
146
147         names = xrealloc_vector(names, 4, cur);
148         names[cur++] = xstrdup(file);
149         /*names[cur] = NULL; - xrealloc_vector did it */
150
151         return TRUE;
152 }
153
154 #if ENABLE_FEATURE_RUN_PARTS_LONG_OPTIONS
155 static const char runparts_longopts[] ALIGN1 =
156         "arg\0"     Required_argument "a"
157         "umask\0"   Required_argument "u"
158 //TODO: "verbose\0" No_argument       "v"
159         "reverse\0" No_argument       "\xf0"
160         "test\0"    No_argument       "\xf1"
161         "exit-on-error\0" No_argument "\xf2"
162 #if ENABLE_FEATURE_RUN_PARTS_FANCY
163         "list\0"    No_argument       "\xf3"
164 #endif
165         ;
166 #endif
167
168 int run_parts_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
169 int run_parts_main(int argc UNUSED_PARAM, char **argv)
170 {
171         const char *umask_p = "22";
172         llist_t *arg_list = NULL;
173         unsigned n;
174         int ret;
175
176         INIT_G();
177
178 #if ENABLE_FEATURE_RUN_PARTS_LONG_OPTIONS
179         applet_long_options = runparts_longopts;
180 #endif
181         /* We require exactly one argument: the directory name */
182         opt_complementary = "=1";
183         getopt32(argv, "a:*u:", &arg_list, &umask_p);
184
185         umask(xstrtou_range(umask_p, 8, 0, 07777));
186
187         n = 1;
188         while (arg_list && n < NUM_CMD) {
189                 cmd[n++] = llist_pop(&arg_list);
190         }
191         /* cmd[n] = NULL; - is already zeroed out */
192
193         /* run-parts has to sort executables by name before running them */
194
195         recursive_action(argv[optind],
196                         ACTION_RECURSE|ACTION_FOLLOWLINKS,
197                         act,            /* file action */
198                         act,            /* dir action */
199                         NULL,           /* user data */
200                         1               /* depth */
201                 );
202
203         if (!names)
204                 return 0;
205
206         qsort(names, cur, sizeof(char *), bb_alphasort);
207
208         n = 0;
209         while (1) {
210                 char *name = *names++;
211                 if (!name)
212                         break;
213                 if (option_mask32 & (OPT_t | OPT_l)) {
214                         puts(name);
215                         continue;
216                 }
217                 cmd[0] = name;
218                 ret = spawn_and_wait(cmd);
219                 if (ret == 0)
220                         continue;
221                 n = 1;
222                 if (ret < 0)
223                         bb_perror_msg("can't execute '%s'", name);
224                 else /* ret > 0 */
225                         bb_error_msg("%s: exit status %u", name, ret & 0xff);
226
227                 if (option_mask32 & OPT_e)
228                         xfunc_die();
229         }
230
231         return n;
232 }