1 /* vi: set sw=4 ts=4: */
4 * mdev - Mini udev for busybox
6 * Copyright 2005 Rob Landley <rob@landley.net>
7 * Copyright 2005 Frank Sorenson <frank@tuxrocks.com>
9 * Licensed under GPL version 2, see file LICENSE in this tarball for details.
16 int root_major, root_minor;
18 #define G (*(struct globals*)&bb_common_bufsiz1)
19 #define root_major (G.root_major)
20 #define root_minor (G.root_minor)
22 /* Prevent infinite loops in /sys symlinks */
23 #define MAX_SYSFS_DEPTH 3
25 /* We use additional 64+ bytes in make_device() */
26 #define SCRATCH_SIZE 80
28 /* Builds an alias path.
29 * This function potentionally reallocates the alias parameter.
31 static char *build_alias(char *alias, const char *device_name)
35 /* ">bar/": rename to bar/device_name */
36 /* ">bar[/]baz": rename to bar[/]baz */
37 dest = strrchr(alias, '/');
38 if (dest) { /* ">bar/[baz]" ? */
39 *dest = '\0'; /* mkdir bar */
40 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
42 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
44 alias = concat_path_file(alias, device_name);
52 /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
53 /* NB: "mdev -s" may call us many times, do not leak memory/fds! */
54 static void make_device(char *path, int delete)
56 const char *device_name;
57 int major, minor, type, len;
61 char *dev_maj_min = path + strlen(path);
64 char aliaslink = aliaslink; /* for compiler */
66 /* Force the configuration file settings exactly. */
69 /* Try to read major/minor string. Note that the kernel puts \n after
70 * the data, so we don't need to worry about null terminating the string
71 * because sscanf() will stop at the first nondigit, which \n is. We
72 * also depend on path having writeable space after it.
75 strcpy(dev_maj_min, "/dev");
76 len = open_read_close(path, dev_maj_min + 1, 64);
77 *dev_maj_min++ = '\0';
79 if (!ENABLE_FEATURE_MDEV_EXEC)
81 /* no "dev" file, so just try to run script */
86 /* Determine device name, type, major and minor */
87 device_name = bb_basename(path);
88 /* http://kernel.org/doc/pending/hotplug.txt says that only
89 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
90 * But since 2.6.25 block devices are also in /sys/class/block.
91 * We use strstr("/block/") to forestall future surprises. */
93 if (strstr(path, "/block/"))
96 if (ENABLE_FEATURE_MDEV_CONF) {
97 parser_t *parser = config_open("/etc/mdev.conf");
100 /* If we have config file, look up user settings */
104 while (config_read(parser, tokens, 4, 3, " \t", '#') >= 0) {
105 regmatch_t off[1+9*ENABLE_FEATURE_MDEV_RENAME_REGEXP];
108 /* Fields: regex uid:gid mode [alias] [cmd] */
110 /* 1st field: regex to match this device */
116 xregcomp(&match, tokens[0], REG_EXTENDED);
117 result = regexec(&match, device_name, ARRAY_SIZE(off), off, 0);
120 //bb_error_msg("matches:");
121 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
122 // if (off[i].rm_so < 0) continue;
123 // bb_error_msg("match %d: '%.*s'\n", i,
124 // (int)(off[i].rm_eo - off[i].rm_so),
125 // device_name + off[i].rm_so);
128 /* If not this device, skip rest of line */
129 /* (regexec returns whole pattern as "range" 0) */
130 if (result || off[0].rm_so
131 || ((int)off[0].rm_eo != (int)strlen(device_name))
137 /* This line matches: stop parsing the file
138 * after parsing the rest of fields */
140 /* 2nd field: uid:gid - device ownership */
144 char *str_uid = tokens[1];
145 char *str_gid = strchrnul(str_uid, ':');
150 pass = getpwnam(str_uid);
154 uid = strtoul(str_uid, NULL, 10);
156 grp = getgrnam(str_gid);
160 gid = strtoul(str_gid, NULL, 10);
163 /* 3rd field: mode - device permissions */
164 mode = strtoul(tokens[2], NULL, 8);
167 /* 4th field (opt): >alias */
168 #if ENABLE_FEATURE_MDEV_RENAME
172 if (aliaslink == '>' || aliaslink == '=') {
176 s = strchr(val, ' ');
177 val = (s && s[1]) ? s+1 : NULL;
178 #if ENABLE_FEATURE_MDEV_RENAME_REGEXP
179 /* substitute %1..9 with off[1..9], if any */
186 p = alias = xzalloc(strlen(a) + n * strlen(device_name));
192 if (i <= 9 && off[i].rm_so >= 0) {
193 n = off[i].rm_eo - off[i].rm_so;
194 strncpy(p, device_name + off[i].rm_so, n);
203 alias = xstrdup(a + 1);
206 #endif /* ENABLE_FEATURE_MDEV_RENAME */
208 /* The rest (opt): command to run */
211 if (ENABLE_FEATURE_MDEV_EXEC) {
212 const char *s = "@$*";
213 const char *s2 = strchr(s, *val);
216 bb_error_msg_and_die("bad line %u", parser->lineno);
218 /* Correlate the position in the "@$*" with the delete
219 * step so that we get the proper behavior:
220 * @cmd: run on create
221 * $cmd: run on delete
224 if ((s2 - s + 1) /*1/2/3*/ & /*1/2*/ (1 + delete)) {
225 command = xstrdup(val + 1);
228 /* end of field parsing */
229 break; /* we found matching line, stop */
230 } /* end of "while line is read from /etc/mdev.conf" */
232 config_close(parser);
236 if (!delete && sscanf(dev_maj_min, "%u:%u", &major, &minor) == 2) {
238 if (ENABLE_FEATURE_MDEV_RENAME)
241 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
242 bb_perror_msg_and_die("mknod %s", device_name);
244 if (major == root_major && minor == root_minor)
245 symlink(device_name, "root");
247 if (ENABLE_FEATURE_MDEV_CONF) {
248 chown(device_name, uid, gid);
250 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
251 alias = build_alias(alias, device_name);
253 /* move the device, and optionally
254 * make a symlink to moved device node */
255 if (rename(device_name, alias) == 0 && aliaslink == '>')
256 symlink(alias, device_name);
263 if (ENABLE_FEATURE_MDEV_EXEC && command) {
264 /* setenv will leak memory, use putenv/unsetenv/free */
265 char *s = xasprintf("MDEV=%s", device_name);
267 if (system(command) == -1)
268 bb_perror_msg_and_die("can't run '%s'", command);
277 /* At creation time, device might have been moved
278 * and a symlink might have been created. Undo that. */
279 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
280 alias = build_alias(alias, device_name);
287 /* File callback for /sys/ traversal */
288 static int FAST_FUNC fileAction(const char *fileName,
289 struct stat *statbuf UNUSED_PARAM,
291 int depth UNUSED_PARAM)
293 size_t len = strlen(fileName) - 4; /* can't underflow */
294 char *scratch = userData;
296 /* len check is for paranoid reasons */
297 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
300 strcpy(scratch, fileName);
302 make_device(scratch, 0);
307 /* Directory callback for /sys/ traversal */
308 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
309 struct stat *statbuf UNUSED_PARAM,
310 void *userData UNUSED_PARAM,
313 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
316 /* For the full gory details, see linux/Documentation/firmware_class/README
318 * Firmware loading works like this:
319 * - kernel sets FIRMWARE env var
320 * - userspace checks /lib/firmware/$FIRMWARE
321 * - userspace waits for /sys/$DEVPATH/loading to appear
322 * - userspace writes "1" to /sys/$DEVPATH/loading
323 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
324 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
325 * - kernel loads firmware into device
327 static void load_firmware(const char *const firmware, const char *const sysfs_path)
330 int firmware_fd, loading_fd, data_fd;
332 /* check for /lib/firmware/$FIRMWARE */
333 xchdir("/lib/firmware");
334 firmware_fd = xopen(firmware, O_RDONLY);
336 /* in case we goto out ... */
339 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
341 for (cnt = 0; cnt < 30; ++cnt) {
342 loading_fd = open("loading", O_WRONLY);
343 if (loading_fd != -1)
350 /* tell kernel we're loading by `echo 1 > /sys/$DEVPATH/loading` */
351 if (full_write(loading_fd, "1", 1) != 1)
354 /* load firmware by `cat /lib/firmware/$FIRMWARE > /sys/$DEVPATH/data */
355 data_fd = open("data", O_WRONLY);
358 cnt = bb_copyfd_eof(firmware_fd, data_fd);
360 /* tell kernel result by `echo [0|-1] > /sys/$DEVPATH/loading` */
362 full_write(loading_fd, "0", 1);
364 full_write(loading_fd, "-1", 2);
367 if (ENABLE_FEATURE_CLEAN_UP) {
374 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
375 int mdev_main(int argc UNUSED_PARAM, char **argv)
377 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
379 /* We can be called as hotplug helper */
380 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
385 /* Replace LOGFILE by other file or device name if you need */
386 #define LOGFILE "/dev/console"
387 /* Just making sure fd 0 is not closed,
388 * we don't really intend to read from it */
389 xmove_fd(xopen("/", O_RDONLY), STDIN_FILENO);
390 xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDOUT_FILENO);
391 xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDERR_FILENO);
396 if (argv[1] && !strcmp(argv[1], "-s")) {
403 root_major = major(st.st_dev);
404 root_minor = minor(st.st_dev);
406 /* ACTION_FOLLOWLINKS is needed since in newer kernels
407 * /sys/block/loop* (for example) are symlinks to dirs,
408 * not real directories.
409 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
410 * but we can't enforce that on users) */
411 recursive_action("/sys/block",
412 ACTION_RECURSE | ACTION_FOLLOWLINKS,
413 fileAction, dirAction, temp, 0);
414 recursive_action("/sys/class",
415 ACTION_RECURSE | ACTION_FOLLOWLINKS,
416 fileAction, dirAction, temp, 0);
421 char seqbuf[sizeof(int)*3 + 2];
422 int seqlen = seqlen; /* for compiler */
425 * env ACTION=... DEVPATH=... [SEQNUM=...] mdev
426 * ACTION can be "add" or "remove"
427 * DEVPATH is like "/block/sda" or "/class/input/mice"
429 action = getenv("ACTION");
430 env_path = getenv("DEVPATH");
431 if (!action || !env_path)
434 seq = getenv("SEQNUM");
436 int timeout = 2000 / 32;
438 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
441 seqbuf[seqlen] = '\0';
442 if (seqbuf[0] == '\n' /* seed file? */
443 || strcmp(seq, seqbuf) == 0 /* correct idx? */
451 snprintf(temp, PATH_MAX, "/sys%s", env_path);
452 if (!strcmp(action, "remove"))
453 make_device(temp, 1);
454 else if (!strcmp(action, "add")) {
455 make_device(temp, 0);
457 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
458 char *fw = getenv("FIRMWARE");
460 load_firmware(fw, temp);
464 if (seq && seqlen >= 0) {
465 xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
469 if (ENABLE_FEATURE_CLEAN_UP)
470 RELEASE_CONFIG_BUFFER(temp);