mdev: fix a bug where it was not stopping on first matching rule
[platform/upstream/busybox.git] / util-linux / mdev.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *
4  * mdev - Mini udev for busybox
5  *
6  * Copyright 2005 Rob Landley <rob@landley.net>
7  * Copyright 2005 Frank Sorenson <frank@tuxrocks.com>
8  *
9  * Licensed under GPL version 2, see file LICENSE in this tarball for details.
10  */
11
12 #include "libbb.h"
13 #include "xregex.h"
14
15 struct globals {
16         int root_major, root_minor;
17 };
18 #define G (*(struct globals*)&bb_common_bufsiz1)
19 #define root_major (G.root_major)
20 #define root_minor (G.root_minor)
21
22 #define MAX_SYSFS_DEPTH 3 /* prevent infinite loops in /sys symlinks */
23
24 /* We use additional 64+ bytes in make_device() */
25 #define SCRATCH_SIZE 80
26
27 static char *next_field(char *s)
28 {
29         char *end = skip_non_whitespace(s);
30         s = skip_whitespace(end);
31         *end = '\0';
32         if (*s == '\0')
33                 s = NULL;
34         return s;
35 }
36
37 /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
38 /* NB: "mdev -s" may call us many times, do not leak memory/fds! */
39 static void make_device(char *path, int delete)
40 {
41         const char *device_name;
42         int major, minor, type, len;
43         int mode = 0660;
44         uid_t uid = 0;
45         gid_t gid = 0;
46         char *dev_maj_min = path + strlen(path);
47         char *command = NULL;
48         char *alias = NULL;
49
50         /* Force the configuration file settings exactly. */
51         umask(0);
52
53         /* Try to read major/minor string.  Note that the kernel puts \n after
54          * the data, so we don't need to worry about null terminating the string
55          * because sscanf() will stop at the first nondigit, which \n is.  We
56          * also depend on path having writeable space after it.
57          */
58         if (!delete) {
59                 strcpy(dev_maj_min, "/dev");
60                 len = open_read_close(path, dev_maj_min + 1, 64);
61                 *dev_maj_min++ = '\0';
62                 if (len < 1) {
63                         if (!ENABLE_FEATURE_MDEV_EXEC)
64                                 return;
65                         /* no "dev" file, so just try to run script */
66                         *dev_maj_min = '\0';
67                 }
68         }
69
70         /* Determine device name, type, major and minor */
71         device_name = bb_basename(path);
72         type = (path[5] == 'c' ? S_IFCHR : S_IFBLK); /* "/sys/[c]lass"? */
73
74         if (ENABLE_FEATURE_MDEV_CONF) {
75                 FILE *fp;
76                 char *line, *val, *next;
77                 unsigned lineno = 0;
78
79                 /* If we have config file, look up user settings */
80                 fp = fopen_or_warn("/etc/mdev.conf", "r");
81                 if (!fp)
82                         goto end_parse;
83
84                 while ((line = xmalloc_fgetline(fp)) != NULL) {
85                         ++lineno;
86                         trim(line);
87                         if (!line[0])
88                                 goto next_line;
89
90                         /* Fields: regex uid:gid mode [alias] [cmd] */
91
92                         /* 1st field: regex to match this device */
93                         next = next_field(line);
94                         {
95                                 regex_t match;
96                                 regmatch_t off;
97                                 int result;
98
99                                 /* Is this it? */
100                                 xregcomp(&match, line, REG_EXTENDED);
101                                 result = regexec(&match, device_name, 1, &off, 0);
102                                 regfree(&match);
103
104                                 /* If not this device, skip rest of line */
105                                 if (result || off.rm_so || off.rm_eo != strlen(device_name))
106                                         goto next_line;
107                         }
108
109                         /* This line matches: stop parsing the file
110                          * after parsing the rest of fields */
111
112                         /* 2nd field: uid:gid - device ownership */
113                         if (!next) /* field must exist */
114                                 bb_error_msg_and_die("bad line %u", lineno);
115                         val = next;
116                         next = next_field(val);
117                         {
118                                 struct passwd *pass;
119                                 struct group *grp;
120                                 char *str_uid = val;
121                                 char *str_gid = strchrnul(val, ':');
122
123                                 if (*str_gid)
124                                         *str_gid++ = '\0';
125                                 /* Parse UID */
126                                 pass = getpwnam(str_uid);
127                                 if (pass)
128                                         uid = pass->pw_uid;
129                                 else
130                                         uid = strtoul(str_uid, NULL, 10);
131                                 /* Parse GID */
132                                 grp = getgrnam(str_gid);
133                                 if (grp)
134                                         gid = grp->gr_gid;
135                                 else
136                                         gid = strtoul(str_gid, NULL, 10);
137                         }
138
139                         /* 3rd field: mode - device permissions */
140                         if (!next) /* field must exist */
141                                 bb_error_msg_and_die("bad line %u", lineno);
142                         val = next;
143                         next = next_field(val);
144                         mode = strtoul(val, NULL, 8);
145
146                         /* 4th field (opt): >alias */
147                         if (ENABLE_FEATURE_MDEV_RENAME) {
148                                 if (!next)
149                                         break;
150                                 val = next;
151                                 next = next_field(val);
152                                 if (*val == '>') {
153                                         alias = xstrdup(val + 1);
154                                 }
155                         }
156
157                         /* The rest (opt): command to run */
158                         if (!next)
159                                 break;
160                         val = next;
161                         if (ENABLE_FEATURE_MDEV_EXEC) {
162                                 const char *s = "@$*";
163                                 const char *s2 = strchr(s, *val);
164
165                                 if (!s2)
166                                         bb_error_msg_and_die("bad line %u", lineno);
167
168                                 /* Correlate the position in the "@$*" with the delete
169                                  * step so that we get the proper behavior:
170                                  * @cmd: run on create
171                                  * $cmd: run on delete
172                                  * *cmd: run on both
173                                  */
174                                 if ((s2 - s + 1) /*1/2/3*/ & /*1/2*/ (1 + delete)) {
175                                         command = xstrdup(val + 1);
176                                 }
177                         }
178                         /* end of field parsing */
179                         break; /* we found matching line, stop */
180  next_line:
181                         free(line);
182                 } /* end of "while line is read from /etc/mdev.conf" */
183
184                 free(line); /* in case we used "break" to get here */
185                 fclose(fp);
186         }
187  end_parse:
188
189         if (!delete && sscanf(dev_maj_min, "%u:%u", &major, &minor) == 2) {
190
191                 if (ENABLE_FEATURE_MDEV_RENAME)
192                         unlink(device_name);
193
194                 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
195                         bb_perror_msg_and_die("mknod %s", device_name);
196
197                 if (major == root_major && minor == root_minor)
198                         symlink(device_name, "root");
199
200                 if (ENABLE_FEATURE_MDEV_CONF) {
201                         chown(device_name, uid, gid);
202
203                         if (ENABLE_FEATURE_MDEV_RENAME && alias) {
204                                 char *dest;
205
206                                 dest = strrchr(alias, '/');
207                                 if (dest) {
208                                         if (dest[1] != '\0')
209                                                 /* given a file name, so rename it */
210                                                 *dest = '\0';
211                                         bb_make_directory(alias, 0755, FILEUTILS_RECUR);
212                                         dest = concat_path_file(alias, device_name);
213                                         free(alias);
214                                 } else
215                                         dest = alias;
216
217                                 rename(device_name, dest);
218                                 symlink(dest, device_name);
219
220                                 free(dest);
221                         }
222                 }
223         }
224
225         if (ENABLE_FEATURE_MDEV_EXEC && command) {
226                 /* setenv will leak memory, use putenv/unsetenv/free */
227                 char *s = xasprintf("MDEV=%s", device_name);
228                 putenv(s);
229                 if (system(command) == -1)
230                         bb_perror_msg_and_die("can't run '%s'", command);
231                 s[4] = '\0';
232                 unsetenv(s);
233                 free(s);
234                 free(command);
235         }
236
237         if (delete)
238                 unlink(device_name);
239 }
240
241 /* File callback for /sys/ traversal */
242 static int fileAction(const char *fileName,
243                       struct stat *statbuf ATTRIBUTE_UNUSED,
244                       void *userData,
245                       int depth ATTRIBUTE_UNUSED)
246 {
247         size_t len = strlen(fileName) - 4; /* can't underflow */
248         char *scratch = userData;
249
250         /* len check is for paranoid reasons */
251         if (strcmp(fileName + len, "/dev") || len >= PATH_MAX)
252                 return FALSE;
253
254         strcpy(scratch, fileName);
255         scratch[len] = '\0';
256         make_device(scratch, 0);
257
258         return TRUE;
259 }
260
261 /* Directory callback for /sys/ traversal */
262 static int dirAction(const char *fileName ATTRIBUTE_UNUSED,
263                       struct stat *statbuf ATTRIBUTE_UNUSED,
264                       void *userData ATTRIBUTE_UNUSED,
265                       int depth)
266 {
267         return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
268 }
269
270 /* For the full gory details, see linux/Documentation/firmware_class/README
271  *
272  * Firmware loading works like this:
273  * - kernel sets FIRMWARE env var
274  * - userspace checks /lib/firmware/$FIRMWARE
275  * - userspace waits for /sys/$DEVPATH/loading to appear
276  * - userspace writes "1" to /sys/$DEVPATH/loading
277  * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
278  * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
279  * - kernel loads firmware into device
280  */
281 static void load_firmware(const char *const firmware, const char *const sysfs_path)
282 {
283         int cnt;
284         int firmware_fd, loading_fd, data_fd;
285
286         /* check for /lib/firmware/$FIRMWARE */
287         xchdir("/lib/firmware");
288         firmware_fd = xopen(firmware, O_RDONLY);
289
290         /* in case we goto out ... */
291         data_fd = -1;
292
293         /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
294         xchdir(sysfs_path);
295         for (cnt = 0; cnt < 30; ++cnt) {
296                 loading_fd = open("loading", O_WRONLY);
297                 if (loading_fd != -1)
298                         goto loading;
299                 sleep(1);
300         }
301         goto out;
302
303  loading:
304         /* tell kernel we're loading by `echo 1 > /sys/$DEVPATH/loading` */
305         if (full_write(loading_fd, "1", 1) != 1)
306                 goto out;
307
308         /* load firmware by `cat /lib/firmware/$FIRMWARE > /sys/$DEVPATH/data */
309         data_fd = open("data", O_WRONLY);
310         if (data_fd == -1)
311                 goto out;
312         cnt = bb_copyfd_eof(firmware_fd, data_fd);
313
314         /* tell kernel result by `echo [0|-1] > /sys/$DEVPATH/loading` */
315         if (cnt > 0)
316                 full_write(loading_fd, "0", 1);
317         else
318                 full_write(loading_fd, "-1", 2);
319
320  out:
321         if (ENABLE_FEATURE_CLEAN_UP) {
322                 close(firmware_fd);
323                 close(loading_fd);
324                 close(data_fd);
325         }
326 }
327
328 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
329 int mdev_main(int argc, char **argv)
330 {
331         char *action;
332         char *env_path;
333         RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
334
335         xchdir("/dev");
336
337         if (argc == 2 && !strcmp(argv[1], "-s")) {
338                 /* Scan:
339                  * mdev -s
340                  */
341                 struct stat st;
342
343                 xstat("/", &st);
344                 root_major = major(st.st_dev);
345                 root_minor = minor(st.st_dev);
346
347                 recursive_action("/sys/block",
348                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
349                         fileAction, dirAction, temp, 0);
350
351                 recursive_action("/sys/class",
352                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
353                         fileAction, dirAction, temp, 0);
354
355         } else {
356                 /* Hotplug:
357                  * env ACTION=... DEVPATH=... mdev
358                  * ACTION can be "add" or "remove"
359                  * DEVPATH is like "/block/sda" or "/class/input/mice"
360                  */
361                 action = getenv("ACTION");
362                 env_path = getenv("DEVPATH");
363                 if (!action || !env_path)
364                         bb_show_usage();
365
366                 snprintf(temp, PATH_MAX, "/sys%s", env_path);
367                 if (!strcmp(action, "remove"))
368                         make_device(temp, 1);
369                 else if (!strcmp(action, "add")) {
370                         make_device(temp, 0);
371
372                         if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
373                                 char *fw = getenv("FIRMWARE");
374                                 if (fw)
375                                         load_firmware(fw, temp);
376                         }
377                 }
378         }
379
380         if (ENABLE_FEATURE_CLEAN_UP)
381                 RELEASE_CONFIG_BUFFER(temp);
382
383         return 0;
384 }