move help text from include/usage.src.h to debianutils/*.c e2fsprogs/*.c editors...
[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  *
15  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
16  */
17
18 /* This is my first attempt to write a program in C (well, this is my first
19  * attempt to write a program! :-) . */
20
21 /* This piece of code is heavily based on the original version of run-parts,
22  * taken from debian-utils. I've only removed the long options and a the
23  * report mode. As the original run-parts support only long options, I've
24  * broken compatibility because the BusyBox policy doesn't allow them.
25  * The supported options are:
26  * -t           test. Print the name of the files to be executed, without
27  *              execute them.
28  * -a ARG       argument. Pass ARG as an argument the program executed. It can
29  *              be repeated to pass multiple arguments.
30  * -u MASK      umask. Set the umask of the program executed to MASK.
31  */
32
33 //usage:#define run_parts_trivial_usage
34 //usage:       "[-t] "IF_FEATURE_RUN_PARTS_FANCY("[-l] ")"[-a ARG] [-u MASK] DIRECTORY"
35 //usage:#define run_parts_full_usage "\n\n"
36 //usage:       "Run a bunch of scripts in DIRECTORY\n"
37 //usage:     "\nOptions:"
38 //usage:     "\n        -t      Print what would be run, but don't actually run anything"
39 //usage:     "\n        -a ARG  Pass ARG as argument for every program"
40 //usage:     "\n        -u MASK Set the umask to MASK before running every program"
41 //usage:        IF_FEATURE_RUN_PARTS_FANCY(
42 //usage:     "\n        -l      Print names of all matching files even if they are not executable"
43 //usage:        )
44 //usage:
45 //usage:#define run_parts_example_usage
46 //usage:       "$ run-parts -a start /etc/init.d\n"
47 //usage:       "$ run-parts -a stop=now /etc/init.d\n\n"
48 //usage:       "Let's assume you have a script foo/dosomething:\n"
49 //usage:       "#!/bin/sh\n"
50 //usage:       "for i in $*; do eval $i; done; unset i\n"
51 //usage:       "case \"$1\" in\n"
52 //usage:       "start*) echo starting something;;\n"
53 //usage:       "stop*) set -x; shutdown -h $stop;;\n"
54 //usage:       "esac\n\n"
55 //usage:       "Running this yields:\n"
56 //usage:       "$run-parts -a stop=+4m foo/\n"
57 //usage:       "+ shutdown -h +4m"
58
59 #include "libbb.h"
60
61 struct globals {
62         char **names;
63         int    cur;
64         char  *cmd[1];
65 } FIX_ALIASING;
66 #define G (*(struct globals*)&bb_common_bufsiz1)
67 #define names (G.names)
68 #define cur   (G.cur  )
69 #define cmd   (G.cmd  )
70
71 enum { NUM_CMD = (COMMON_BUFSIZE - sizeof(G)) / sizeof(cmd[0]) - 1 };
72
73 enum {
74         OPT_r = (1 << 0),
75         OPT_a = (1 << 1),
76         OPT_u = (1 << 2),
77         OPT_t = (1 << 3),
78         OPT_l = (1 << 4) * ENABLE_FEATURE_RUN_PARTS_FANCY,
79 };
80
81 #if ENABLE_FEATURE_RUN_PARTS_FANCY
82 #define list_mode (option_mask32 & OPT_l)
83 #else
84 #define list_mode 0
85 #endif
86
87 /* Is this a valid filename (upper/lower alpha, digits,
88  * underscores, and hyphens only?)
89  */
90 static bool invalid_name(const char *c)
91 {
92         c = bb_basename(c);
93
94         while (*c && (isalnum(*c) || *c == '_' || *c == '-'))
95                 c++;
96
97         return *c; /* TRUE (!0) if terminating NUL is not reached */
98 }
99
100 static int bb_alphasort(const void *p1, const void *p2)
101 {
102         int r = strcmp(*(char **) p1, *(char **) p2);
103         return (option_mask32 & OPT_r) ? -r : r;
104 }
105
106 static int FAST_FUNC act(const char *file, struct stat *statbuf, void *args UNUSED_PARAM, int depth)
107 {
108         if (depth == 1)
109                 return TRUE;
110
111         if (depth == 2
112          && (  !(statbuf->st_mode & (S_IFREG | S_IFLNK))
113             || invalid_name(file)
114             || (!list_mode && access(file, X_OK) != 0))
115         ) {
116                 return SKIP;
117         }
118
119         names = xrealloc_vector(names, 4, cur);
120         names[cur++] = xstrdup(file);
121         /*names[cur] = NULL; - xrealloc_vector did it */
122
123         return TRUE;
124 }
125
126 #if ENABLE_FEATURE_RUN_PARTS_LONG_OPTIONS
127 static const char runparts_longopts[] ALIGN1 =
128         "arg\0"     Required_argument "a"
129         "umask\0"   Required_argument "u"
130         "test\0"    No_argument       "t"
131 #if ENABLE_FEATURE_RUN_PARTS_FANCY
132         "list\0"    No_argument       "l"
133         "reverse\0" No_argument       "r"
134 //TODO: "verbose\0" No_argument       "v"
135 #endif
136         ;
137 #endif
138
139 int run_parts_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
140 int run_parts_main(int argc UNUSED_PARAM, char **argv)
141 {
142         const char *umask_p = "22";
143         llist_t *arg_list = NULL;
144         unsigned n;
145         int ret;
146
147 #if ENABLE_FEATURE_RUN_PARTS_LONG_OPTIONS
148         applet_long_options = runparts_longopts;
149 #endif
150         /* We require exactly one argument: the directory name */
151         opt_complementary = "=1:a::";
152         getopt32(argv, "ra:u:t"IF_FEATURE_RUN_PARTS_FANCY("l"), &arg_list, &umask_p);
153
154         umask(xstrtou_range(umask_p, 8, 0, 07777));
155
156         n = 1;
157         while (arg_list && n < NUM_CMD) {
158                 cmd[n++] = llist_pop(&arg_list);
159         }
160         /* cmd[n] = NULL; - is already zeroed out */
161
162         /* run-parts has to sort executables by name before running them */
163
164         recursive_action(argv[optind],
165                         ACTION_RECURSE|ACTION_FOLLOWLINKS,
166                         act,            /* file action */
167                         act,            /* dir action */
168                         NULL,           /* user data */
169                         1               /* depth */
170                 );
171
172         if (!names)
173                 return 0;
174
175         qsort(names, cur, sizeof(char *), bb_alphasort);
176
177         n = 0;
178         while (1) {
179                 char *name = *names++;
180                 if (!name)
181                         break;
182                 if (option_mask32 & (OPT_t | OPT_l)) {
183                         puts(name);
184                         continue;
185                 }
186                 cmd[0] = name;
187                 ret = spawn_and_wait(cmd);
188                 if (ret == 0)
189                         continue;
190                 n = 1;
191                 if (ret < 0)
192                         bb_perror_msg("can't execute '%s'", name);
193                 else /* ret > 0 */
194                         bb_error_msg("%s exited with code %d", name, ret & 0xff);
195         }
196
197         return n;
198 }