mdev.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. *
  4. * mdev - Mini udev for busybox
  5. *
  6. * Copyright 2005 Rob Landley <rob@landley.net>
  7. * Copyright 2005 Frank Sorenson <frank@tuxrocks.com>
  8. *
  9. * Licensed under GPL version 2, see file LICENSE in this tarball for details.
  10. */
  11. #include "libbb.h"
  12. #include "xregex.h"
  13. struct globals {
  14. int root_major, root_minor;
  15. };
  16. #define G (*(struct globals*)&bb_common_bufsiz1)
  17. #define root_major (G.root_major)
  18. #define root_minor (G.root_minor)
  19. /* Prevent infinite loops in /sys symlinks */
  20. #define MAX_SYSFS_DEPTH 3
  21. /* We use additional 64+ bytes in make_device() */
  22. #define SCRATCH_SIZE 80
  23. #if ENABLE_FEATURE_MDEV_RENAME
  24. /* Builds an alias path.
  25. * This function potentionally reallocates the alias parameter.
  26. */
  27. static char *build_alias(char *alias, const char *device_name)
  28. {
  29. char *dest;
  30. /* ">bar/": rename to bar/device_name */
  31. /* ">bar[/]baz": rename to bar[/]baz */
  32. dest = strrchr(alias, '/');
  33. if (dest) { /* ">bar/[baz]" ? */
  34. *dest = '\0'; /* mkdir bar */
  35. bb_make_directory(alias, 0755, FILEUTILS_RECUR);
  36. *dest = '/';
  37. if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
  38. dest = alias;
  39. alias = concat_path_file(alias, device_name);
  40. free(dest);
  41. }
  42. }
  43. return alias;
  44. }
  45. #endif
  46. /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
  47. /* NB: "mdev -s" may call us many times, do not leak memory/fds! */
  48. static void make_device(char *path, int delete)
  49. {
  50. const char *device_name;
  51. int major, minor, type, len;
  52. int mode = 0660;
  53. #if ENABLE_FEATURE_MDEV_CONF
  54. uid_t uid = 0;
  55. gid_t gid = 0;
  56. parser_t *parser;
  57. char *tokens[5];
  58. #endif
  59. #if ENABLE_FEATURE_MDEV_EXEC
  60. char *command = NULL;
  61. #endif
  62. #if ENABLE_FEATURE_MDEV_RENAME
  63. char *alias = NULL;
  64. char aliaslink = aliaslink; /* for compiler */
  65. #endif
  66. char *dev_maj_min = path + strlen(path);
  67. /* Force the configuration file settings exactly. */
  68. umask(0);
  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.
  73. */
  74. if (!delete) {
  75. strcpy(dev_maj_min, "/dev");
  76. len = open_read_close(path, dev_maj_min + 1, 64);
  77. *dev_maj_min++ = '\0';
  78. if (len < 1) {
  79. if (!ENABLE_FEATURE_MDEV_EXEC)
  80. return;
  81. /* no "dev" file, so just try to run script */
  82. *dev_maj_min = '\0';
  83. }
  84. }
  85. /* Determine device name, type, major and minor */
  86. device_name = bb_basename(path);
  87. /* http://kernel.org/doc/pending/hotplug.txt says that only
  88. * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
  89. * But since 2.6.25 block devices are also in /sys/class/block.
  90. * We use strstr("/block/") to forestall future surprises. */
  91. type = S_IFCHR;
  92. if (strstr(path, "/block/"))
  93. type = S_IFBLK;
  94. #if ENABLE_FEATURE_MDEV_CONF
  95. parser = config_open2("/etc/mdev.conf", fopen_for_read);
  96. /* If we have config file, look up user settings */
  97. while (config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)) {
  98. regmatch_t off[1 + 9*ENABLE_FEATURE_MDEV_RENAME_REGEXP];
  99. char *val;
  100. /* Fields: regex uid:gid mode [alias] [cmd] */
  101. /* 1st field: regex to match this device */
  102. {
  103. regex_t match;
  104. int result;
  105. /* Is this it? */
  106. xregcomp(&match, tokens[0], REG_EXTENDED);
  107. result = regexec(&match, device_name, ARRAY_SIZE(off), off, 0);
  108. regfree(&match);
  109. //bb_error_msg("matches:");
  110. //for (int i = 0; i < ARRAY_SIZE(off); i++) {
  111. // if (off[i].rm_so < 0) continue;
  112. // bb_error_msg("match %d: '%.*s'\n", i,
  113. // (int)(off[i].rm_eo - off[i].rm_so),
  114. // device_name + off[i].rm_so);
  115. //}
  116. /* If not this device, skip rest of line */
  117. /* (regexec returns whole pattern as "range" 0) */
  118. if (result || off[0].rm_so
  119. || ((int)off[0].rm_eo != (int)strlen(device_name))
  120. ) {
  121. continue;
  122. }
  123. }
  124. /* This line matches: stop parsing the file
  125. * after parsing the rest of fields */
  126. /* 2nd field: uid:gid - device ownership */
  127. {
  128. struct passwd *pass;
  129. struct group *grp;
  130. char *str_uid = tokens[1];
  131. char *str_gid = strchrnul(str_uid, ':');
  132. if (*str_gid)
  133. *str_gid++ = '\0';
  134. /* Parse UID */
  135. pass = getpwnam(str_uid);
  136. if (pass)
  137. uid = pass->pw_uid;
  138. else
  139. uid = strtoul(str_uid, NULL, 10);
  140. /* Parse GID */
  141. grp = getgrnam(str_gid);
  142. if (grp)
  143. gid = grp->gr_gid;
  144. else
  145. gid = strtoul(str_gid, NULL, 10);
  146. }
  147. /* 3rd field: mode - device permissions */
  148. mode = strtoul(tokens[2], NULL, 8);
  149. val = tokens[3];
  150. /* 4th field (opt): >alias */
  151. #if ENABLE_FEATURE_MDEV_RENAME
  152. if (!val)
  153. break;
  154. aliaslink = *val;
  155. if (aliaslink == '>' || aliaslink == '=') {
  156. char *s;
  157. #if ENABLE_FEATURE_MDEV_RENAME_REGEXP
  158. char *p;
  159. unsigned i, n;
  160. #endif
  161. char *a = val;
  162. s = strchr(val, ' ');
  163. val = (s && s[1]) ? s+1 : NULL;
  164. #if ENABLE_FEATURE_MDEV_RENAME_REGEXP
  165. /* substitute %1..9 with off[1..9], if any */
  166. n = 0;
  167. s = a;
  168. while (*s)
  169. if (*s++ == '%')
  170. n++;
  171. p = alias = xzalloc(strlen(a) + n * strlen(device_name));
  172. s = a + 1;
  173. while (*s) {
  174. *p = *s;
  175. if ('%' == *s) {
  176. i = (s[1] - '0');
  177. if (i <= 9 && off[i].rm_so >= 0) {
  178. n = off[i].rm_eo - off[i].rm_so;
  179. strncpy(p, device_name + off[i].rm_so, n);
  180. p += n - 1;
  181. s++;
  182. }
  183. }
  184. p++;
  185. s++;
  186. }
  187. #else
  188. alias = xstrdup(a + 1);
  189. #endif
  190. }
  191. #endif /* ENABLE_FEATURE_MDEV_RENAME */
  192. #if ENABLE_FEATURE_MDEV_EXEC
  193. /* The rest (opt): command to run */
  194. if (!val)
  195. break;
  196. {
  197. const char *s = "@$*";
  198. const char *s2 = strchr(s, *val);
  199. if (!s2)
  200. bb_error_msg_and_die("bad line %u", parser->lineno);
  201. /* Correlate the position in the "@$*" with the delete
  202. * step so that we get the proper behavior:
  203. * @cmd: run on create
  204. * $cmd: run on delete
  205. * *cmd: run on both
  206. */
  207. if ((s2 - s + 1) /*1/2/3*/ & /*1/2*/ (1 + delete)) {
  208. command = xstrdup(val + 1);
  209. }
  210. }
  211. #endif
  212. /* end of field parsing */
  213. break; /* we found matching line, stop */
  214. } /* end of "while line is read from /etc/mdev.conf" */
  215. config_close(parser);
  216. #endif /* ENABLE_FEATURE_MDEV_CONF */
  217. if (!delete && sscanf(dev_maj_min, "%u:%u", &major, &minor) == 2) {
  218. if (ENABLE_FEATURE_MDEV_RENAME)
  219. unlink(device_name);
  220. if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
  221. bb_perror_msg_and_die("mknod %s", device_name);
  222. if (major == root_major && minor == root_minor)
  223. symlink(device_name, "root");
  224. #if ENABLE_FEATURE_MDEV_CONF
  225. chown(device_name, uid, gid);
  226. #if ENABLE_FEATURE_MDEV_RENAME
  227. if (alias) {
  228. alias = build_alias(alias, device_name);
  229. /* move the device, and optionally
  230. * make a symlink to moved device node */
  231. if (rename(device_name, alias) == 0 && aliaslink == '>')
  232. symlink(alias, device_name);
  233. free(alias);
  234. }
  235. #endif
  236. #endif
  237. }
  238. #if ENABLE_FEATURE_MDEV_EXEC
  239. if (command) {
  240. /* setenv will leak memory, use putenv/unsetenv/free */
  241. char *s = xasprintf("MDEV=%s", device_name);
  242. putenv(s);
  243. if (system(command) == -1)
  244. bb_perror_msg_and_die("can't run '%s'", command);
  245. s[4] = '\0';
  246. unsetenv(s);
  247. free(s);
  248. free(command);
  249. }
  250. #endif
  251. if (delete) {
  252. unlink(device_name);
  253. /* At creation time, device might have been moved
  254. * and a symlink might have been created. Undo that. */
  255. #if ENABLE_FEATURE_MDEV_RENAME
  256. if (alias) {
  257. alias = build_alias(alias, device_name);
  258. unlink(alias);
  259. free(alias);
  260. }
  261. #endif
  262. }
  263. }
  264. /* File callback for /sys/ traversal */
  265. static int FAST_FUNC fileAction(const char *fileName,
  266. struct stat *statbuf UNUSED_PARAM,
  267. void *userData,
  268. int depth UNUSED_PARAM)
  269. {
  270. size_t len = strlen(fileName) - 4; /* can't underflow */
  271. char *scratch = userData;
  272. /* len check is for paranoid reasons */
  273. if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
  274. return FALSE;
  275. strcpy(scratch, fileName);
  276. scratch[len] = '\0';
  277. make_device(scratch, 0);
  278. return TRUE;
  279. }
  280. /* Directory callback for /sys/ traversal */
  281. static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
  282. struct stat *statbuf UNUSED_PARAM,
  283. void *userData UNUSED_PARAM,
  284. int depth)
  285. {
  286. return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
  287. }
  288. /* For the full gory details, see linux/Documentation/firmware_class/README
  289. *
  290. * Firmware loading works like this:
  291. * - kernel sets FIRMWARE env var
  292. * - userspace checks /lib/firmware/$FIRMWARE
  293. * - userspace waits for /sys/$DEVPATH/loading to appear
  294. * - userspace writes "1" to /sys/$DEVPATH/loading
  295. * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
  296. * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
  297. * - kernel loads firmware into device
  298. */
  299. static void load_firmware(const char *const firmware, const char *const sysfs_path)
  300. {
  301. int cnt;
  302. int firmware_fd, loading_fd, data_fd;
  303. /* check for /lib/firmware/$FIRMWARE */
  304. xchdir("/lib/firmware");
  305. firmware_fd = xopen(firmware, O_RDONLY);
  306. /* in case we goto out ... */
  307. data_fd = -1;
  308. /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
  309. xchdir(sysfs_path);
  310. for (cnt = 0; cnt < 30; ++cnt) {
  311. loading_fd = open("loading", O_WRONLY);
  312. if (loading_fd != -1)
  313. goto loading;
  314. sleep(1);
  315. }
  316. goto out;
  317. loading:
  318. /* tell kernel we're loading by `echo 1 > /sys/$DEVPATH/loading` */
  319. if (full_write(loading_fd, "1", 1) != 1)
  320. goto out;
  321. /* load firmware by `cat /lib/firmware/$FIRMWARE > /sys/$DEVPATH/data */
  322. data_fd = open("data", O_WRONLY);
  323. if (data_fd == -1)
  324. goto out;
  325. cnt = bb_copyfd_eof(firmware_fd, data_fd);
  326. /* tell kernel result by `echo [0|-1] > /sys/$DEVPATH/loading` */
  327. if (cnt > 0)
  328. full_write(loading_fd, "0", 1);
  329. else
  330. full_write(loading_fd, "-1", 2);
  331. out:
  332. if (ENABLE_FEATURE_CLEAN_UP) {
  333. close(firmware_fd);
  334. close(loading_fd);
  335. close(data_fd);
  336. }
  337. }
  338. int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  339. int mdev_main(int argc UNUSED_PARAM, char **argv)
  340. {
  341. RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
  342. /* We can be called as hotplug helper */
  343. /* Kernel cannot provide suitable stdio fds for us, do it ourself */
  344. #if 1
  345. bb_sanitize_stdio();
  346. #else
  347. /* Debug code */
  348. /* Replace LOGFILE by other file or device name if you need */
  349. #define LOGFILE "/dev/console"
  350. /* Just making sure fd 0 is not closed,
  351. * we don't really intend to read from it */
  352. xmove_fd(xopen("/", O_RDONLY), STDIN_FILENO);
  353. xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDOUT_FILENO);
  354. xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDERR_FILENO);
  355. #endif
  356. xchdir("/dev");
  357. if (argv[1] && !strcmp(argv[1], "-s")) {
  358. /* Scan:
  359. * mdev -s
  360. */
  361. struct stat st;
  362. xstat("/", &st);
  363. root_major = major(st.st_dev);
  364. root_minor = minor(st.st_dev);
  365. /* ACTION_FOLLOWLINKS is needed since in newer kernels
  366. * /sys/block/loop* (for example) are symlinks to dirs,
  367. * not real directories.
  368. * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
  369. * but we can't enforce that on users) */
  370. recursive_action("/sys/block",
  371. ACTION_RECURSE | ACTION_FOLLOWLINKS,
  372. fileAction, dirAction, temp, 0);
  373. recursive_action("/sys/class",
  374. ACTION_RECURSE | ACTION_FOLLOWLINKS,
  375. fileAction, dirAction, temp, 0);
  376. } else {
  377. char *seq;
  378. char *action;
  379. char *env_path;
  380. char seqbuf[sizeof(int)*3 + 2];
  381. int seqlen = seqlen; /* for compiler */
  382. /* Hotplug:
  383. * env ACTION=... DEVPATH=... [SEQNUM=...] mdev
  384. * ACTION can be "add" or "remove"
  385. * DEVPATH is like "/block/sda" or "/class/input/mice"
  386. */
  387. action = getenv("ACTION");
  388. env_path = getenv("DEVPATH");
  389. if (!action || !env_path)
  390. bb_show_usage();
  391. seq = getenv("SEQNUM");
  392. if (seq) {
  393. int timeout = 2000 / 32;
  394. do {
  395. seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
  396. if (seqlen < 0)
  397. break;
  398. seqbuf[seqlen] = '\0';
  399. if (seqbuf[0] == '\n' /* seed file? */
  400. || strcmp(seq, seqbuf) == 0 /* correct idx? */
  401. ) {
  402. break;
  403. }
  404. usleep(32*1000);
  405. } while (--timeout);
  406. }
  407. snprintf(temp, PATH_MAX, "/sys%s", env_path);
  408. if (!strcmp(action, "remove"))
  409. make_device(temp, 1);
  410. else if (!strcmp(action, "add")) {
  411. make_device(temp, 0);
  412. if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
  413. char *fw = getenv("FIRMWARE");
  414. if (fw)
  415. load_firmware(fw, temp);
  416. }
  417. }
  418. if (seq && seqlen >= 0) {
  419. xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
  420. }
  421. }
  422. if (ENABLE_FEATURE_CLEAN_UP)
  423. RELEASE_CONFIG_BUFFER(temp);
  424. return 0;
  425. }