mdev.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 GPL version 2, see file LICENSE in this tarball for details.
  9. */
  10. #include "libbb.h"
  11. #include "xregex.h"
  12. /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
  13. * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
  14. * contains "4:0\n". Directory name is taken as device name, path component
  15. * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
  16. * Then mdev creates the /dev/device_name node.
  17. * If /sys/class/.../dev file does not exist, mdev still may act
  18. * on this device: see "@|$|*command args..." parameter in config file.
  19. *
  20. * mdev w/o parameters is called as hotplug helper. It takes device
  21. * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
  22. * maj,min from "/sys/$DEVPATH/dev" and also examines
  23. * $ACTION ("add"/"delete") and $FIRMWARE.
  24. *
  25. * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
  26. * (todo: explain "delete" and $FIRMWARE)
  27. *
  28. * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
  29. * /etc/mdev.conf file format:
  30. *
  31. * [-][subsystem/]device user:grp mode [>|=path] [@|$|*command args...]
  32. * [-]@maj,min[-min2] user:grp mode [>|=path] [@|$|*command args...]
  33. * [-]$envvar=val user:grp mode [>|=path] [@|$|*command args...]
  34. *
  35. * Leading minus in 1st field means "don't stop on this line", otherwise
  36. * search is stopped after the matching line is encountered.
  37. *
  38. * The device name or "subsystem/device" combo is matched against 1st field
  39. * (which is a regex), or maj,min is matched against 1st field,
  40. * or specified environment variable (as regex) is matched against 1st field.
  41. *
  42. * $envvar=val format is useful for loading modules for hot-plugged devices
  43. * which do not have driver loaded yet. In this case /sys/class/.../dev
  44. * does not exist, but $MODALIAS is set to needed module's name
  45. * (actually, an alias to it) by kernel. This rule instructs mdev
  46. * to load the module and exit:
  47. * $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
  48. * The kernel will generate another hotplug event when /sys/class/.../dev
  49. * file appears.
  50. *
  51. * When line matches, the device node is created, chmod'ed and chown'ed,
  52. * moved to path, and if >path, a symlink to moved node is created,
  53. * all this if /sys/class/.../dev exists.
  54. * Examples:
  55. * =loop/ - moves to /dev/loop
  56. * >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
  57. *
  58. * Then "command args..." is executed (via sh -c 'command args...').
  59. * @:execute on creation, $:on deletion, *:on both.
  60. * This happens regardless of /sys/class/.../dev existence.
  61. */
  62. struct globals {
  63. int root_major, root_minor;
  64. char *subsystem;
  65. };
  66. #define G (*(struct globals*)&bb_common_bufsiz1)
  67. #define root_major (G.root_major)
  68. #define root_minor (G.root_minor)
  69. #define subsystem (G.subsystem )
  70. /* Prevent infinite loops in /sys symlinks */
  71. #define MAX_SYSFS_DEPTH 3
  72. /* We use additional 64+ bytes in make_device() */
  73. #define SCRATCH_SIZE 80
  74. /* Builds an alias path.
  75. * This function potentionally reallocates the alias parameter.
  76. * Only used for ENABLE_FEATURE_MDEV_RENAME
  77. */
  78. static char *build_alias(char *alias, const char *device_name)
  79. {
  80. char *dest;
  81. /* ">bar/": rename to bar/device_name */
  82. /* ">bar[/]baz": rename to bar[/]baz */
  83. dest = strrchr(alias, '/');
  84. if (dest) { /* ">bar/[baz]" ? */
  85. *dest = '\0'; /* mkdir bar */
  86. bb_make_directory(alias, 0755, FILEUTILS_RECUR);
  87. *dest = '/';
  88. if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
  89. dest = alias;
  90. alias = concat_path_file(alias, device_name);
  91. free(dest);
  92. }
  93. }
  94. return alias;
  95. }
  96. /* mknod in /dev based on a path like "/sys/block/hda/hda1"
  97. * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
  98. * after NUL, but we promise to not mangle (IOW: to restore if needed)
  99. * path string.
  100. * NB2: "mdev -s" may call us many times, do not leak memory/fds!
  101. */
  102. static void make_device(char *path, int delete)
  103. {
  104. char *device_name;
  105. int major, minor, type, len;
  106. mode_t mode;
  107. parser_t *parser;
  108. /* Try to read major/minor string. Note that the kernel puts \n after
  109. * the data, so we don't need to worry about null terminating the string
  110. * because sscanf() will stop at the first nondigit, which \n is.
  111. * We also depend on path having writeable space after it.
  112. */
  113. major = -1;
  114. if (!delete) {
  115. char *dev_maj_min = path + strlen(path);
  116. strcpy(dev_maj_min, "/dev");
  117. len = open_read_close(path, dev_maj_min + 1, 64);
  118. *dev_maj_min = '\0';
  119. if (len < 1) {
  120. if (!ENABLE_FEATURE_MDEV_EXEC)
  121. return;
  122. /* no "dev" file, but we can still run scripts
  123. * based on device name */
  124. } else if (sscanf(++dev_maj_min, "%u:%u", &major, &minor) != 2) {
  125. major = -1;
  126. }
  127. }
  128. /* Determine device name, type, major and minor */
  129. device_name = (char*) bb_basename(path);
  130. /* http://kernel.org/doc/pending/hotplug.txt says that only
  131. * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
  132. * But since 2.6.25 block devices are also in /sys/class/block,
  133. * we use strstr("/block/") to forestall future surprises. */
  134. type = S_IFCHR;
  135. if (strstr(path, "/block/"))
  136. type = S_IFBLK;
  137. /* Make path point to "subsystem/device_name" */
  138. if (path[5] == 'b') /* legacy /sys/block? */
  139. path += sizeof("/sys/") - 1;
  140. else
  141. path += sizeof("/sys/class/") - 1;
  142. /* If we have config file, look up user settings */
  143. if (ENABLE_FEATURE_MDEV_CONF)
  144. parser = config_open2("/etc/mdev.conf", fopen_for_read);
  145. do {
  146. int keep_matching;
  147. struct bb_uidgid_t ugid;
  148. char *tokens[4];
  149. char *command = NULL;
  150. char *alias = NULL;
  151. char aliaslink = aliaslink; /* for compiler */
  152. /* Defaults in case we won't match any line */
  153. ugid.uid = ugid.gid = 0;
  154. keep_matching = 0;
  155. mode = 0660;
  156. if (ENABLE_FEATURE_MDEV_CONF
  157. && config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)
  158. ) {
  159. char *val;
  160. char *str_to_match;
  161. regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
  162. val = tokens[0];
  163. keep_matching = ('-' == val[0]);
  164. val += keep_matching; /* swallow leading dash */
  165. /* Match against either "subsystem/device_name"
  166. * or "device_name" alone */
  167. str_to_match = strchr(val, '/') ? path : device_name;
  168. /* Fields: regex uid:gid mode [alias] [cmd] */
  169. if (val[0] == '@') {
  170. /* @major,minor[-minor2] */
  171. /* (useful when name is ambiguous:
  172. * "/sys/class/usb/lp0" and
  173. * "/sys/class/printer/lp0") */
  174. int cmaj, cmin0, cmin1, sc;
  175. if (major < 0)
  176. continue; /* no dev, no match */
  177. sc = sscanf(val, "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
  178. if (sc < 1 || major != cmaj
  179. || (sc == 2 && minor != cmin0)
  180. || (sc == 3 && (minor < cmin0 || minor > cmin1))
  181. ) {
  182. continue; /* this line doesn't match */
  183. }
  184. goto line_matches;
  185. }
  186. if (val[0] == '$') {
  187. /* regex to match an environment variable */
  188. char *eq = strchr(++val, '=');
  189. if (!eq)
  190. continue;
  191. *eq = '\0';
  192. str_to_match = getenv(val);
  193. if (!str_to_match)
  194. continue;
  195. str_to_match -= strlen(val) + 1;
  196. *eq = '=';
  197. }
  198. /* else: regex to match [subsystem/]device_name */
  199. {
  200. regex_t match;
  201. int result;
  202. xregcomp(&match, val, REG_EXTENDED);
  203. result = regexec(&match, str_to_match, ARRAY_SIZE(off), off, 0);
  204. regfree(&match);
  205. //bb_error_msg("matches:");
  206. //for (int i = 0; i < ARRAY_SIZE(off); i++) {
  207. // if (off[i].rm_so < 0) continue;
  208. // bb_error_msg("match %d: '%.*s'\n", i,
  209. // (int)(off[i].rm_eo - off[i].rm_so),
  210. // device_name + off[i].rm_so);
  211. //}
  212. /* If no match, skip rest of line */
  213. /* (regexec returns whole pattern as "range" 0) */
  214. if (result || off[0].rm_so
  215. || ((int)off[0].rm_eo != (int)strlen(str_to_match))
  216. ) {
  217. continue; /* this line doesn't match */
  218. }
  219. }
  220. line_matches:
  221. /* This line matches. Stop parsing after parsing
  222. * the rest the line unless keep_matching == 1 */
  223. /* 2nd field: uid:gid - device ownership */
  224. if (get_uidgid(&ugid, tokens[1], 1) == 0)
  225. bb_error_msg("unknown user/group %s on line %d", tokens[1], parser->lineno);
  226. /* 3rd field: mode - device permissions */
  227. /* mode = strtoul(tokens[2], NULL, 8); */
  228. bb_parse_mode(tokens[2], &mode);
  229. val = tokens[3];
  230. /* 4th field (opt): >|=alias */
  231. if (ENABLE_FEATURE_MDEV_RENAME && val) {
  232. aliaslink = val[0];
  233. if (aliaslink == '>' || aliaslink == '=') {
  234. char *a, *s, *st;
  235. char *p;
  236. unsigned i, n;
  237. a = val;
  238. s = strchrnul(val, ' ');
  239. st = strchrnul(val, '\t');
  240. if (st < s)
  241. s = st;
  242. val = (s[0] && s[1]) ? s+1 : NULL;
  243. s[0] = '\0';
  244. if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
  245. /* substitute %1..9 with off[1..9], if any */
  246. n = 0;
  247. s = a;
  248. while (*s)
  249. if (*s++ == '%')
  250. n++;
  251. p = alias = xzalloc(strlen(a) + n * strlen(str_to_match));
  252. s = a + 1;
  253. while (*s) {
  254. *p = *s;
  255. if ('%' == *s) {
  256. i = (s[1] - '0');
  257. if (i <= 9 && off[i].rm_so >= 0) {
  258. n = off[i].rm_eo - off[i].rm_so;
  259. strncpy(p, str_to_match + off[i].rm_so, n);
  260. p += n - 1;
  261. s++;
  262. }
  263. }
  264. p++;
  265. s++;
  266. }
  267. } else {
  268. alias = xstrdup(a + 1);
  269. }
  270. }
  271. }
  272. if (ENABLE_FEATURE_MDEV_EXEC && val) {
  273. const char *s = "$@*";
  274. const char *s2 = strchr(s, val[0]);
  275. if (!s2) {
  276. bb_error_msg("bad line %u", parser->lineno);
  277. if (ENABLE_FEATURE_MDEV_RENAME)
  278. free(alias);
  279. continue;
  280. }
  281. /* Are we running this command now?
  282. * Run $cmd on delete, @cmd on create, *cmd on both
  283. */
  284. if (s2-s != delete)
  285. command = xstrdup(val + 1);
  286. }
  287. }
  288. /* End of field parsing */
  289. /* "Execute" the line we found */
  290. {
  291. const char *node_name;
  292. node_name = device_name;
  293. if (ENABLE_FEATURE_MDEV_RENAME && alias)
  294. node_name = alias = build_alias(alias, device_name);
  295. if (!delete && major >= 0) {
  296. if (mknod(node_name, mode | type, makedev(major, minor)) && errno != EEXIST)
  297. bb_perror_msg("can't create %s", node_name);
  298. if (major == root_major && minor == root_minor)
  299. symlink(node_name, "root");
  300. if (ENABLE_FEATURE_MDEV_CONF) {
  301. chmod(node_name, mode);
  302. chown(node_name, ugid.uid, ugid.gid);
  303. }
  304. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  305. if (aliaslink == '>')
  306. symlink(node_name, device_name);
  307. }
  308. }
  309. if (ENABLE_FEATURE_MDEV_EXEC && command) {
  310. /* setenv will leak memory, use putenv/unsetenv/free */
  311. char *s = xasprintf("%s=%s", "MDEV", node_name);
  312. char *s1 = xasprintf("%s=%s", "SUBSYSTEM", subsystem);
  313. putenv(s);
  314. putenv(s1);
  315. if (system(command) == -1)
  316. bb_perror_msg("can't run '%s'", command);
  317. unsetenv("SUBSYSTEM");
  318. free(s1);
  319. unsetenv("MDEV");
  320. free(s);
  321. free(command);
  322. }
  323. if (delete) {
  324. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  325. if (aliaslink == '>')
  326. unlink(device_name);
  327. }
  328. unlink(node_name);
  329. }
  330. if (ENABLE_FEATURE_MDEV_RENAME)
  331. free(alias);
  332. }
  333. /* We found matching line.
  334. * Stop unless it was prefixed with '-' */
  335. if (ENABLE_FEATURE_MDEV_CONF && !keep_matching)
  336. break;
  337. /* end of "while line is read from /etc/mdev.conf" */
  338. } while (ENABLE_FEATURE_MDEV_CONF);
  339. if (ENABLE_FEATURE_MDEV_CONF)
  340. config_close(parser);
  341. }
  342. /* File callback for /sys/ traversal */
  343. static int FAST_FUNC fileAction(const char *fileName,
  344. struct stat *statbuf UNUSED_PARAM,
  345. void *userData,
  346. int depth UNUSED_PARAM)
  347. {
  348. size_t len = strlen(fileName) - 4; /* can't underflow */
  349. char *scratch = userData;
  350. /* len check is for paranoid reasons */
  351. if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
  352. return FALSE;
  353. strcpy(scratch, fileName);
  354. scratch[len] = '\0';
  355. make_device(scratch, 0);
  356. return TRUE;
  357. }
  358. /* Directory callback for /sys/ traversal */
  359. static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
  360. struct stat *statbuf UNUSED_PARAM,
  361. void *userData UNUSED_PARAM,
  362. int depth)
  363. {
  364. /* Extract device subsystem -- the name of the directory
  365. * under /sys/class/ */
  366. if (1 == depth) {
  367. free(subsystem);
  368. subsystem = strrchr(fileName, '/');
  369. if (subsystem)
  370. subsystem = xstrdup(subsystem + 1);
  371. }
  372. return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
  373. }
  374. /* For the full gory details, see linux/Documentation/firmware_class/README
  375. *
  376. * Firmware loading works like this:
  377. * - kernel sets FIRMWARE env var
  378. * - userspace checks /lib/firmware/$FIRMWARE
  379. * - userspace waits for /sys/$DEVPATH/loading to appear
  380. * - userspace writes "1" to /sys/$DEVPATH/loading
  381. * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
  382. * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
  383. * - kernel loads firmware into device
  384. */
  385. static void load_firmware(const char *firmware, const char *sysfs_path)
  386. {
  387. int cnt;
  388. int firmware_fd, loading_fd, data_fd;
  389. /* check for /lib/firmware/$FIRMWARE */
  390. xchdir("/lib/firmware");
  391. firmware_fd = xopen(firmware, O_RDONLY);
  392. /* in case we goto out ... */
  393. data_fd = -1;
  394. /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
  395. xchdir(sysfs_path);
  396. for (cnt = 0; cnt < 30; ++cnt) {
  397. loading_fd = open("loading", O_WRONLY);
  398. if (loading_fd != -1)
  399. goto loading;
  400. sleep(1);
  401. }
  402. goto out;
  403. loading:
  404. /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
  405. if (full_write(loading_fd, "1", 1) != 1)
  406. goto out;
  407. /* load firmware into /sys/$DEVPATH/data */
  408. data_fd = open("data", O_WRONLY);
  409. if (data_fd == -1)
  410. goto out;
  411. cnt = bb_copyfd_eof(firmware_fd, data_fd);
  412. /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
  413. if (cnt > 0)
  414. full_write(loading_fd, "0", 1);
  415. else
  416. full_write(loading_fd, "-1", 2);
  417. out:
  418. if (ENABLE_FEATURE_CLEAN_UP) {
  419. close(firmware_fd);
  420. close(loading_fd);
  421. close(data_fd);
  422. }
  423. }
  424. int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  425. int mdev_main(int argc UNUSED_PARAM, char **argv)
  426. {
  427. RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
  428. /* We can be called as hotplug helper */
  429. /* Kernel cannot provide suitable stdio fds for us, do it ourself */
  430. bb_sanitize_stdio();
  431. /* Force the configuration file settings exactly */
  432. umask(0);
  433. xchdir("/dev");
  434. if (argv[1] && strcmp(argv[1], "-s") == 0) {
  435. /* Scan:
  436. * mdev -s
  437. */
  438. struct stat st;
  439. xstat("/", &st);
  440. root_major = major(st.st_dev);
  441. root_minor = minor(st.st_dev);
  442. /* ACTION_FOLLOWLINKS is needed since in newer kernels
  443. * /sys/block/loop* (for example) are symlinks to dirs,
  444. * not real directories.
  445. * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
  446. * but we can't enforce that on users)
  447. */
  448. if (access("/sys/class/block", F_OK) != 0) {
  449. /* Scan obsolete /sys/block only if /sys/class/block
  450. * doesn't exist. Otherwise we'll have dupes.
  451. * Also, do not complain if it doesn't exist.
  452. * Some people configure kernel to have no blockdevs.
  453. */
  454. recursive_action("/sys/block",
  455. ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
  456. fileAction, dirAction, temp, 0);
  457. }
  458. recursive_action("/sys/class",
  459. ACTION_RECURSE | ACTION_FOLLOWLINKS,
  460. fileAction, dirAction, temp, 0);
  461. } else {
  462. char *fw;
  463. char *seq;
  464. char *action;
  465. char *env_path;
  466. static const char keywords[] ALIGN1 = "remove\0add\0";
  467. enum { OP_remove = 0, OP_add };
  468. smalluint op;
  469. /* Hotplug:
  470. * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
  471. * ACTION can be "add" or "remove"
  472. * DEVPATH is like "/block/sda" or "/class/input/mice"
  473. */
  474. action = getenv("ACTION");
  475. env_path = getenv("DEVPATH");
  476. subsystem = getenv("SUBSYSTEM");
  477. if (!action || !env_path /*|| !subsystem*/)
  478. bb_show_usage();
  479. fw = getenv("FIRMWARE");
  480. op = index_in_strings(keywords, action);
  481. /* If it exists, does /dev/mdev.seq match $SEQNUM?
  482. * If it does not match, earlier mdev is running
  483. * in parallel, and we need to wait */
  484. seq = getenv("SEQNUM");
  485. if (seq) {
  486. int timeout = 2000 / 32; /* 2000 msec */
  487. do {
  488. int seqlen;
  489. char seqbuf[sizeof(int)*3 + 2];
  490. seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
  491. if (seqlen < 0) {
  492. seq = NULL;
  493. break;
  494. }
  495. seqbuf[seqlen] = '\0';
  496. if (seqbuf[0] == '\n' /* seed file? */
  497. || strcmp(seq, seqbuf) == 0 /* correct idx? */
  498. ) {
  499. break;
  500. }
  501. usleep(32*1000);
  502. } while (--timeout);
  503. }
  504. snprintf(temp, PATH_MAX, "/sys%s", env_path);
  505. if (op == OP_remove) {
  506. /* Ignoring "remove firmware". It was reported
  507. * to happen and to cause erroneous deletion
  508. * of device nodes. */
  509. if (!fw)
  510. make_device(temp, 1);
  511. }
  512. else if (op == OP_add) {
  513. make_device(temp, 0);
  514. if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
  515. if (fw)
  516. load_firmware(fw, temp);
  517. }
  518. }
  519. if (seq) {
  520. xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
  521. }
  522. }
  523. if (ENABLE_FEATURE_CLEAN_UP)
  524. RELEASE_CONFIG_BUFFER(temp);
  525. return EXIT_SUCCESS;
  526. }