blob: 0a34122b41d55d253c5aaa6237f24adf215e6be0 [file] [log] [blame]
"Robert P. J. Day"63fc1a92006-07-02 19:47:05 +00001/* vi: set sw=4 ts=4: */
2/*
Rob Landley70f7ef72005-12-13 08:21:33 +00003 * mdev - Mini udev for busybox
Tim Rikerc1ef7bd2006-01-25 00:08:53 +00004 *
Rob Landley70f7ef72005-12-13 08:21:33 +00005 * Copyright 2005 Rob Landley <rob@landley.net>
6 * Copyright 2005 Frank Sorenson <frank@tuxrocks.com>
7 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02008 * Licensed under GPLv2, see file LICENSE in this source tree.
Rob Landley70f7ef72005-12-13 08:21:33 +00009 */
Pere Orga5bc8c002011-04-11 03:29:49 +020010
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +020011//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
Pere Orga5bc8c002011-04-11 03:29:49 +020073//usage:#define mdev_trivial_usage
74//usage: "[-s]"
75//usage:#define mdev_full_usage "\n\n"
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +020076//usage: "mdev -s is to be run during boot to scan /sys and populate /dev.\n"
Pere Orga5bc8c002011-04-11 03:29:49 +020077//usage: "\n"
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +020078//usage: "Bare mdev is a kernel hotplug helper. To activate it:\n"
79//usage: " echo /sbin/mdev >/proc/sys/kernel/hotplug\n"
Pere Orga5bc8c002011-04-11 03:29:49 +020080//usage: IF_FEATURE_MDEV_CONF(
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +020081//usage: "\n"
Pere Orga5bc8c002011-04-11 03:29:49 +020082//usage: "It uses /etc/mdev.conf with lines\n"
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +020083//usage: " [-]DEVNAME UID:GID PERM"
84//usage: IF_FEATURE_MDEV_RENAME(" [>|=PATH]|[!]")
Pere Orga5bc8c002011-04-11 03:29:49 +020085//usage: IF_FEATURE_MDEV_EXEC(" [@|$|*PROG]")
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +020086//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"
Pere Orga5bc8c002011-04-11 03:29:49 +020091//usage: )
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +020092//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."
Pere Orga5bc8c002011-04-11 03:29:49 +020096
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000097#include "libbb.h"
Rob Landleyb56c2852005-12-17 10:52:30 +000098#include "xregex.h"
Rob Landley70f7ef72005-12-13 08:21:33 +000099
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000100/* "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.
Denis Vlasenko11c17f72009-04-19 23:38:08 +0000105 * If /sys/class/.../dev file does not exist, mdev still may act
106 * on this device: see "@|$|*command args..." parameter in config file.
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000107 *
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.
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000117 *
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 *
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200121 * $envvar=regex format is useful for loading modules for hot-plugged devices
Denis Vlasenko11c17f72009-04-19 23:38:08 +0000122 * 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.
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000133 * Examples:
134 * =loop/ - moves to /dev/loop
135 * >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
Denis Vlasenko11c17f72009-04-19 23:38:08 +0000136 *
137 * Then "command args..." is executed (via sh -c 'command args...').
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000138 * @:execute on creation, $:on deletion, *:on both.
Denis Vlasenko11c17f72009-04-19 23:38:08 +0000139 * This happens regardless of /sys/class/.../dev existence.
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000140 */
141
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200142struct 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
Denis Vlasenko4e5f82c2007-06-03 22:30:22 +0000155struct globals {
Rob Landley5cd1ccd2006-05-21 18:33:27 +0000156 int root_major, root_minor;
Denis Vlasenko065c7142009-04-13 22:23:02 +0000157 char *subsystem;
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200158#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;
Denys Vlasenko98a4c7c2010-02-04 15:00:15 +0100165} FIX_ALIASING;
Denis Vlasenko4e5f82c2007-06-03 22:30:22 +0000166#define G (*(struct globals*)&bb_common_bufsiz1)
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200167#define INIT_G() do { \
168 IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.maj = -1;) \
169 IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.mode = 0660;) \
170} while (0)
171
Rob Landleya7e3d052006-02-21 06:11:13 +0000172
Denis Vlasenkod48e81f2008-07-06 07:00:11 +0000173/* Prevent infinite loops in /sys symlinks */
174#define MAX_SYSFS_DEPTH 3
Mike Frysingerb51fd352007-06-13 09:24:50 +0000175
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000176/* We use additional 64+ bytes in make_device() */
177#define SCRATCH_SIZE 80
178
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200179#if 0
180# define dbg(...) bb_error_msg(__VA_ARGS__)
181#else
182# define dbg(...) ((void)0)
183#endif
184
185
186#if ENABLE_FEATURE_MDEV_CONF
187
188static void make_default_cur_rule(void)
189{
190 memset(&G.cur_rule, 0, sizeof(G.cur_rule));
191 G.cur_rule.maj = -1; /* "not a @major,minor rule" */
192 G.cur_rule.mode = 0660;
193}
194
195static void clean_up_cur_rule(void)
196{
197 free(G.cur_rule.envvar);
198 if (G.cur_rule.regex_compiled)
199 regfree(&G.cur_rule.match);
200 free(G.cur_rule.ren_mov);
201 IF_FEATURE_MDEV_EXEC(free(G.cur_rule.r_cmd);)
202 make_default_cur_rule();
203}
204
205static void parse_next_rule(void)
206{
207 /* Note: on entry, G.cur_rule is set to default */
208 while (1) {
209 char *tokens[4];
210 char *val;
211
212 /* No PARSE_EOL_COMMENTS, because command may contain '#' chars */
213 if (!config_read(G.parser, tokens, 4, 3, "# \t", PARSE_NORMAL & ~PARSE_EOL_COMMENTS))
214 break;
215
216 /* Fields: [-]regex uid:gid mode [alias] [cmd] */
217 dbg("token1:'%s'", tokens[1]);
218
219 /* 1st field */
220 val = tokens[0];
221 G.cur_rule.keep_matching = ('-' == val[0]);
222 val += G.cur_rule.keep_matching; /* swallow leading dash */
223 if (val[0] == '@') {
224 /* @major,minor[-minor2] */
225 /* (useful when name is ambiguous:
226 * "/sys/class/usb/lp0" and
227 * "/sys/class/printer/lp0")
228 */
229 int sc = sscanf(val, "@%u,%u-%u", &G.cur_rule.maj, &G.cur_rule.min0, &G.cur_rule.min1);
230 if (sc < 2 || G.cur_rule.maj < 0) {
231 bb_error_msg("bad @maj,min on line %d", G.parser->lineno);
232 goto next_rule;
233 }
234 if (sc == 2)
235 G.cur_rule.min1 = G.cur_rule.min0;
236 } else {
237 if (val[0] == '$') {
238 char *eq = strchr(++val, '=');
239 if (!eq) {
240 bb_error_msg("bad $envvar=regex on line %d", G.parser->lineno);
241 goto next_rule;
242 }
243 G.cur_rule.envvar = xstrndup(val, eq - val);
244 val = eq + 1;
245 }
246 xregcomp(&G.cur_rule.match, val, REG_EXTENDED);
247 G.cur_rule.regex_compiled = 1;
248 G.cur_rule.regex_has_slash = (strchr(val, '/') != NULL);
249 }
250
251 /* 2nd field: uid:gid - device ownership */
252 if (get_uidgid(&G.cur_rule.ugid, tokens[1], /*allow_numeric:*/ 1) == 0) {
253 bb_error_msg("unknown user/group '%s' on line %d", tokens[1], G.parser->lineno);
254 goto next_rule;
255 }
256
257 /* 3rd field: mode - device permissions */
258 bb_parse_mode(tokens[2], &G.cur_rule.mode);
259
260 /* 4th field (opt): ">|=alias" or "!" to not create the node */
261 val = tokens[3];
262 if (ENABLE_FEATURE_MDEV_RENAME && val && strchr(">=!", val[0])) {
263 char *s = skip_non_whitespace(val);
264 G.cur_rule.ren_mov = xstrndup(val, s - val);
265 val = skip_whitespace(s);
266 }
267
268 if (ENABLE_FEATURE_MDEV_EXEC && val && val[0]) {
269 const char *s = "$@*";
270 const char *s2 = strchr(s, val[0]);
271 if (!s2) {
272 bb_error_msg("bad line %u", G.parser->lineno);
273 goto next_rule;
274 }
275 IF_FEATURE_MDEV_EXEC(G.cur_rule.r_cmd = xstrdup(val);)
276 }
277
278 return;
279 next_rule:
280 clean_up_cur_rule();
281 } /* while (config_read) */
282
283 dbg("config_close(G.parser)");
284 config_close(G.parser);
285 G.parser = NULL;
286
287 return;
288}
289
290/* If mdev -s, we remember rules in G.rule_vec[].
291 * Otherwise, there is no point in doing it, and we just
292 * save only one parsed rule in G.cur_rule.
293 */
294static const struct rule *next_rule(void)
295{
296 struct rule *rule;
297
298 /* Open conf file if we didn't do it yet */
299 if (!G.parser && G.filename) {
300 dbg("config_open('%s')", G.filename);
301 G.parser = config_open2(G.filename, fopen_for_read);
302 G.filename = NULL;
303 }
304
305 if (G.rule_vec) {
306 /* mdev -s */
307 /* Do we have rule parsed already? */
308 if (G.rule_vec[G.rule_idx]) {
309 dbg("< G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
310 return G.rule_vec[G.rule_idx++];
311 }
312 make_default_cur_rule();
313 } else {
314 /* not mdev -s */
315 clean_up_cur_rule();
316 }
317
318 /* Parse one more rule if file isn't fully read */
319 rule = &G.cur_rule;
320 if (G.parser) {
321 parse_next_rule();
322 if (G.rule_vec) { /* mdev -s */
323 rule = memcpy(xmalloc(sizeof(G.cur_rule)), &G.cur_rule, sizeof(G.cur_rule));
324 G.rule_vec = xrealloc_vector(G.rule_vec, 4, G.rule_idx);
325 G.rule_vec[G.rule_idx++] = rule;
326 dbg("> G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
327 }
328 }
329
330 return rule;
331}
332
333#else
334
335# define next_rule() (&G.cur_rule)
336
337#endif
338
Denis Vlasenkod9860482008-07-12 10:23:16 +0000339/* Builds an alias path.
340 * This function potentionally reallocates the alias parameter.
Denis Vlasenkoc7cc5a92009-04-19 01:27:20 +0000341 * Only used for ENABLE_FEATURE_MDEV_RENAME
Denis Vlasenkod9860482008-07-12 10:23:16 +0000342 */
343static char *build_alias(char *alias, const char *device_name)
344{
345 char *dest;
346
347 /* ">bar/": rename to bar/device_name */
348 /* ">bar[/]baz": rename to bar[/]baz */
349 dest = strrchr(alias, '/');
350 if (dest) { /* ">bar/[baz]" ? */
351 *dest = '\0'; /* mkdir bar */
352 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
353 *dest = '/';
354 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
355 dest = alias;
356 alias = concat_path_file(alias, device_name);
357 free(dest);
358 }
359 }
360
361 return alias;
362}
363
Denys Vlasenko76f5e382009-05-04 21:59:05 +0200364/* mknod in /dev based on a path like "/sys/block/hda/hda1"
365 * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
366 * after NUL, but we promise to not mangle (IOW: to restore if needed)
367 * path string.
368 * NB2: "mdev -s" may call us many times, do not leak memory/fds!
369 */
Rob Landleyef10d522006-06-26 14:11:33 +0000370static void make_device(char *path, int delete)
Rob Landley70f7ef72005-12-13 08:21:33 +0000371{
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100372 char *device_name, *subsystem_slash_devname;
Denis Vlasenkof46be092006-10-16 19:39:37 +0000373 int major, minor, type, len;
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200374
375 dbg("%s('%s', delete:%d)", __func__, path, delete);
Mike Frysingerf0044c42008-02-01 06:53:50 +0000376
Rob Landley15fe2e12006-05-08 02:53:23 +0000377 /* Try to read major/minor string. Note that the kernel puts \n after
378 * the data, so we don't need to worry about null terminating the string
Denis Vlasenko8d89bed2008-09-07 23:22:08 +0000379 * because sscanf() will stop at the first nondigit, which \n is.
380 * We also depend on path having writeable space after it.
Mike Frysingerc881c732007-11-19 09:04:22 +0000381 */
Denis Vlasenko8d89bed2008-09-07 23:22:08 +0000382 major = -1;
Rob Landley10b36f92006-08-10 01:09:37 +0000383 if (!delete) {
Denis Vlasenko3798db52009-04-19 21:37:07 +0000384 char *dev_maj_min = path + strlen(path);
385
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000386 strcpy(dev_maj_min, "/dev");
387 len = open_read_close(path, dev_maj_min + 1, 64);
Denis Vlasenko3798db52009-04-19 21:37:07 +0000388 *dev_maj_min = '\0';
Mike Frysingerae86a332008-02-20 18:31:36 +0000389 if (len < 1) {
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000390 if (!ENABLE_FEATURE_MDEV_EXEC)
Mike Frysingerae86a332008-02-20 18:31:36 +0000391 return;
Denis Vlasenko3798db52009-04-19 21:37:07 +0000392 /* no "dev" file, but we can still run scripts
393 * based on device name */
394 } else if (sscanf(++dev_maj_min, "%u:%u", &major, &minor) != 2) {
Denis Vlasenko8d89bed2008-09-07 23:22:08 +0000395 major = -1;
Mike Frysingerae86a332008-02-20 18:31:36 +0000396 }
Rob Landley10b36f92006-08-10 01:09:37 +0000397 }
Denys Vlasenkof2860bf2010-08-16 14:26:15 +0200398 /* else: for delete, -1 still deletes the node, but < -1 suppresses that */
Tim Rikerc1ef7bd2006-01-25 00:08:53 +0000399
Rob Landley70f7ef72005-12-13 08:21:33 +0000400 /* Determine device name, type, major and minor */
Denis Vlasenko3798db52009-04-19 21:37:07 +0000401 device_name = (char*) bb_basename(path);
Denis Vlasenkoaa8a6012008-03-29 16:07:46 +0000402 /* http://kernel.org/doc/pending/hotplug.txt says that only
Denis Vlasenkoa87045c2008-07-12 10:28:41 +0000403 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100404 * But since 2.6.25 block devices are also in /sys/class/block.
405 * We use strstr("/block/") to forestall future surprises. */
Denis Vlasenko9504e442008-10-29 01:19:15 +0000406 type = S_IFCHR;
Denys Vlasenko8d4a8d12010-03-16 18:37:19 +0100407 if (strstr(path, "/block/") || (G.subsystem && strncmp(G.subsystem, "block", 5) == 0))
Denis Vlasenko9504e442008-10-29 01:19:15 +0000408 type = S_IFBLK;
Tim Rikerc1ef7bd2006-01-25 00:08:53 +0000409
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000410 /* Make path point to "subsystem/device_name" */
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100411 subsystem_slash_devname = NULL;
412 /* Check for coldplug invocations first */
413 if (strncmp(path, "/sys/block/", 11) == 0) /* legacy case */
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000414 path += sizeof("/sys/") - 1;
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100415 else if (strncmp(path, "/sys/class/", 11) == 0)
Denis Vlasenko5ff96292009-04-17 00:01:04 +0000416 path += sizeof("/sys/class/") - 1;
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100417 else {
418 /* Example of a hotplug invocation:
419 * SUBSYSTEM="block"
420 * DEVPATH="/sys" + "/devices/virtual/mtd/mtd3/mtdblock3"
421 * ("/sys" is added by mdev_main)
422 * - path does not contain subsystem
423 */
424 subsystem_slash_devname = concat_path_file(G.subsystem, device_name);
425 path = subsystem_slash_devname;
426 }
Denis Vlasenko6dda5de2009-04-16 21:42:12 +0000427
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200428#if ENABLE_FEATURE_MDEV_CONF
429 G.rule_idx = 0; /* restart from the beginning (think mdev -s) */
430#endif
431 for (;;) {
432 const char *str_to_match;
433 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
434 char *command;
435 char *alias;
Denis Vlasenkof2b39e02009-04-13 23:18:52 +0000436 char aliaslink = aliaslink; /* for compiler */
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200437 const char *node_name;
438 const struct rule *rule;
Denis Vlasenkoc7cc5a92009-04-19 01:27:20 +0000439
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200440 str_to_match = "";
Denis Vlasenkof2b39e02009-04-13 23:18:52 +0000441
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200442 rule = next_rule();
Denis Vlasenko3798db52009-04-19 21:37:07 +0000443
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200444#if ENABLE_FEATURE_MDEV_CONF
445 if (rule->maj >= 0) { /* @maj,min rule */
446 if (major != rule->maj)
447 continue;
448 if (minor < rule->min0 || minor > rule->min1)
449 continue;
450 memset(off, 0, sizeof(off));
451 goto rule_matches;
452 }
453 if (rule->envvar) { /* $envvar=regex rule */
454 str_to_match = getenv(rule->envvar);
455 dbg("getenv('%s'):'%s'", rule->envvar, str_to_match);
456 if (!str_to_match)
457 continue;
458 } else {
459 /* regex to match [subsystem/]device_name */
460 str_to_match = (rule->regex_has_slash ? path : device_name);
461 }
Denis Vlasenkof2b39e02009-04-13 23:18:52 +0000462
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200463 if (rule->regex_compiled) {
464 int regex_match = regexec(&rule->match, str_to_match, ARRAY_SIZE(off), off, 0);
465 dbg("regex_match for '%s':%d", str_to_match, regex_match);
466 //bb_error_msg("matches:");
467 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
468 // if (off[i].rm_so < 0) continue;
469 // bb_error_msg("match %d: '%.*s'\n", i,
470 // (int)(off[i].rm_eo - off[i].rm_so),
471 // device_name + off[i].rm_so);
472 //}
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000473
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200474 if (regex_match != 0
475 /* regexec returns whole pattern as "range" 0 */
476 || off[0].rm_so != 0
477 || (int)off[0].rm_eo != (int)strlen(str_to_match)
478 ) {
479 continue; /* this rule doesn't match */
Denis Vlasenko3798db52009-04-19 21:37:07 +0000480 }
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200481 }
482 /* else: it's final implicit "match-all" rule */
483 rule_matches:
484#endif
485 dbg("rule matched");
486
487 /* Build alias name */
488 alias = NULL;
489 if (ENABLE_FEATURE_MDEV_RENAME && rule->ren_mov) {
490 aliaslink = rule->ren_mov[0];
491 if (aliaslink == '!') {
492 /* "!": suppress node creation/deletion */
493 major = -2;
Denis Vlasenko3798db52009-04-19 21:37:07 +0000494 }
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200495 else if (aliaslink == '>' || aliaslink == '=') {
496 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
497 char *s;
498 char *p;
499 unsigned n;
Denis Vlasenko3798db52009-04-19 21:37:07 +0000500
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200501 /* substitute %1..9 with off[1..9], if any */
502 n = 0;
503 s = rule->ren_mov;
504 while (*s)
505 if (*s++ == '%')
506 n++;
Mike Frysingerc881c732007-11-19 09:04:22 +0000507
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200508 p = alias = xzalloc(strlen(rule->ren_mov) + n * strlen(str_to_match));
509 s = rule->ren_mov + 1;
510 while (*s) {
511 *p = *s;
512 if ('%' == *s) {
513 unsigned i = (s[1] - '0');
514 if (i <= 9 && off[i].rm_so >= 0) {
515 n = off[i].rm_eo - off[i].rm_so;
516 strncpy(p, str_to_match + off[i].rm_so, n);
517 p += n - 1;
518 s++;
Denis Vlasenkoc7cc5a92009-04-19 01:27:20 +0000519 }
Denis Vlasenkoc7cc5a92009-04-19 01:27:20 +0000520 }
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200521 p++;
522 s++;
Denis Vlasenkof2f38682008-03-29 17:26:10 +0000523 }
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200524 } else {
525 alias = xstrdup(rule->ren_mov + 1);
Denys Vlasenkob38af7b2010-04-02 06:47:14 +0200526 }
Denis Vlasenko44615642008-03-29 13:10:57 +0000527 }
Denis Vlasenkodf96df92008-07-26 18:35:10 +0000528 }
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200529 dbg("alias:'%s'", alias);
Denis Vlasenkoc7cc5a92009-04-19 01:27:20 +0000530
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200531 command = NULL;
532 IF_FEATURE_MDEV_EXEC(command = rule->r_cmd;)
533 if (command) {
534 const char *s = "$@*";
535 const char *s2 = strchr(s, command[0]);
536
537 /* Are we running this command now?
538 * Run $cmd on delete, @cmd on create, *cmd on both
539 */
540 if (s2 - s != delete) {
541 /* We are here if: '*',
542 * or: '@' and delete = 0,
543 * or: '$' and delete = 1
544 */
545 command++;
546 } else {
547 command = NULL;
548 }
549 }
550 dbg("command:'%s'", command);
Denis Vlasenkof2b39e02009-04-13 23:18:52 +0000551
552 /* "Execute" the line we found */
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200553 node_name = device_name;
554 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
555 node_name = alias = build_alias(alias, device_name);
556 dbg("alias2:'%s'", alias);
Denis Vlasenkof2b39e02009-04-13 23:18:52 +0000557 }
558
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200559 if (!delete && major >= 0) {
560 dbg("mknod('%s',%o,(%d,%d))", node_name, rule->mode | type, major, minor);
561 if (mknod(node_name, rule->mode | type, makedev(major, minor)) && errno != EEXIST)
562 bb_perror_msg("can't create '%s'", node_name);
563 if (major == G.root_major && minor == G.root_minor)
564 symlink(node_name, "root");
565 if (ENABLE_FEATURE_MDEV_CONF) {
566 chmod(node_name, rule->mode);
567 chown(node_name, rule->ugid.uid, rule->ugid.gid);
568 }
569 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
570 if (aliaslink == '>') {
571//TODO: on devtmpfs, device_name already exists and symlink() fails.
572//End result is that instead of symlink, we have two nodes.
573//What should be done?
574 symlink(node_name, device_name);
575 }
576 }
577 }
578
579 if (ENABLE_FEATURE_MDEV_EXEC && command) {
580 /* setenv will leak memory, use putenv/unsetenv/free */
581 char *s = xasprintf("%s=%s", "MDEV", node_name);
582 char *s1 = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
583 putenv(s);
584 putenv(s1);
585 if (system(command) == -1)
586 bb_perror_msg("can't run '%s'", command);
587 bb_unsetenv_and_free(s1);
588 bb_unsetenv_and_free(s);
589 }
590
591 if (delete && major >= -1) {
592 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
593 if (aliaslink == '>')
594 unlink(device_name);
595 }
596 unlink(node_name);
597 }
598
599 if (ENABLE_FEATURE_MDEV_RENAME)
600 free(alias);
601
Denis Vlasenkof2b39e02009-04-13 23:18:52 +0000602 /* We found matching line.
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200603 * Stop unless it was prefixed with '-'
604 */
605 if (!ENABLE_FEATURE_MDEV_CONF || !rule->keep_matching)
Denis Vlasenkof2b39e02009-04-13 23:18:52 +0000606 break;
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200607 } /* for (;;) */
Mike Frysingerc881c732007-11-19 09:04:22 +0000608
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100609 free(subsystem_slash_devname);
Rob Landley70f7ef72005-12-13 08:21:33 +0000610}
611
Mike Frysingerb51fd352007-06-13 09:24:50 +0000612/* File callback for /sys/ traversal */
Denis Vlasenkodefc1ea2008-06-27 02:52:20 +0000613static int FAST_FUNC fileAction(const char *fileName,
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000614 struct stat *statbuf UNUSED_PARAM,
Denis Vlasenko7049ff82008-06-25 09:53:17 +0000615 void *userData,
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000616 int depth UNUSED_PARAM)
Rob Landley70f7ef72005-12-13 08:21:33 +0000617{
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000618 size_t len = strlen(fileName) - 4; /* can't underflow */
Mike Frysingerb51fd352007-06-13 09:24:50 +0000619 char *scratch = userData;
Rob Landley70f7ef72005-12-13 08:21:33 +0000620
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000621 /* len check is for paranoid reasons */
Denis Vlasenkod9860482008-07-12 10:23:16 +0000622 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
Mike Frysingerb51fd352007-06-13 09:24:50 +0000623 return FALSE;
Rob Landley70f7ef72005-12-13 08:21:33 +0000624
Mike Frysingerb51fd352007-06-13 09:24:50 +0000625 strcpy(scratch, fileName);
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000626 scratch[len] = '\0';
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100627 make_device(scratch, /*delete:*/ 0);
Rob Landley70f7ef72005-12-13 08:21:33 +0000628
Mike Frysingerb51fd352007-06-13 09:24:50 +0000629 return TRUE;
630}
Rob Landley70f7ef72005-12-13 08:21:33 +0000631
Mike Frysingerb51fd352007-06-13 09:24:50 +0000632/* Directory callback for /sys/ traversal */
Denis Vlasenkoa60f84e2008-07-05 09:18:54 +0000633static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
634 struct stat *statbuf UNUSED_PARAM,
635 void *userData UNUSED_PARAM,
Denis Vlasenko7049ff82008-06-25 09:53:17 +0000636 int depth)
Mike Frysingerb51fd352007-06-13 09:24:50 +0000637{
Denis Vlasenko32a3d082009-04-14 21:23:33 +0000638 /* Extract device subsystem -- the name of the directory
639 * under /sys/class/ */
Denis Vlasenko065c7142009-04-13 22:23:02 +0000640 if (1 == depth) {
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100641 free(G.subsystem);
642 G.subsystem = strrchr(fileName, '/');
643 if (G.subsystem)
644 G.subsystem = xstrdup(G.subsystem + 1);
Denis Vlasenko065c7142009-04-13 22:23:02 +0000645 }
646
Mike Frysingerb51fd352007-06-13 09:24:50 +0000647 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
Rob Landley70f7ef72005-12-13 08:21:33 +0000648}
649
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000650/* For the full gory details, see linux/Documentation/firmware_class/README
651 *
652 * Firmware loading works like this:
653 * - kernel sets FIRMWARE env var
654 * - userspace checks /lib/firmware/$FIRMWARE
655 * - userspace waits for /sys/$DEVPATH/loading to appear
656 * - userspace writes "1" to /sys/$DEVPATH/loading
657 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
658 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
659 * - kernel loads firmware into device
660 */
Denis Vlasenkoc7cc5a92009-04-19 01:27:20 +0000661static void load_firmware(const char *firmware, const char *sysfs_path)
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000662{
663 int cnt;
664 int firmware_fd, loading_fd, data_fd;
665
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000666 /* check for /lib/firmware/$FIRMWARE */
667 xchdir("/lib/firmware");
Mike Frysinger0e0639b2007-06-14 09:29:48 +0000668 firmware_fd = xopen(firmware, O_RDONLY);
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000669
670 /* in case we goto out ... */
671 data_fd = -1;
672
673 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
674 xchdir(sysfs_path);
675 for (cnt = 0; cnt < 30; ++cnt) {
676 loading_fd = open("loading", O_WRONLY);
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000677 if (loading_fd != -1)
678 goto loading;
679 sleep(1);
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000680 }
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000681 goto out;
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000682
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000683 loading:
Denis Vlasenko32a3d082009-04-14 21:23:33 +0000684 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000685 if (full_write(loading_fd, "1", 1) != 1)
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000686 goto out;
687
Denis Vlasenko32a3d082009-04-14 21:23:33 +0000688 /* load firmware into /sys/$DEVPATH/data */
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000689 data_fd = open("data", O_WRONLY);
690 if (data_fd == -1)
691 goto out;
692 cnt = bb_copyfd_eof(firmware_fd, data_fd);
693
Denis Vlasenko32a3d082009-04-14 21:23:33 +0000694 /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000695 if (cnt > 0)
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000696 full_write(loading_fd, "0", 1);
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000697 else
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000698 full_write(loading_fd, "-1", 2);
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000699
700 out:
701 if (ENABLE_FEATURE_CLEAN_UP) {
702 close(firmware_fd);
703 close(loading_fd);
704 close(data_fd);
705 }
706}
707
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +0000708int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Denis Vlasenkod9860482008-07-12 10:23:16 +0000709int mdev_main(int argc UNUSED_PARAM, char **argv)
Rob Landley70f7ef72005-12-13 08:21:33 +0000710{
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000711 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
Rob Landley29e08ff2006-01-12 06:13:50 +0000712
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200713 INIT_G();
714
715#if ENABLE_FEATURE_MDEV_CONF
716 G.filename = "/etc/mdev.conf";
717#endif
718
Denis Vlasenkod48e81f2008-07-06 07:00:11 +0000719 /* We can be called as hotplug helper */
Denis Vlasenkof4e6bd02008-05-31 18:27:58 +0000720 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
Denis Vlasenkod48e81f2008-07-06 07:00:11 +0000721 bb_sanitize_stdio();
Denis Vlasenkof4e6bd02008-05-31 18:27:58 +0000722
Denis Vlasenko3798db52009-04-19 21:37:07 +0000723 /* Force the configuration file settings exactly */
724 umask(0);
725
Denis Vlasenko4e5f82c2007-06-03 22:30:22 +0000726 xchdir("/dev");
Rob Landley15fe2e12006-05-08 02:53:23 +0000727
Denis Vlasenkoaafbae62009-04-13 13:33:02 +0000728 if (argv[1] && strcmp(argv[1], "-s") == 0) {
Mike Frysingerc881c732007-11-19 09:04:22 +0000729 /* Scan:
730 * mdev -s
731 */
Rob Landleya7e3d052006-02-21 06:11:13 +0000732 struct stat st;
733
Tanguy Pruvot8a6c2c22012-04-28 00:24:09 +0200734#if ENABLE_FEATURE_MDEV_CONF
735 /* Same as xrealloc_vector(NULL, 4, 0): */
736 G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
737#endif
Denis Vlasenkof46be092006-10-16 19:39:37 +0000738 xstat("/", &st);
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100739 G.root_major = major(st.st_dev);
740 G.root_minor = minor(st.st_dev);
Mike Frysingerb51fd352007-06-13 09:24:50 +0000741
Denis Vlasenko67075bb2008-07-06 17:00:49 +0000742 /* ACTION_FOLLOWLINKS is needed since in newer kernels
743 * /sys/block/loop* (for example) are symlinks to dirs,
744 * not real directories.
745 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
Denis Vlasenkod63cd1b2009-02-13 00:02:54 +0000746 * but we can't enforce that on users)
747 */
748 if (access("/sys/class/block", F_OK) != 0) {
749 /* Scan obsolete /sys/block only if /sys/class/block
750 * doesn't exist. Otherwise we'll have dupes.
Denis Vlasenkof1df35c2009-04-12 14:00:12 +0000751 * Also, do not complain if it doesn't exist.
752 * Some people configure kernel to have no blockdevs.
Denis Vlasenkod63cd1b2009-02-13 00:02:54 +0000753 */
754 recursive_action("/sys/block",
Denis Vlasenkof1df35c2009-04-12 14:00:12 +0000755 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
Denis Vlasenkod63cd1b2009-02-13 00:02:54 +0000756 fileAction, dirAction, temp, 0);
757 }
Mike Frysingerb51fd352007-06-13 09:24:50 +0000758 recursive_action("/sys/class",
Denis Vlasenko67075bb2008-07-06 17:00:49 +0000759 ACTION_RECURSE | ACTION_FOLLOWLINKS,
Mike Frysingerb51fd352007-06-13 09:24:50 +0000760 fileAction, dirAction, temp, 0);
Rob Landley29e08ff2006-01-12 06:13:50 +0000761 } else {
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000762 char *fw;
Denis Vlasenko018bee62008-07-15 22:33:13 +0000763 char *seq;
764 char *action;
765 char *env_path;
Bernhard Reutner-Fischer6531f092009-10-26 23:27:04 +0100766 static const char keywords[] ALIGN1 = "remove\0add\0";
767 enum { OP_remove = 0, OP_add };
768 smalluint op;
Denis Vlasenko018bee62008-07-15 22:33:13 +0000769
Mike Frysingerc881c732007-11-19 09:04:22 +0000770 /* Hotplug:
Denis Vlasenko065c7142009-04-13 22:23:02 +0000771 * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
Mike Frysingerc881c732007-11-19 09:04:22 +0000772 * ACTION can be "add" or "remove"
773 * DEVPATH is like "/block/sda" or "/class/input/mice"
774 */
Rob Landley29e08ff2006-01-12 06:13:50 +0000775 action = getenv("ACTION");
776 env_path = getenv("DEVPATH");
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100777 G.subsystem = getenv("SUBSYSTEM");
778 if (!action || !env_path /*|| !G.subsystem*/)
Mike Frysingera421ba82006-02-03 00:25:37 +0000779 bb_show_usage();
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000780 fw = getenv("FIRMWARE");
Bernhard Reutner-Fischer6531f092009-10-26 23:27:04 +0100781 op = index_in_strings(keywords, action);
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000782 /* If it exists, does /dev/mdev.seq match $SEQNUM?
783 * If it does not match, earlier mdev is running
784 * in parallel, and we need to wait */
Denis Vlasenko018bee62008-07-15 22:33:13 +0000785 seq = getenv("SEQNUM");
786 if (seq) {
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000787 int timeout = 2000 / 32; /* 2000 msec */
Denis Vlasenko018bee62008-07-15 22:33:13 +0000788 do {
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000789 int seqlen;
790 char seqbuf[sizeof(int)*3 + 2];
791
Denys Vlasenko8a90e612012-02-04 19:55:27 +0100792 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf) - 1);
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000793 if (seqlen < 0) {
794 seq = NULL;
Denis Vlasenko018bee62008-07-15 22:33:13 +0000795 break;
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000796 }
Denis Vlasenko018bee62008-07-15 22:33:13 +0000797 seqbuf[seqlen] = '\0';
798 if (seqbuf[0] == '\n' /* seed file? */
799 || strcmp(seq, seqbuf) == 0 /* correct idx? */
800 ) {
801 break;
802 }
803 usleep(32*1000);
804 } while (--timeout);
805 }
806
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000807 snprintf(temp, PATH_MAX, "/sys%s", env_path);
Bernhard Reutner-Fischer6531f092009-10-26 23:27:04 +0100808 if (op == OP_remove) {
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000809 /* Ignoring "remove firmware". It was reported
810 * to happen and to cause erroneous deletion
811 * of device nodes. */
812 if (!fw)
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100813 make_device(temp, /*delete:*/ 1);
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000814 }
Bernhard Reutner-Fischer6531f092009-10-26 23:27:04 +0100815 else if (op == OP_add) {
Denys Vlasenko64bb95a2010-02-24 10:39:47 +0100816 make_device(temp, /*delete:*/ 0);
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000817 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
Denis Vlasenkocf26ab72008-03-27 22:45:44 +0000818 if (fw)
819 load_firmware(fw, temp);
820 }
Mike Frysingera78ef2c2007-06-13 07:34:15 +0000821 }
Denis Vlasenko018bee62008-07-15 22:33:13 +0000822
Denis Vlasenko1fb26da2009-04-13 02:15:57 +0000823 if (seq) {
Denis Vlasenko018bee62008-07-15 22:33:13 +0000824 xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
825 }
Rob Landley29e08ff2006-01-12 06:13:50 +0000826 }
827
Mike Frysingerc881c732007-11-19 09:04:22 +0000828 if (ENABLE_FEATURE_CLEAN_UP)
829 RELEASE_CONFIG_BUFFER(temp);
830
Denis Vlasenkoaafbae62009-04-13 13:33:02 +0000831 return EXIT_SUCCESS;
Rob Landley70f7ef72005-12-13 08:21:33 +0000832}