Bump to version 1.22.1
[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:       "        [-][ENV=regex;]...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.\n"
96 //usage:       "\n"
97 //usage:       "If /dev/mdev.log file exists, debug log will be appended to it."
98
99 #include "libbb.h"
100 #include "xregex.h"
101
102 /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
103  * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
104  * contains "4:0\n". Directory name is taken as device name, path component
105  * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
106  * Then mdev creates the /dev/device_name node.
107  * If /sys/class/.../dev file does not exist, mdev still may act
108  * on this device: see "@|$|*command args..." parameter in config file.
109  *
110  * mdev w/o parameters is called as hotplug helper. It takes device
111  * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
112  * maj,min from "/sys/$DEVPATH/dev" and also examines
113  * $ACTION ("add"/"delete") and $FIRMWARE.
114  *
115  * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
116  * (todo: explain "delete" and $FIRMWARE)
117  *
118  * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
119  *
120  * Leading minus in 1st field means "don't stop on this line", otherwise
121  * search is stopped after the matching line is encountered.
122  *
123  * $envvar=regex format is useful for loading modules for hot-plugged devices
124  * which do not have driver loaded yet. In this case /sys/class/.../dev
125  * does not exist, but $MODALIAS is set to needed module's name
126  * (actually, an alias to it) by kernel. This rule instructs mdev
127  * to load the module and exit:
128  *    $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
129  * The kernel will generate another hotplug event when /sys/class/.../dev
130  * file appears.
131  *
132  * When line matches, the device node is created, chmod'ed and chown'ed,
133  * moved to path, and if >path, a symlink to moved node is created,
134  * all this if /sys/class/.../dev exists.
135  *    Examples:
136  *    =loop/      - moves to /dev/loop
137  *    >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
138  *
139  * Then "command args..." is executed (via sh -c 'command args...').
140  * @:execute on creation, $:on deletion, *:on both.
141  * This happens regardless of /sys/class/.../dev existence.
142  */
143
144 /* Kernel's hotplug environment constantly changes.
145  * Here are new cases I observed on 3.1.0:
146  *
147  * Case with $DEVNAME and $DEVICE, not just $DEVPATH:
148  * ACTION=add
149  * BUSNUM=001
150  * DEVICE=/proc/bus/usb/001/003
151  * DEVNAME=bus/usb/001/003
152  * DEVNUM=003
153  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5
154  * DEVTYPE=usb_device
155  * MAJOR=189
156  * MINOR=2
157  * PRODUCT=18d1/4e12/227
158  * SUBSYSTEM=usb
159  * TYPE=0/0/0
160  *
161  * Case with $DEVICE, but no $DEVNAME - apparenty, usb iface notification?
162  * "Please load me a module" thing?
163  * ACTION=add
164  * DEVICE=/proc/bus/usb/001/003
165  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0
166  * DEVTYPE=usb_interface
167  * INTERFACE=8/6/80
168  * MODALIAS=usb:v18D1p4E12d0227dc00dsc00dp00ic08isc06ip50
169  * PRODUCT=18d1/4e12/227
170  * SUBSYSTEM=usb
171  * TYPE=0/0/0
172  *
173  * ACTION=add
174  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5
175  * DEVTYPE=scsi_host
176  * SUBSYSTEM=scsi
177  *
178  * ACTION=add
179  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/scsi_host/host5
180  * SUBSYSTEM=scsi_host
181  *
182  * ACTION=add
183  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0
184  * DEVTYPE=scsi_target
185  * SUBSYSTEM=scsi
186  *
187  * Case with strange $MODALIAS:
188  * ACTION=add
189  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0
190  * DEVTYPE=scsi_device
191  * MODALIAS=scsi:t-0x00
192  * SUBSYSTEM=scsi
193  *
194  * ACTION=add
195  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/scsi_disk/5:0:0:0
196  * SUBSYSTEM=scsi_disk
197  *
198  * ACTION=add
199  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/scsi_device/5:0:0:0
200  * SUBSYSTEM=scsi_device
201  *
202  * Case with explicit $MAJOR/$MINOR (no need to read /sys/$DEVPATH/dev?):
203  * ACTION=add
204  * DEVNAME=bsg/5:0:0:0
205  * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/bsg/5:0:0:0
206  * MAJOR=253
207  * MINOR=1
208  * SUBSYSTEM=bsg
209  *
210  * ACTION=add
211  * DEVPATH=/devices/virtual/bdi/8:16
212  * SUBSYSTEM=bdi
213  *
214  * ACTION=add
215  * DEVNAME=sdb
216  * DEVPATH=/block/sdb
217  * DEVTYPE=disk
218  * MAJOR=8
219  * MINOR=16
220  * SUBSYSTEM=block
221  *
222  * Case with ACTION=change:
223  * ACTION=change
224  * DEVNAME=sdb
225  * DEVPATH=/block/sdb
226  * DEVTYPE=disk
227  * DISK_MEDIA_CHANGE=1
228  * MAJOR=8
229  * MINOR=16
230  * SUBSYSTEM=block
231  */
232
233 #define DEBUG_LVL 2
234
235 #if DEBUG_LVL >= 1
236 # define dbg1(...) do { if (G.verbose) bb_error_msg(__VA_ARGS__); } while(0)
237 #else
238 # define dbg1(...) ((void)0)
239 #endif
240 #if DEBUG_LVL >= 2
241 # define dbg2(...) do { if (G.verbose >= 2) bb_error_msg(__VA_ARGS__); } while(0)
242 #else
243 # define dbg2(...) ((void)0)
244 #endif
245 #if DEBUG_LVL >= 3
246 # define dbg3(...) do { if (G.verbose >= 3) bb_error_msg(__VA_ARGS__); } while(0)
247 #else
248 # define dbg3(...) ((void)0)
249 #endif
250
251
252 static const char keywords[] ALIGN1 = "add\0remove\0"; // "change\0"
253 enum { OP_add, OP_remove };
254
255 struct envmatch {
256         struct envmatch *next;
257         char *envname;
258         regex_t match;
259 };
260
261 struct rule {
262         bool keep_matching;
263         bool regex_compiled;
264         mode_t mode;
265         int maj, min0, min1;
266         struct bb_uidgid_t ugid;
267         char *envvar;
268         char *ren_mov;
269         IF_FEATURE_MDEV_EXEC(char *r_cmd;)
270         regex_t match;
271         struct envmatch *envmatch;
272 };
273
274 struct globals {
275         int root_major, root_minor;
276         smallint verbose;
277         char *subsystem;
278         char *subsys_env; /* for putenv("SUBSYSTEM=subsystem") */
279 #if ENABLE_FEATURE_MDEV_CONF
280         const char *filename;
281         parser_t *parser;
282         struct rule **rule_vec;
283         unsigned rule_idx;
284 #endif
285         struct rule cur_rule;
286         char timestr[sizeof("60.123456")];
287 } FIX_ALIASING;
288 #define G (*(struct globals*)&bb_common_bufsiz1)
289 #define INIT_G() do { \
290         IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.maj = -1;) \
291         IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.mode = 0660;) \
292 } while (0)
293
294
295 /* Prevent infinite loops in /sys symlinks */
296 #define MAX_SYSFS_DEPTH 3
297
298 /* We use additional bytes in make_device() */
299 #define SCRATCH_SIZE 128
300
301 #if ENABLE_FEATURE_MDEV_CONF
302
303 static void make_default_cur_rule(void)
304 {
305         memset(&G.cur_rule, 0, sizeof(G.cur_rule));
306         G.cur_rule.maj = -1; /* "not a @major,minor rule" */
307         G.cur_rule.mode = 0660;
308 }
309
310 static void clean_up_cur_rule(void)
311 {
312         struct envmatch *e;
313
314         free(G.cur_rule.envvar);
315         free(G.cur_rule.ren_mov);
316         if (G.cur_rule.regex_compiled)
317                 regfree(&G.cur_rule.match);
318         IF_FEATURE_MDEV_EXEC(free(G.cur_rule.r_cmd);)
319         e = G.cur_rule.envmatch;
320         while (e) {
321                 free(e->envname);
322                 regfree(&e->match);
323                 e = e->next;
324         }
325         make_default_cur_rule();
326 }
327
328 static char *parse_envmatch_pfx(char *val)
329 {
330         struct envmatch **nextp = &G.cur_rule.envmatch;
331
332         for (;;) {
333                 struct envmatch *e;
334                 char *semicolon;
335                 char *eq = strchr(val, '=');
336                 if (!eq /* || eq == val? */)
337                         return val;
338                 if (endofname(val) != eq)
339                         return val;
340                 semicolon = strchr(eq, ';');
341                 if (!semicolon)
342                         return val;
343                 /* ENVVAR=regex;... */
344                 *nextp = e = xzalloc(sizeof(*e));
345                 nextp = &e->next;
346                 e->envname = xstrndup(val, eq - val);
347                 *semicolon = '\0';
348                 xregcomp(&e->match, eq + 1, REG_EXTENDED);
349                 *semicolon = ';';
350                 val = semicolon + 1;
351         }
352 }
353
354 static void parse_next_rule(void)
355 {
356         /* Note: on entry, G.cur_rule is set to default */
357         while (1) {
358                 char *tokens[4];
359                 char *val;
360
361                 /* No PARSE_EOL_COMMENTS, because command may contain '#' chars */
362                 if (!config_read(G.parser, tokens, 4, 3, "# \t", PARSE_NORMAL & ~PARSE_EOL_COMMENTS))
363                         break;
364
365                 /* Fields: [-]regex uid:gid mode [alias] [cmd] */
366                 dbg3("token1:'%s'", tokens[1]);
367
368                 /* 1st field */
369                 val = tokens[0];
370                 G.cur_rule.keep_matching = ('-' == val[0]);
371                 val += G.cur_rule.keep_matching; /* swallow leading dash */
372                 val = parse_envmatch_pfx(val);
373                 if (val[0] == '@') {
374                         /* @major,minor[-minor2] */
375                         /* (useful when name is ambiguous:
376                          * "/sys/class/usb/lp0" and
377                          * "/sys/class/printer/lp0")
378                          */
379                         int sc = sscanf(val, "@%u,%u-%u", &G.cur_rule.maj, &G.cur_rule.min0, &G.cur_rule.min1);
380                         if (sc < 2 || G.cur_rule.maj < 0) {
381                                 bb_error_msg("bad @maj,min on line %d", G.parser->lineno);
382                                 goto next_rule;
383                         }
384                         if (sc == 2)
385                                 G.cur_rule.min1 = G.cur_rule.min0;
386                 } else {
387                         char *eq = strchr(val, '=');
388                         if (val[0] == '$') {
389                                 /* $ENVVAR=regex ... */
390                                 val++;
391                                 if (!eq) {
392                                         bb_error_msg("bad $envvar=regex on line %d", G.parser->lineno);
393                                         goto next_rule;
394                                 }
395                                 G.cur_rule.envvar = xstrndup(val, eq - val);
396                                 val = eq + 1;
397                         }
398                         xregcomp(&G.cur_rule.match, val, REG_EXTENDED);
399                         G.cur_rule.regex_compiled = 1;
400                 }
401
402                 /* 2nd field: uid:gid - device ownership */
403                 if (get_uidgid(&G.cur_rule.ugid, tokens[1], /*allow_numeric:*/ 1) == 0) {
404                         bb_error_msg("unknown user/group '%s' on line %d", tokens[1], G.parser->lineno);
405                         goto next_rule;
406                 }
407
408                 /* 3rd field: mode - device permissions */
409                 bb_parse_mode(tokens[2], &G.cur_rule.mode);
410
411                 /* 4th field (opt): ">|=alias" or "!" to not create the node */
412                 val = tokens[3];
413                 if (ENABLE_FEATURE_MDEV_RENAME && val && strchr(">=!", val[0])) {
414                         char *s = skip_non_whitespace(val);
415                         G.cur_rule.ren_mov = xstrndup(val, s - val);
416                         val = skip_whitespace(s);
417                 }
418
419                 if (ENABLE_FEATURE_MDEV_EXEC && val && val[0]) {
420                         const char *s = "$@*";
421                         const char *s2 = strchr(s, val[0]);
422                         if (!s2) {
423                                 bb_error_msg("bad line %u", G.parser->lineno);
424                                 goto next_rule;
425                         }
426                         IF_FEATURE_MDEV_EXEC(G.cur_rule.r_cmd = xstrdup(val);)
427                 }
428
429                 return;
430  next_rule:
431                 clean_up_cur_rule();
432         } /* while (config_read) */
433
434         dbg3("config_close(G.parser)");
435         config_close(G.parser);
436         G.parser = NULL;
437
438         return;
439 }
440
441 /* If mdev -s, we remember rules in G.rule_vec[].
442  * Otherwise, there is no point in doing it, and we just
443  * save only one parsed rule in G.cur_rule.
444  */
445 static const struct rule *next_rule(void)
446 {
447         struct rule *rule;
448
449         /* Open conf file if we didn't do it yet */
450         if (!G.parser && G.filename) {
451                 dbg3("config_open('%s')", G.filename);
452                 G.parser = config_open2(G.filename, fopen_for_read);
453                 G.filename = NULL;
454         }
455
456         if (G.rule_vec) {
457                 /* mdev -s */
458                 /* Do we have rule parsed already? */
459                 if (G.rule_vec[G.rule_idx]) {
460                         dbg3("< G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
461                         return G.rule_vec[G.rule_idx++];
462                 }
463                 make_default_cur_rule();
464         } else {
465                 /* not mdev -s */
466                 clean_up_cur_rule();
467         }
468
469         /* Parse one more rule if file isn't fully read */
470         rule = &G.cur_rule;
471         if (G.parser) {
472                 parse_next_rule();
473                 if (G.rule_vec) { /* mdev -s */
474                         rule = memcpy(xmalloc(sizeof(G.cur_rule)), &G.cur_rule, sizeof(G.cur_rule));
475                         G.rule_vec = xrealloc_vector(G.rule_vec, 4, G.rule_idx);
476                         G.rule_vec[G.rule_idx++] = rule;
477                         dbg3("> G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
478                 }
479         }
480
481         return rule;
482 }
483
484 static int env_matches(struct envmatch *e)
485 {
486         while (e) {
487                 int r;
488                 char *val = getenv(e->envname);
489                 if (!val)
490                         return 0;
491                 r = regexec(&e->match, val, /*size*/ 0, /*range[]*/ NULL, /*eflags*/ 0);
492                 if (r != 0) /* no match */
493                         return 0;
494                 e = e->next;
495         }
496         return 1;
497 }
498
499 #else
500
501 # define next_rule() (&G.cur_rule)
502
503 #endif
504
505 static void mkdir_recursive(char *name)
506 {
507         /* if name has many levels ("dir1/dir2"),
508          * bb_make_directory() will create dir1 according to umask,
509          * not according to its "mode" parameter.
510          * Since we run with umask=0, need to temporarily switch it.
511          */
512         umask(022); /* "dir1" (if any) will be 0755 too */
513         bb_make_directory(name, 0755, FILEUTILS_RECUR);
514         umask(0);
515 }
516
517 /* Builds an alias path.
518  * This function potentionally reallocates the alias parameter.
519  * Only used for ENABLE_FEATURE_MDEV_RENAME
520  */
521 static char *build_alias(char *alias, const char *device_name)
522 {
523         char *dest;
524
525         /* ">bar/": rename to bar/device_name */
526         /* ">bar[/]baz": rename to bar[/]baz */
527         dest = strrchr(alias, '/');
528         if (dest) { /* ">bar/[baz]" ? */
529                 *dest = '\0'; /* mkdir bar */
530                 mkdir_recursive(alias);
531                 *dest = '/';
532                 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
533                         dest = alias;
534                         alias = concat_path_file(alias, device_name);
535                         free(dest);
536                 }
537         }
538
539         return alias;
540 }
541
542 /* mknod in /dev based on a path like "/sys/block/hda/hda1"
543  * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
544  * after NUL, but we promise to not mangle (IOW: to restore NUL if needed)
545  * path string.
546  * NB2: "mdev -s" may call us many times, do not leak memory/fds!
547  *
548  * device_name = $DEVNAME (may be NULL)
549  * path        = /sys/$DEVPATH
550  */
551 static void make_device(char *device_name, char *path, int operation)
552 {
553         int major, minor, type, len;
554         char *path_end = path + strlen(path);
555
556         /* Try to read major/minor string.  Note that the kernel puts \n after
557          * the data, so we don't need to worry about null terminating the string
558          * because sscanf() will stop at the first nondigit, which \n is.
559          * We also depend on path having writeable space after it.
560          */
561         major = -1;
562         if (operation == OP_add) {
563                 strcpy(path_end, "/dev");
564                 len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
565                 *path_end = '\0';
566                 if (len < 1) {
567                         if (!ENABLE_FEATURE_MDEV_EXEC)
568                                 return;
569                         /* no "dev" file, but we can still run scripts
570                          * based on device name */
571                 } else if (sscanf(path_end + 1, "%u:%u", &major, &minor) == 2) {
572                         dbg1("dev %u,%u", major, minor);
573                 } else {
574                         major = -1;
575                 }
576         }
577         /* else: for delete, -1 still deletes the node, but < -1 suppresses that */
578
579         /* Determine device name */
580         if (!device_name) {
581                 /*
582                  * There was no $DEVNAME envvar (for example, mdev -s never has).
583                  * But it is very useful: it contains the *path*, not only basename,
584                  * Thankfully, uevent file has it.
585                  * Example of .../sound/card0/controlC0/uevent file on Linux-3.7.7:
586                  * MAJOR=116
587                  * MINOR=7
588                  * DEVNAME=snd/controlC0
589                  */
590                 strcpy(path_end, "/uevent");
591                 len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
592                 if (len < 0)
593                         len = 0;
594                 *path_end = '\0';
595                 path_end[1 + len] = '\0';
596                 device_name = strstr(path_end + 1, "\nDEVNAME=");
597                 if (device_name) {
598                         device_name += sizeof("\nDEVNAME=")-1;
599                         strchrnul(device_name, '\n')[0] = '\0';
600                 } else {
601                         /* Fall back to just basename */
602                         device_name = (char*) bb_basename(path);
603                 }
604         }
605         /* Determine device type */
606         /*
607          * http://kernel.org/doc/pending/hotplug.txt says that only
608          * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
609          * But since 2.6.25 block devices are also in /sys/class/block.
610          * We use strstr("/block/") to forestall future surprises.
611          */
612         type = S_IFCHR;
613         if (strstr(path, "/block/") || (G.subsystem && strncmp(G.subsystem, "block", 5) == 0))
614                 type = S_IFBLK;
615
616 #if ENABLE_FEATURE_MDEV_CONF
617         G.rule_idx = 0; /* restart from the beginning (think mdev -s) */
618 #endif
619         for (;;) {
620                 const char *str_to_match;
621                 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
622                 char *command;
623                 char *alias;
624                 char aliaslink = aliaslink; /* for compiler */
625                 char *node_name;
626                 const struct rule *rule;
627
628                 str_to_match = device_name;
629
630                 rule = next_rule();
631
632 #if ENABLE_FEATURE_MDEV_CONF
633                 if (!env_matches(rule->envmatch))
634                         continue;
635                 if (rule->maj >= 0) {  /* @maj,min rule */
636                         if (major != rule->maj)
637                                 continue;
638                         if (minor < rule->min0 || minor > rule->min1)
639                                 continue;
640                         memset(off, 0, sizeof(off));
641                         goto rule_matches;
642                 }
643                 if (rule->envvar) { /* $envvar=regex rule */
644                         str_to_match = getenv(rule->envvar);
645                         dbg3("getenv('%s'):'%s'", rule->envvar, str_to_match);
646                         if (!str_to_match)
647                                 continue;
648                 }
649                 /* else: str_to_match = device_name */
650
651                 if (rule->regex_compiled) {
652                         int regex_match = regexec(&rule->match, str_to_match, ARRAY_SIZE(off), off, 0);
653                         dbg3("regex_match for '%s':%d", str_to_match, regex_match);
654                         //bb_error_msg("matches:");
655                         //for (int i = 0; i < ARRAY_SIZE(off); i++) {
656                         //      if (off[i].rm_so < 0) continue;
657                         //      bb_error_msg("match %d: '%.*s'\n", i,
658                         //              (int)(off[i].rm_eo - off[i].rm_so),
659                         //              device_name + off[i].rm_so);
660                         //}
661
662                         if (regex_match != 0
663                         /* regexec returns whole pattern as "range" 0 */
664                          || off[0].rm_so != 0
665                          || (int)off[0].rm_eo != (int)strlen(str_to_match)
666                         ) {
667                                 continue; /* this rule doesn't match */
668                         }
669                 }
670                 /* else: it's final implicit "match-all" rule */
671  rule_matches:
672                 dbg2("rule matched, line %d", G.parser ? G.parser->lineno : -1);
673 #endif
674                 /* Build alias name */
675                 alias = NULL;
676                 if (ENABLE_FEATURE_MDEV_RENAME && rule->ren_mov) {
677                         aliaslink = rule->ren_mov[0];
678                         if (aliaslink == '!') {
679                                 /* "!": suppress node creation/deletion */
680                                 major = -2;
681                         }
682                         else if (aliaslink == '>' || aliaslink == '=') {
683                                 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
684                                         char *s;
685                                         char *p;
686                                         unsigned n;
687
688                                         /* substitute %1..9 with off[1..9], if any */
689                                         n = 0;
690                                         s = rule->ren_mov;
691                                         while (*s)
692                                                 if (*s++ == '%')
693                                                         n++;
694
695                                         p = alias = xzalloc(strlen(rule->ren_mov) + n * strlen(str_to_match));
696                                         s = rule->ren_mov + 1;
697                                         while (*s) {
698                                                 *p = *s;
699                                                 if ('%' == *s) {
700                                                         unsigned i = (s[1] - '0');
701                                                         if (i <= 9 && off[i].rm_so >= 0) {
702                                                                 n = off[i].rm_eo - off[i].rm_so;
703                                                                 strncpy(p, str_to_match + off[i].rm_so, n);
704                                                                 p += n - 1;
705                                                                 s++;
706                                                         }
707                                                 }
708                                                 p++;
709                                                 s++;
710                                         }
711                                 } else {
712                                         alias = xstrdup(rule->ren_mov + 1);
713                                 }
714                         }
715                 }
716                 dbg3("alias:'%s'", alias);
717
718                 command = NULL;
719                 IF_FEATURE_MDEV_EXEC(command = rule->r_cmd;)
720                 if (command) {
721                         /* Are we running this command now?
722                          * Run @cmd on create, $cmd on delete, *cmd on any
723                          */
724                         if ((command[0] == '@' && operation == OP_add)
725                          || (command[0] == '$' && operation == OP_remove)
726                          || (command[0] == '*')
727                         ) {
728                                 command++;
729                         } else {
730                                 command = NULL;
731                         }
732                 }
733                 dbg3("command:'%s'", command);
734
735                 /* "Execute" the line we found */
736                 node_name = device_name;
737                 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
738                         node_name = alias = build_alias(alias, device_name);
739                         dbg3("alias2:'%s'", alias);
740                 }
741
742                 if (operation == OP_add && major >= 0) {
743                         char *slash = strrchr(node_name, '/');
744                         if (slash) {
745                                 *slash = '\0';
746                                 mkdir_recursive(node_name);
747                                 *slash = '/';
748                         }
749                         if (ENABLE_FEATURE_MDEV_CONF) {
750                                 dbg1("mknod %s (%d,%d) %o"
751                                         " %u:%u",
752                                         node_name, major, minor, rule->mode | type,
753                                         rule->ugid.uid, rule->ugid.gid
754                                 );
755                         } else {
756                                 dbg1("mknod %s (%d,%d) %o",
757                                         node_name, major, minor, rule->mode | type
758                                 );
759                         }
760                         if (mknod(node_name, rule->mode | type, makedev(major, minor)) && errno != EEXIST)
761                                 bb_perror_msg("can't create '%s'", node_name);
762                         if (ENABLE_FEATURE_MDEV_CONF) {
763                                 chmod(node_name, rule->mode);
764                                 chown(node_name, rule->ugid.uid, rule->ugid.gid);
765                         }
766                         if (major == G.root_major && minor == G.root_minor)
767                                 symlink(node_name, "root");
768                         if (ENABLE_FEATURE_MDEV_RENAME && alias) {
769                                 if (aliaslink == '>') {
770 //TODO: on devtmpfs, device_name already exists and symlink() fails.
771 //End result is that instead of symlink, we have two nodes.
772 //What should be done?
773                                         dbg1("symlink: %s", device_name);
774                                         symlink(node_name, device_name);
775                                 }
776                         }
777                 }
778
779                 if (ENABLE_FEATURE_MDEV_EXEC && command) {
780                         /* setenv will leak memory, use putenv/unsetenv/free */
781                         char *s = xasprintf("%s=%s", "MDEV", node_name);
782                         putenv(s);
783                         dbg1("running: %s", command);
784                         if (system(command) == -1)
785                                 bb_perror_msg("can't run '%s'", command);
786                         bb_unsetenv_and_free(s);
787                 }
788
789                 if (operation == OP_remove && major >= -1) {
790                         if (ENABLE_FEATURE_MDEV_RENAME && alias) {
791                                 if (aliaslink == '>') {
792                                         dbg1("unlink: %s", device_name);
793                                         unlink(device_name);
794                                 }
795                         }
796                         dbg1("unlink: %s", node_name);
797                         unlink(node_name);
798                 }
799
800                 if (ENABLE_FEATURE_MDEV_RENAME)
801                         free(alias);
802
803                 /* We found matching line.
804                  * Stop unless it was prefixed with '-'
805                  */
806                 if (!ENABLE_FEATURE_MDEV_CONF || !rule->keep_matching)
807                         break;
808         } /* for (;;) */
809 }
810
811 /* File callback for /sys/ traversal */
812 static int FAST_FUNC fileAction(const char *fileName,
813                 struct stat *statbuf UNUSED_PARAM,
814                 void *userData,
815                 int depth UNUSED_PARAM)
816 {
817         size_t len = strlen(fileName) - 4; /* can't underflow */
818         char *scratch = userData;
819
820         /* len check is for paranoid reasons */
821         if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
822                 return FALSE;
823
824         strcpy(scratch, fileName);
825         scratch[len] = '\0';
826         make_device(/*DEVNAME:*/ NULL, scratch, OP_add);
827
828         return TRUE;
829 }
830
831 /* Directory callback for /sys/ traversal */
832 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
833                 struct stat *statbuf UNUSED_PARAM,
834                 void *userData UNUSED_PARAM,
835                 int depth)
836 {
837         /* Extract device subsystem -- the name of the directory
838          * under /sys/class/ */
839         if (1 == depth) {
840                 free(G.subsystem);
841                 if (G.subsys_env) {
842                         bb_unsetenv_and_free(G.subsys_env);
843                         G.subsys_env = NULL;
844                 }
845                 G.subsystem = strrchr(fileName, '/');
846                 if (G.subsystem) {
847                         G.subsystem = xstrdup(G.subsystem + 1);
848                         G.subsys_env = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
849                         putenv(G.subsys_env);
850                 }
851         }
852
853         return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
854 }
855
856 /* For the full gory details, see linux/Documentation/firmware_class/README
857  *
858  * Firmware loading works like this:
859  * - kernel sets FIRMWARE env var
860  * - userspace checks /lib/firmware/$FIRMWARE
861  * - userspace waits for /sys/$DEVPATH/loading to appear
862  * - userspace writes "1" to /sys/$DEVPATH/loading
863  * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
864  * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
865  * - kernel loads firmware into device
866  */
867 static void load_firmware(const char *firmware, const char *sysfs_path)
868 {
869         int cnt;
870         int firmware_fd, loading_fd;
871
872         /* check for /lib/firmware/$FIRMWARE */
873         xchdir("/lib/firmware");
874         firmware_fd = open(firmware, O_RDONLY); /* can fail */
875
876         /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
877         xchdir(sysfs_path);
878         for (cnt = 0; cnt < 30; ++cnt) {
879                 loading_fd = open("loading", O_WRONLY);
880                 if (loading_fd >= 0)
881                         goto loading;
882                 sleep(1);
883         }
884         goto out;
885
886  loading:
887         cnt = 0;
888         if (firmware_fd >= 0) {
889                 int data_fd;
890
891                 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
892                 if (full_write(loading_fd, "1", 1) != 1)
893                         goto out;
894
895                 /* load firmware into /sys/$DEVPATH/data */
896                 data_fd = open("data", O_WRONLY);
897                 if (data_fd < 0)
898                         goto out;
899                 cnt = bb_copyfd_eof(firmware_fd, data_fd);
900                 if (ENABLE_FEATURE_CLEAN_UP)
901                         close(data_fd);
902         }
903
904         /* Tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading"
905          * Note: we emit -1 also if firmware file wasn't found.
906          * There are cases when otherwise kernel would wait for minutes
907          * before timing out.
908          */
909         if (cnt > 0)
910                 full_write(loading_fd, "0", 1);
911         else
912                 full_write(loading_fd, "-1", 2);
913
914  out:
915         xchdir("/dev");
916         if (ENABLE_FEATURE_CLEAN_UP) {
917                 close(firmware_fd);
918                 close(loading_fd);
919         }
920 }
921
922 static char *curtime(void)
923 {
924         struct timeval tv;
925         gettimeofday(&tv, NULL);
926         sprintf(G.timestr, "%u.%06u", (unsigned)tv.tv_sec % 60, (unsigned)tv.tv_usec);
927         return G.timestr;
928 }
929
930 static void open_mdev_log(const char *seq, unsigned my_pid)
931 {
932         int logfd = open("mdev.log", O_WRONLY | O_APPEND);
933         if (logfd >= 0) {
934                 xmove_fd(logfd, STDERR_FILENO);
935                 G.verbose = 2;
936                 applet_name = xasprintf("%s[%s]", applet_name, seq ? seq : utoa(my_pid));
937         }
938 }
939
940 /* If it exists, does /dev/mdev.seq match $SEQNUM?
941  * If it does not match, earlier mdev is running
942  * in parallel, and we need to wait.
943  * Active mdev pokes us with SIGCHLD to check the new file.
944  */
945 static int
946 wait_for_seqfile(const char *seq)
947 {
948         /* We time out after 2 sec */
949         static const struct timespec ts = { 0, 32*1000*1000 };
950         int timeout = 2000 / 32;
951         int seq_fd = -1;
952         int do_once = 1;
953         sigset_t set_CHLD;
954
955         sigemptyset(&set_CHLD);
956         sigaddset(&set_CHLD, SIGCHLD);
957         sigprocmask(SIG_BLOCK, &set_CHLD, NULL);
958
959         for (;;) {
960                 int seqlen;
961                 char seqbuf[sizeof(int)*3 + 2];
962
963                 if (seq_fd < 0) {
964                         seq_fd = open("mdev.seq", O_RDWR);
965                         if (seq_fd < 0)
966                                 break;
967                 }
968                 seqlen = pread(seq_fd, seqbuf, sizeof(seqbuf) - 1, 0);
969                 if (seqlen < 0) {
970                         close(seq_fd);
971                         seq_fd = -1;
972                         break;
973                 }
974                 seqbuf[seqlen] = '\0';
975                 if (seqbuf[0] == '\n') {
976                         /* seed file: write out seq ASAP */
977                         xwrite_str(seq_fd, seq);
978                         xlseek(seq_fd, 0, SEEK_SET);
979                         dbg2("first seq written");
980                         break;
981                 }
982                 if (strcmp(seq, seqbuf) == 0) {
983                         /* correct idx */
984                         break;
985                 }
986                 if (do_once) {
987                         dbg2("%s waiting for '%s'", curtime(), seqbuf);
988                         do_once = 0;
989                 }
990                 if (sigtimedwait(&set_CHLD, NULL, &ts) >= 0) {
991                         dbg3("woken up");
992                         continue; /* don't decrement timeout! */
993                 }
994                 if (--timeout == 0) {
995                         dbg1("%s waiting for '%s'", "timed out", seqbuf);
996                         break;
997                 }
998         }
999         sigprocmask(SIG_UNBLOCK, &set_CHLD, NULL);
1000         return seq_fd;
1001 }
1002
1003 static void signal_mdevs(unsigned my_pid)
1004 {
1005         procps_status_t* p = NULL;
1006         while ((p = procps_scan(p, PSSCAN_ARGV0)) != NULL) {
1007                 if (p->pid != my_pid
1008                  && p->argv0
1009                  && strcmp(bb_basename(p->argv0), "mdev") == 0
1010                 ) {
1011                         kill(p->pid, SIGCHLD);
1012                 }
1013         }
1014 }
1015
1016 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1017 int mdev_main(int argc UNUSED_PARAM, char **argv)
1018 {
1019         RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
1020
1021         INIT_G();
1022
1023 #if ENABLE_FEATURE_MDEV_CONF
1024         G.filename = "/etc/mdev.conf";
1025 #endif
1026
1027         /* We can be called as hotplug helper */
1028         /* Kernel cannot provide suitable stdio fds for us, do it ourself */
1029         bb_sanitize_stdio();
1030
1031         /* Force the configuration file settings exactly */
1032         umask(0);
1033
1034         xchdir("/dev");
1035
1036         if (argv[1] && strcmp(argv[1], "-s") == 0) {
1037                 /*
1038                  * Scan: mdev -s
1039                  */
1040                 struct stat st;
1041
1042 #if ENABLE_FEATURE_MDEV_CONF
1043                 /* Same as xrealloc_vector(NULL, 4, 0): */
1044                 G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
1045 #endif
1046                 xstat("/", &st);
1047                 G.root_major = major(st.st_dev);
1048                 G.root_minor = minor(st.st_dev);
1049
1050                 putenv((char*)"ACTION=add");
1051
1052                 /* ACTION_FOLLOWLINKS is needed since in newer kernels
1053                  * /sys/block/loop* (for example) are symlinks to dirs,
1054                  * not real directories.
1055                  * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
1056                  * but we can't enforce that on users)
1057                  */
1058                 if (access("/sys/class/block", F_OK) != 0) {
1059                         /* Scan obsolete /sys/block only if /sys/class/block
1060                          * doesn't exist. Otherwise we'll have dupes.
1061                          * Also, do not complain if it doesn't exist.
1062                          * Some people configure kernel to have no blockdevs.
1063                          */
1064                         recursive_action("/sys/block",
1065                                 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
1066                                 fileAction, dirAction, temp, 0);
1067                 }
1068                 recursive_action("/sys/class",
1069                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
1070                         fileAction, dirAction, temp, 0);
1071         } else {
1072                 char *fw;
1073                 char *seq;
1074                 char *action;
1075                 char *env_devname;
1076                 char *env_devpath;
1077                 unsigned my_pid;
1078                 int seq_fd;
1079                 smalluint op;
1080
1081                 /* Hotplug:
1082                  * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
1083                  * ACTION can be "add", "remove", "change"
1084                  * DEVPATH is like "/block/sda" or "/class/input/mice"
1085                  */
1086                 env_devname = getenv("DEVNAME"); /* can be NULL */
1087                 G.subsystem = getenv("SUBSYSTEM");
1088                 action = getenv("ACTION");
1089                 env_devpath = getenv("DEVPATH");
1090                 if (!action || !env_devpath /*|| !G.subsystem*/)
1091                         bb_show_usage();
1092                 fw = getenv("FIRMWARE");
1093                 seq = getenv("SEQNUM");
1094                 op = index_in_strings(keywords, action);
1095
1096                 my_pid = getpid();
1097                 open_mdev_log(seq, my_pid);
1098
1099                 seq_fd = seq ? wait_for_seqfile(seq) : -1;
1100
1101                 dbg1("%s "
1102                         "ACTION:%s SUBSYSTEM:%s DEVNAME:%s DEVPATH:%s"
1103                         "%s%s",
1104                         curtime(),
1105                         action, G.subsystem, env_devname, env_devpath,
1106                         fw ? " FW:" : "", fw ? fw : ""
1107                 );
1108
1109                 snprintf(temp, PATH_MAX, "/sys%s", env_devpath);
1110                 if (op == OP_remove) {
1111                         /* Ignoring "remove firmware". It was reported
1112                          * to happen and to cause erroneous deletion
1113                          * of device nodes. */
1114                         if (!fw)
1115                                 make_device(env_devname, temp, op);
1116                 }
1117                 else {
1118                         make_device(env_devname, temp, op);
1119                         if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
1120                                 if (op == OP_add && fw)
1121                                         load_firmware(fw, temp);
1122                         }
1123                 }
1124
1125                 dbg1("%s exiting", curtime());
1126                 if (seq_fd >= 0) {
1127                         xwrite_str(seq_fd, utoa(xatou(seq) + 1));
1128                         signal_mdevs(my_pid);
1129                 }
1130         }
1131
1132         if (ENABLE_FEATURE_CLEAN_UP)
1133                 RELEASE_CONFIG_BUFFER(temp);
1134
1135         return EXIT_SUCCESS;
1136 }