mdev: add a comment. no code changes
[platform/upstream/busybox.git] / util-linux / mdev.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * mdev - Mini udev for busybox
4  *
5  * Copyright 2005 Rob Landley <rob@landley.net>
6  * Copyright 2005 Frank Sorenson <frank@tuxrocks.com>
7  *
8  * Licensed under GPLv2, see file LICENSE in this source tree.
9  */
10
11 //config:config MDEV
12 //config:       bool "mdev"
13 //config:       default y
14 //config:       select PLATFORM_LINUX
15 //config:       help
16 //config:         mdev is a mini-udev implementation for dynamically creating device
17 //config:         nodes in the /dev directory.
18 //config:
19 //config:         For more information, please see docs/mdev.txt
20 //config:
21 //config:config FEATURE_MDEV_CONF
22 //config:       bool "Support /etc/mdev.conf"
23 //config:       default y
24 //config:       depends on MDEV
25 //config:       help
26 //config:         Add support for the mdev config file to control ownership and
27 //config:         permissions of the device nodes.
28 //config:
29 //config:         For more information, please see docs/mdev.txt
30 //config:
31 //config:config FEATURE_MDEV_RENAME
32 //config:       bool "Support subdirs/symlinks"
33 //config:       default y
34 //config:       depends on FEATURE_MDEV_CONF
35 //config:       help
36 //config:         Add support for renaming devices and creating symlinks.
37 //config:
38 //config:         For more information, please see docs/mdev.txt
39 //config:
40 //config:config FEATURE_MDEV_RENAME_REGEXP
41 //config:       bool "Support regular expressions substitutions when renaming device"
42 //config:       default y
43 //config:       depends on FEATURE_MDEV_RENAME
44 //config:       help
45 //config:         Add support for regular expressions substitutions when renaming
46 //config:         device.
47 //config:
48 //config:config FEATURE_MDEV_EXEC
49 //config:       bool "Support command execution at device addition/removal"
50 //config:       default y
51 //config:       depends on FEATURE_MDEV_CONF
52 //config:       help
53 //config:         This adds support for an optional field to /etc/mdev.conf for
54 //config:         executing commands when devices are created/removed.
55 //config:
56 //config:         For more information, please see docs/mdev.txt
57 //config:
58 //config:config FEATURE_MDEV_LOAD_FIRMWARE
59 //config:       bool "Support loading of firmwares"
60 //config:       default y
61 //config:       depends on MDEV
62 //config:       help
63 //config:         Some devices need to load firmware before they can be usable.
64 //config:
65 //config:         These devices will request userspace look up the files in
66 //config:         /lib/firmware/ and if it exists, send it to the kernel for
67 //config:         loading into the hardware.
68
69 //applet:IF_MDEV(APPLET(mdev, BB_DIR_SBIN, BB_SUID_DROP))
70
71 //kbuild:lib-$(CONFIG_MDEV) += mdev.o
72
73 //usage:#define mdev_trivial_usage
74 //usage:       "[-s]"
75 //usage:#define mdev_full_usage "\n\n"
76 //usage:       "mdev -s is to be run during boot to scan /sys and populate /dev.\n"
77 //usage:       "\n"
78 //usage:       "Bare mdev is a kernel hotplug helper. To activate it:\n"
79 //usage:       "        echo /sbin/mdev >/proc/sys/kernel/hotplug\n"
80 //usage:        IF_FEATURE_MDEV_CONF(
81 //usage:       "\n"
82 //usage:       "It uses /etc/mdev.conf with lines\n"
83 //usage:       "        [-]DEVNAME UID:GID PERM"
84 //usage:                        IF_FEATURE_MDEV_RENAME(" [>|=PATH]|[!]")
85 //usage:                        IF_FEATURE_MDEV_EXEC(" [@|$|*PROG]")
86 //usage:       "\n"
87 //usage:       "where DEVNAME is device name regex, @major,minor[-minor2], or\n"
88 //usage:       "environment variable regex. A common use of the latter is\n"
89 //usage:       "to load modules for hotplugged devices:\n"
90 //usage:       "        $MODALIAS=.* 0:0 660 @modprobe \"$MODALIAS\"\n"
91 //usage:        )
92 //usage:       "\n"
93 //usage:       "If /dev/mdev.seq file exists, mdev will wait for its value\n"
94 //usage:       "to match $SEQNUM variable. This prevents plug/unplug races.\n"
95 //usage:       "To activate this feature, create empty /dev/mdev.seq at boot."
96
97 #include "libbb.h"
98 #include "xregex.h"
99
100 /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
101  * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
102  * contains "4:0\n". Directory name is taken as device name, path component
103  * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
104  * Then mdev creates the /dev/device_name node.
105  * If /sys/class/.../dev file does not exist, mdev still may act
106  * on this device: see "@|$|*command args..." parameter in config file.
107  *
108  * mdev w/o parameters is called as hotplug helper. It takes device
109  * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
110  * maj,min from "/sys/$DEVPATH/dev" and also examines
111  * $ACTION ("add"/"delete") and $FIRMWARE.
112  *
113  * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
114  * (todo: explain "delete" and $FIRMWARE)
115  *
116  * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
117  *
118  * Leading minus in 1st field means "don't stop on this line", otherwise
119  * search is stopped after the matching line is encountered.
120  *
121  * $envvar=regex format is useful for loading modules for hot-plugged devices
122  * which do not have driver loaded yet. In this case /sys/class/.../dev
123  * does not exist, but $MODALIAS is set to needed module's name
124  * (actually, an alias to it) by kernel. This rule instructs mdev
125  * to load the module and exit:
126  *    $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
127  * The kernel will generate another hotplug event when /sys/class/.../dev
128  * file appears.
129  *
130  * When line matches, the device node is created, chmod'ed and chown'ed,
131  * moved to path, and if >path, a symlink to moved node is created,
132  * all this if /sys/class/.../dev exists.
133  *    Examples:
134  *    =loop/      - moves to /dev/loop
135  *    >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
136  *
137  * Then "command args..." is executed (via sh -c 'command args...').
138  * @:execute on creation, $:on deletion, *:on both.
139  * This happens regardless of /sys/class/.../dev existence.
140  */
141
142 struct rule {
143         bool keep_matching;
144         bool regex_compiled;
145         bool regex_has_slash;
146         mode_t mode;
147         int maj, min0, min1;
148         struct bb_uidgid_t ugid;
149         char *envvar;
150         char *ren_mov;
151         IF_FEATURE_MDEV_EXEC(char *r_cmd;)
152         regex_t match;
153 };
154
155 struct globals {
156         int root_major, root_minor;
157         char *subsystem;
158 #if ENABLE_FEATURE_MDEV_CONF
159         const char *filename;
160         parser_t *parser;
161         struct rule **rule_vec;
162         unsigned rule_idx;
163 #endif
164         struct rule cur_rule;
165 } FIX_ALIASING;
166 #define G (*(struct globals*)&bb_common_bufsiz1)
167 #define INIT_G() do { } while (0)
168
169
170 /* Prevent infinite loops in /sys symlinks */
171 #define MAX_SYSFS_DEPTH 3
172
173 /* We use additional 64+ bytes in make_device() */
174 #define SCRATCH_SIZE 80
175
176 #if 0
177 # define dbg(...) bb_error_msg(__VA_ARGS__)
178 #else
179 # define dbg(...) ((void)0)
180 #endif
181
182
183 #if ENABLE_FEATURE_MDEV_CONF
184
185 static void make_default_cur_rule(void)
186 {
187         memset(&G.cur_rule, 0, sizeof(G.cur_rule));
188         G.cur_rule.maj = -1; /* "not a @major,minor rule" */
189         G.cur_rule.mode = 0660;
190 }
191
192 static void clean_up_cur_rule(void)
193 {
194         free(G.cur_rule.envvar);
195         if (G.cur_rule.regex_compiled)
196                 regfree(&G.cur_rule.match);
197         free(G.cur_rule.ren_mov);
198         IF_FEATURE_MDEV_EXEC(free(G.cur_rule.r_cmd);)
199         make_default_cur_rule();
200 }
201
202 static void parse_next_rule(void)
203 {
204         /* Note: on entry, G.cur_rule is set to default */
205         while (1) {
206                 char *tokens[4];
207                 char *val;
208
209                 /* No PARSE_EOL_COMMENTS, because command may contain '#' chars */
210                 if (!config_read(G.parser, tokens, 4, 3, "# \t", PARSE_NORMAL & ~PARSE_EOL_COMMENTS))
211                         break;
212
213                 /* Fields: [-]regex uid:gid mode [alias] [cmd] */
214                 dbg("token1:'%s'", tokens[1]);
215
216                 /* 1st field */
217                 val = tokens[0];
218                 G.cur_rule.keep_matching = ('-' == val[0]);
219                 val += G.cur_rule.keep_matching; /* swallow leading dash */
220                 if (val[0] == '@') {
221                         /* @major,minor[-minor2] */
222                         /* (useful when name is ambiguous:
223                          * "/sys/class/usb/lp0" and
224                          * "/sys/class/printer/lp0")
225                          */
226                         int sc = sscanf(val, "@%u,%u-%u", &G.cur_rule.maj, &G.cur_rule.min0, &G.cur_rule.min1);
227                         if (sc < 2 || G.cur_rule.maj < 0) {
228                                 bb_error_msg("bad @maj,min on line %d", G.parser->lineno);
229                                 goto next_rule;
230                         }
231                         if (sc == 2)
232                                 G.cur_rule.min1 = G.cur_rule.min0;
233                 } else {
234                         if (val[0] == '$') {
235                                 char *eq = strchr(++val, '=');
236                                 if (!eq) {
237                                         bb_error_msg("bad $envvar=regex on line %d", G.parser->lineno);
238                                         goto next_rule;
239                                 }
240                                 G.cur_rule.envvar = xstrndup(val, eq - val);
241                                 val = eq + 1;
242                         }
243                         xregcomp(&G.cur_rule.match, val, REG_EXTENDED);
244                         G.cur_rule.regex_compiled = 1;
245                         G.cur_rule.regex_has_slash = (strchr(val, '/') != NULL);
246                 }
247
248                 /* 2nd field: uid:gid - device ownership */
249                 if (get_uidgid(&G.cur_rule.ugid, tokens[1], /*allow_numeric:*/ 1) == 0) {
250                         bb_error_msg("unknown user/group '%s' on line %d", tokens[1], G.parser->lineno);
251                         goto next_rule;
252                 }
253
254                 /* 3rd field: mode - device permissions */
255                 bb_parse_mode(tokens[2], &G.cur_rule.mode);
256
257                 /* 4th field (opt): ">|=alias" or "!" to not create the node */
258                 val = tokens[3];
259                 if (ENABLE_FEATURE_MDEV_RENAME && val && strchr(">=!", val[0])) {
260                         char *s = skip_non_whitespace(val);
261                         G.cur_rule.ren_mov = xstrndup(val, s - val);
262                         val = skip_whitespace(s);
263                 }
264
265                 if (ENABLE_FEATURE_MDEV_EXEC && val && val[0]) {
266                         const char *s = "$@*";
267                         const char *s2 = strchr(s, val[0]);
268                         if (!s2) {
269                                 bb_error_msg("bad line %u", G.parser->lineno);
270                                 goto next_rule;
271                         }
272                         IF_FEATURE_MDEV_EXEC(G.cur_rule.r_cmd = xstrdup(val);)
273                 }
274
275                 return;
276  next_rule:
277                 clean_up_cur_rule();
278         } /* while (config_read) */
279
280         dbg("config_close(G.parser)");
281         config_close(G.parser);
282         G.parser = NULL;
283
284         return;
285 }
286
287 /* If mdev -s, we remember rules in G.rule_vec[].
288  * Otherwise, there is no point in doing it, and we just
289  * save only one parsed rule in G.cur_rule.
290  */
291 static const struct rule *next_rule(void)
292 {
293         struct rule *rule;
294
295         /* Open conf file if we didn't do it yet */
296         if (!G.parser && G.filename) {
297                 dbg("config_open('%s')", G.filename);
298                 G.parser = config_open2(G.filename, fopen_for_read);
299                 G.filename = NULL;
300         }
301
302         if (G.rule_vec) {
303                 /* mdev -s */
304                 /* Do we have rule parsed already? */
305                 if (G.rule_vec[G.rule_idx]) {
306                         dbg("< G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
307                         return G.rule_vec[G.rule_idx++];
308                 }
309                 make_default_cur_rule();
310         } else {
311                 /* not mdev -s */
312                 clean_up_cur_rule();
313         }
314
315         /* Parse one more rule if file isn't fully read */
316         rule = &G.cur_rule;
317         if (G.parser) {
318                 parse_next_rule();
319                 if (G.rule_vec) { /* mdev -s */
320                         rule = memcpy(xmalloc(sizeof(G.cur_rule)), &G.cur_rule, sizeof(G.cur_rule));
321                         G.rule_vec = xrealloc_vector(G.rule_vec, 4, G.rule_idx);
322                         G.rule_vec[G.rule_idx++] = rule;
323                         dbg("> G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
324                 }
325         }
326
327         return rule;
328 }
329
330 #else
331
332 # define next_rule() (&G.cur_rule)
333
334 #endif
335
336 /* Builds an alias path.
337  * This function potentionally reallocates the alias parameter.
338  * Only used for ENABLE_FEATURE_MDEV_RENAME
339  */
340 static char *build_alias(char *alias, const char *device_name)
341 {
342         char *dest;
343
344         /* ">bar/": rename to bar/device_name */
345         /* ">bar[/]baz": rename to bar[/]baz */
346         dest = strrchr(alias, '/');
347         if (dest) { /* ">bar/[baz]" ? */
348                 *dest = '\0'; /* mkdir bar */
349                 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
350                 *dest = '/';
351                 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
352                         dest = alias;
353                         alias = concat_path_file(alias, device_name);
354                         free(dest);
355                 }
356         }
357
358         return alias;
359 }
360
361 /* mknod in /dev based on a path like "/sys/block/hda/hda1"
362  * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
363  * after NUL, but we promise to not mangle (IOW: to restore if needed)
364  * path string.
365  * NB2: "mdev -s" may call us many times, do not leak memory/fds!
366  */
367 static void make_device(char *path, int delete)
368 {
369         char *device_name, *subsystem_slash_devname;
370         int major, minor, type, len;
371
372         dbg("%s('%s', delete:%d)", __func__, path, delete);
373
374         /* Try to read major/minor string.  Note that the kernel puts \n after
375          * the data, so we don't need to worry about null terminating the string
376          * because sscanf() will stop at the first nondigit, which \n is.
377          * We also depend on path having writeable space after it.
378          */
379         major = -1;
380         if (!delete) {
381                 char *dev_maj_min = path + strlen(path);
382
383                 strcpy(dev_maj_min, "/dev");
384                 len = open_read_close(path, dev_maj_min + 1, 64);
385                 *dev_maj_min = '\0';
386                 if (len < 1) {
387                         if (!ENABLE_FEATURE_MDEV_EXEC)
388                                 return;
389                         /* no "dev" file, but we can still run scripts
390                          * based on device name */
391                 } else if (sscanf(++dev_maj_min, "%u:%u", &major, &minor) != 2) {
392                         major = -1;
393                 }
394         }
395         /* else: for delete, -1 still deletes the node, but < -1 suppresses that */
396
397         /* Determine device name, type, major and minor */
398         device_name = (char*) bb_basename(path);
399         /* http://kernel.org/doc/pending/hotplug.txt says that only
400          * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
401          * But since 2.6.25 block devices are also in /sys/class/block.
402          * We use strstr("/block/") to forestall future surprises. */
403         type = S_IFCHR;
404         if (strstr(path, "/block/") || (G.subsystem && strncmp(G.subsystem, "block", 5) == 0))
405                 type = S_IFBLK;
406
407         /* Make path point to "subsystem/device_name" */
408         subsystem_slash_devname = NULL;
409         /* Check for coldplug invocations first */
410         if (strncmp(path, "/sys/block/", 11) == 0) /* legacy case */
411                 path += sizeof("/sys/") - 1;
412         else if (strncmp(path, "/sys/class/", 11) == 0)
413                 path += sizeof("/sys/class/") - 1;
414         else {
415                 /* Example of a hotplug invocation:
416                  * SUBSYSTEM="block"
417                  * DEVPATH="/sys" + "/devices/virtual/mtd/mtd3/mtdblock3"
418                  * ("/sys" is added by mdev_main)
419                  * - path does not contain subsystem
420                  */
421                 subsystem_slash_devname = concat_path_file(G.subsystem, device_name);
422                 path = subsystem_slash_devname;
423         }
424
425 #if ENABLE_FEATURE_MDEV_CONF
426         G.rule_idx = 0; /* restart from the beginning (think mdev -s) */
427 #endif
428         for (;;) {
429                 const char *str_to_match;
430                 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
431                 char *command;
432                 char *alias;
433                 char aliaslink = aliaslink; /* for compiler */
434                 const char *node_name;
435                 const struct rule *rule;
436
437                 str_to_match = "";
438
439                 rule = next_rule();
440
441 #if ENABLE_FEATURE_MDEV_CONF
442                 if (rule->maj >= 0) {  /* @maj,min rule */
443                         if (major != rule->maj)
444                                 continue;
445                         if (minor < rule->min0 || minor > rule->min1)
446                                 continue;
447                         memset(off, 0, sizeof(off));
448                         goto rule_matches;
449                 }
450                 if (rule->envvar) { /* $envvar=regex rule */
451                         str_to_match = getenv(rule->envvar);
452                         dbg("getenv('%s'):'%s'", rule->envvar, str_to_match);
453                         if (!str_to_match)
454                                 continue;
455                 } else {
456                         /* regex to match [subsystem/]device_name */
457                         str_to_match = (rule->regex_has_slash ? path : device_name);
458                 }
459
460                 if (rule->regex_compiled) {
461                         int regex_match = regexec(&rule->match, str_to_match, ARRAY_SIZE(off), off, 0);
462                         dbg("regex_match for '%s':%d", str_to_match, regex_match);
463                         //bb_error_msg("matches:");
464                         //for (int i = 0; i < ARRAY_SIZE(off); i++) {
465                         //      if (off[i].rm_so < 0) continue;
466                         //      bb_error_msg("match %d: '%.*s'\n", i,
467                         //              (int)(off[i].rm_eo - off[i].rm_so),
468                         //              device_name + off[i].rm_so);
469                         //}
470
471                         if (regex_match != 0
472                         /* regexec returns whole pattern as "range" 0 */
473                          || off[0].rm_so != 0
474                          || (int)off[0].rm_eo != (int)strlen(str_to_match)
475                         ) {
476                                 continue; /* this rule doesn't match */
477                         }
478                 }
479                 /* else: it's final implicit "match-all" rule */
480 #endif
481
482  rule_matches:
483                 dbg("rule matched");
484
485                 /* Build alias name */
486                 alias = NULL;
487                 if (ENABLE_FEATURE_MDEV_RENAME && rule->ren_mov) {
488                         aliaslink = rule->ren_mov[0];
489                         if (aliaslink == '!') {
490                                 /* "!": suppress node creation/deletion */
491                                 major = -2;
492                         }
493                         else if (aliaslink == '>' || aliaslink == '=') {
494                                 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
495                                         char *s;
496                                         char *p;
497                                         unsigned n;
498
499                                         /* substitute %1..9 with off[1..9], if any */
500                                         n = 0;
501                                         s = rule->ren_mov;
502                                         while (*s)
503                                                 if (*s++ == '%')
504                                                         n++;
505
506                                         p = alias = xzalloc(strlen(rule->ren_mov) + n * strlen(str_to_match));
507                                         s = rule->ren_mov + 1;
508                                         while (*s) {
509                                                 *p = *s;
510                                                 if ('%' == *s) {
511                                                         unsigned i = (s[1] - '0');
512                                                         if (i <= 9 && off[i].rm_so >= 0) {
513                                                                 n = off[i].rm_eo - off[i].rm_so;
514                                                                 strncpy(p, str_to_match + off[i].rm_so, n);
515                                                                 p += n - 1;
516                                                                 s++;
517                                                         }
518                                                 }
519                                                 p++;
520                                                 s++;
521                                         }
522                                 } else {
523                                         alias = xstrdup(rule->ren_mov + 1);
524                                 }
525                         }
526                 }
527                 dbg("alias:'%s'", alias);
528
529                 command = NULL;
530                 IF_FEATURE_MDEV_EXEC(command = rule->r_cmd;)
531                 if (command) {
532                         const char *s = "$@*";
533                         const char *s2 = strchr(s, command[0]);
534
535                         /* Are we running this command now?
536                          * Run $cmd on delete, @cmd on create, *cmd on both
537                          */
538                         if (s2 - s != delete) {
539                                 /* We are here if: '*',
540                                  * or: '@' and delete = 0,
541                                  * or: '$' and delete = 1
542                                  */
543                                 command++;
544                         } else {
545                                 command = NULL;
546                         }
547                 }
548                 dbg("command:'%s'", command);
549
550                 /* "Execute" the line we found */
551                 node_name = device_name;
552                 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
553                         node_name = alias = build_alias(alias, device_name);
554                         dbg("alias2:'%s'", alias);
555                 }
556
557                 if (!delete && major >= 0) {
558                         dbg("mknod('%s',%o,(%d,%d))", node_name, rule->mode | type, major, minor);
559                         if (mknod(node_name, rule->mode | type, makedev(major, minor)) && errno != EEXIST)
560                                 bb_perror_msg("can't create '%s'", node_name);
561                         if (major == G.root_major && minor == G.root_minor)
562                                 symlink(node_name, "root");
563                         if (ENABLE_FEATURE_MDEV_CONF) {
564                                 chmod(node_name, rule->mode);
565                                 chown(node_name, rule->ugid.uid, rule->ugid.gid);
566                         }
567                         if (ENABLE_FEATURE_MDEV_RENAME && alias) {
568                                 if (aliaslink == '>') {
569 //TODO: on devtmpfs, device_name already exists and symlink() fails.
570 //End result is that instead of symlink, we have two nodes.
571 //What should be done?
572                                         symlink(node_name, device_name);
573                                 }
574                         }
575                 }
576
577                 if (ENABLE_FEATURE_MDEV_EXEC && command) {
578                         /* setenv will leak memory, use putenv/unsetenv/free */
579                         char *s = xasprintf("%s=%s", "MDEV", node_name);
580                         char *s1 = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
581                         putenv(s);
582                         putenv(s1);
583                         if (system(command) == -1)
584                                 bb_perror_msg("can't run '%s'", command);
585                         bb_unsetenv_and_free(s1);
586                         bb_unsetenv_and_free(s);
587                 }
588
589                 if (delete && major >= -1) {
590                         if (ENABLE_FEATURE_MDEV_RENAME && alias) {
591                                 if (aliaslink == '>')
592                                         unlink(device_name);
593                         }
594                         unlink(node_name);
595                 }
596
597                 if (ENABLE_FEATURE_MDEV_RENAME)
598                         free(alias);
599
600                 /* We found matching line.
601                  * Stop unless it was prefixed with '-'
602                  */
603                 if (!ENABLE_FEATURE_MDEV_CONF || !rule->keep_matching)
604                         break;
605         } /* for (;;) */
606
607         free(subsystem_slash_devname);
608 }
609
610 /* File callback for /sys/ traversal */
611 static int FAST_FUNC fileAction(const char *fileName,
612                 struct stat *statbuf UNUSED_PARAM,
613                 void *userData,
614                 int depth UNUSED_PARAM)
615 {
616         size_t len = strlen(fileName) - 4; /* can't underflow */
617         char *scratch = userData;
618
619         /* len check is for paranoid reasons */
620         if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
621                 return FALSE;
622
623         strcpy(scratch, fileName);
624         scratch[len] = '\0';
625         make_device(scratch, /*delete:*/ 0);
626
627         return TRUE;
628 }
629
630 /* Directory callback for /sys/ traversal */
631 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
632                 struct stat *statbuf UNUSED_PARAM,
633                 void *userData UNUSED_PARAM,
634                 int depth)
635 {
636         /* Extract device subsystem -- the name of the directory
637          * under /sys/class/ */
638         if (1 == depth) {
639                 free(G.subsystem);
640                 G.subsystem = strrchr(fileName, '/');
641                 if (G.subsystem)
642                         G.subsystem = xstrdup(G.subsystem + 1);
643         }
644
645         return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
646 }
647
648 /* For the full gory details, see linux/Documentation/firmware_class/README
649  *
650  * Firmware loading works like this:
651  * - kernel sets FIRMWARE env var
652  * - userspace checks /lib/firmware/$FIRMWARE
653  * - userspace waits for /sys/$DEVPATH/loading to appear
654  * - userspace writes "1" to /sys/$DEVPATH/loading
655  * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
656  * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
657  * - kernel loads firmware into device
658  */
659 static void load_firmware(const char *firmware, const char *sysfs_path)
660 {
661         int cnt;
662         int firmware_fd, loading_fd, data_fd;
663
664         /* check for /lib/firmware/$FIRMWARE */
665         xchdir("/lib/firmware");
666         firmware_fd = xopen(firmware, O_RDONLY);
667
668         /* in case we goto out ... */
669         data_fd = -1;
670
671         /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
672         xchdir(sysfs_path);
673         for (cnt = 0; cnt < 30; ++cnt) {
674                 loading_fd = open("loading", O_WRONLY);
675                 if (loading_fd != -1)
676                         goto loading;
677                 sleep(1);
678         }
679         goto out;
680
681  loading:
682         /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
683         if (full_write(loading_fd, "1", 1) != 1)
684                 goto out;
685
686         /* load firmware into /sys/$DEVPATH/data */
687         data_fd = open("data", O_WRONLY);
688         if (data_fd == -1)
689                 goto out;
690         cnt = bb_copyfd_eof(firmware_fd, data_fd);
691
692         /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
693         if (cnt > 0)
694                 full_write(loading_fd, "0", 1);
695         else
696                 full_write(loading_fd, "-1", 2);
697
698  out:
699         if (ENABLE_FEATURE_CLEAN_UP) {
700                 close(firmware_fd);
701                 close(loading_fd);
702                 close(data_fd);
703         }
704 }
705
706 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
707 int mdev_main(int argc UNUSED_PARAM, char **argv)
708 {
709         RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
710
711         INIT_G();
712
713 #if ENABLE_FEATURE_MDEV_CONF
714         G.filename = "/etc/mdev.conf";
715 #endif
716
717         /* We can be called as hotplug helper */
718         /* Kernel cannot provide suitable stdio fds for us, do it ourself */
719         bb_sanitize_stdio();
720
721         /* Force the configuration file settings exactly */
722         umask(0);
723
724         xchdir("/dev");
725
726         if (argv[1] && strcmp(argv[1], "-s") == 0) {
727                 /* Scan:
728                  * mdev -s
729                  */
730                 struct stat st;
731
732 #if ENABLE_FEATURE_MDEV_CONF
733                 /* Same as xrealloc_vector(NULL, 4, 0): */
734                 G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
735 #endif
736                 xstat("/", &st);
737                 G.root_major = major(st.st_dev);
738                 G.root_minor = minor(st.st_dev);
739
740                 /* ACTION_FOLLOWLINKS is needed since in newer kernels
741                  * /sys/block/loop* (for example) are symlinks to dirs,
742                  * not real directories.
743                  * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
744                  * but we can't enforce that on users)
745                  */
746                 if (access("/sys/class/block", F_OK) != 0) {
747                         /* Scan obsolete /sys/block only if /sys/class/block
748                          * doesn't exist. Otherwise we'll have dupes.
749                          * Also, do not complain if it doesn't exist.
750                          * Some people configure kernel to have no blockdevs.
751                          */
752                         recursive_action("/sys/block",
753                                 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
754                                 fileAction, dirAction, temp, 0);
755                 }
756                 recursive_action("/sys/class",
757                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
758                         fileAction, dirAction, temp, 0);
759         } else {
760                 char *fw;
761                 char *seq;
762                 char *action;
763                 char *env_path;
764                 static const char keywords[] ALIGN1 = "remove\0add\0";
765                 enum { OP_remove = 0, OP_add };
766                 smalluint op;
767
768                 /* Hotplug:
769                  * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
770                  * ACTION can be "add" or "remove"
771                  * DEVPATH is like "/block/sda" or "/class/input/mice"
772                  */
773                 action = getenv("ACTION");
774                 env_path = getenv("DEVPATH");
775                 G.subsystem = getenv("SUBSYSTEM");
776                 if (!action || !env_path /*|| !G.subsystem*/)
777                         bb_show_usage();
778                 fw = getenv("FIRMWARE");
779                 op = index_in_strings(keywords, action);
780                 /* If it exists, does /dev/mdev.seq match $SEQNUM?
781                  * If it does not match, earlier mdev is running
782                  * in parallel, and we need to wait */
783                 seq = getenv("SEQNUM");
784                 if (seq) {
785                         int timeout = 2000 / 32; /* 2000 msec */
786                         do {
787                                 int seqlen;
788                                 char seqbuf[sizeof(int)*3 + 2];
789
790                                 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf) - 1);
791                                 if (seqlen < 0) {
792                                         seq = NULL;
793                                         break;
794                                 }
795                                 seqbuf[seqlen] = '\0';
796                                 if (seqbuf[0] == '\n' /* seed file? */
797                                  || strcmp(seq, seqbuf) == 0 /* correct idx? */
798                                 ) {
799                                         break;
800                                 }
801                                 usleep(32*1000);
802                         } while (--timeout);
803                 }
804
805                 snprintf(temp, PATH_MAX, "/sys%s", env_path);
806                 if (op == OP_remove) {
807                         /* Ignoring "remove firmware". It was reported
808                          * to happen and to cause erroneous deletion
809                          * of device nodes. */
810                         if (!fw)
811                                 make_device(temp, /*delete:*/ 1);
812                 }
813                 else if (op == OP_add) {
814                         make_device(temp, /*delete:*/ 0);
815                         if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
816                                 if (fw)
817                                         load_firmware(fw, temp);
818                         }
819                 }
820
821                 if (seq) {
822                         xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
823                 }
824         }
825
826         if (ENABLE_FEATURE_CLEAN_UP)
827                 RELEASE_CONFIG_BUFFER(temp);
828
829         return EXIT_SUCCESS;
830 }