mdev.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. #define MAX_SYSFS_DEPTH 3 /* prevent infinite loops in /sys symlinks */
  20. /* We use additional 64+ bytes in make_device() */
  21. #define SCRATCH_SIZE 80
  22. static char *next_field(char *s)
  23. {
  24. char *end = skip_non_whitespace(s);
  25. s = skip_whitespace(end);
  26. *end = '\0';
  27. if (*s == '\0')
  28. s = NULL;
  29. return s;
  30. }
  31. /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
  32. /* NB: "mdev -s" may call us many times, do not leak memory/fds! */
  33. static void make_device(char *path, int delete)
  34. {
  35. const char *device_name;
  36. int major, minor, type, len;
  37. int mode = 0660;
  38. uid_t uid = 0;
  39. gid_t gid = 0;
  40. char *dev_maj_min = path + strlen(path);
  41. char *command = NULL;
  42. char *alias = NULL;
  43. char aliaslink = aliaslink; /* for compiler */
  44. /* Force the configuration file settings exactly. */
  45. umask(0);
  46. /* Try to read major/minor string. Note that the kernel puts \n after
  47. * the data, so we don't need to worry about null terminating the string
  48. * because sscanf() will stop at the first nondigit, which \n is. We
  49. * also depend on path having writeable space after it.
  50. */
  51. if (!delete) {
  52. strcpy(dev_maj_min, "/dev");
  53. len = open_read_close(path, dev_maj_min + 1, 64);
  54. *dev_maj_min++ = '\0';
  55. if (len < 1) {
  56. if (!ENABLE_FEATURE_MDEV_EXEC)
  57. return;
  58. /* no "dev" file, so just try to run script */
  59. *dev_maj_min = '\0';
  60. }
  61. }
  62. /* Determine device name, type, major and minor */
  63. device_name = bb_basename(path);
  64. /* http://kernel.org/doc/pending/hotplug.txt says that only
  65. * "/sys/block/..." is for block devices. "/sys/bus" etc is not!
  66. * Since kernel 2.6.25 block devices are also in /sys/class/block. */
  67. /* TODO: would it be acceptable to just use strstr(path, "/block/")? */
  68. if (strncmp(&path[5], "class/block/"+6, 6) != 0
  69. && strncmp(&path[5], "class/block/", 12) != 0)
  70. type = S_IFCHR;
  71. else
  72. type = S_IFBLK;
  73. if (ENABLE_FEATURE_MDEV_CONF) {
  74. FILE *fp;
  75. char *line, *val, *next;
  76. unsigned lineno = 0;
  77. /* If we have config file, look up user settings */
  78. fp = fopen_or_warn("/etc/mdev.conf", "r");
  79. if (!fp)
  80. goto end_parse;
  81. while ((line = xmalloc_fgetline(fp)) != NULL) {
  82. regmatch_t off[1+9*ENABLE_FEATURE_MDEV_RENAME_REGEXP];
  83. ++lineno;
  84. trim(line);
  85. if (!line[0])
  86. goto next_line;
  87. /* Fields: regex uid:gid mode [alias] [cmd] */
  88. /* 1st field: regex to match this device */
  89. next = next_field(line);
  90. {
  91. regex_t match;
  92. int result;
  93. /* Is this it? */
  94. xregcomp(&match, line, REG_EXTENDED);
  95. result = regexec(&match, device_name, ARRAY_SIZE(off), off, 0);
  96. regfree(&match);
  97. //bb_error_msg("matches:");
  98. //for (int i = 0; i < ARRAY_SIZE(off); i++) {
  99. // if (off[i].rm_so < 0) continue;
  100. // bb_error_msg("match %d: '%.*s'\n", i,
  101. // (int)(off[i].rm_eo - off[i].rm_so),
  102. // device_name + off[i].rm_so);
  103. //}
  104. /* If not this device, skip rest of line */
  105. /* (regexec returns whole pattern as "range" 0) */
  106. if (result || off[0].rm_so
  107. || ((int)off[0].rm_eo != (int)strlen(device_name))
  108. ) {
  109. goto next_line;
  110. }
  111. }
  112. /* This line matches: stop parsing the file
  113. * after parsing the rest of fields */
  114. /* 2nd field: uid:gid - device ownership */
  115. if (!next) /* field must exist */
  116. bb_error_msg_and_die("bad line %u", lineno);
  117. val = next;
  118. next = next_field(val);
  119. {
  120. struct passwd *pass;
  121. struct group *grp;
  122. char *str_uid = val;
  123. char *str_gid = strchrnul(val, ':');
  124. if (*str_gid)
  125. *str_gid++ = '\0';
  126. /* Parse UID */
  127. pass = getpwnam(str_uid);
  128. if (pass)
  129. uid = pass->pw_uid;
  130. else
  131. uid = strtoul(str_uid, NULL, 10);
  132. /* Parse GID */
  133. grp = getgrnam(str_gid);
  134. if (grp)
  135. gid = grp->gr_gid;
  136. else
  137. gid = strtoul(str_gid, NULL, 10);
  138. }
  139. /* 3rd field: mode - device permissions */
  140. if (!next) /* field must exist */
  141. bb_error_msg_and_die("bad line %u", lineno);
  142. val = next;
  143. next = next_field(val);
  144. mode = strtoul(val, NULL, 8);
  145. /* 4th field (opt): >alias */
  146. #if ENABLE_FEATURE_MDEV_RENAME
  147. if (!next)
  148. break;
  149. if (*next == '>' || *next == '=') {
  150. #if ENABLE_FEATURE_MDEV_RENAME_REGEXP
  151. char *s, *p;
  152. unsigned i, n;
  153. aliaslink = *next;
  154. val = next;
  155. next = next_field(val);
  156. /* substitute %1..9 with off[1..9], if any */
  157. n = 0;
  158. s = val;
  159. while (*s)
  160. if (*s++ == '%')
  161. n++;
  162. p = alias = xzalloc(strlen(val) + n * strlen(device_name));
  163. s = val + 1;
  164. while (*s) {
  165. *p = *s;
  166. if ('%' == *s) {
  167. i = (s[1] - '0');
  168. if (i <= 9 && off[i].rm_so >= 0) {
  169. n = off[i].rm_eo - off[i].rm_so;
  170. strncpy(p, device_name + off[i].rm_so, n);
  171. p += n - 1;
  172. s++;
  173. }
  174. }
  175. p++;
  176. s++;
  177. }
  178. #else
  179. aliaslink = *next;
  180. val = next;
  181. next = next_field(val);
  182. alias = xstrdup(val + 1);
  183. #endif
  184. }
  185. #endif /* ENABLE_FEATURE_MDEV_RENAME */
  186. /* The rest (opt): command to run */
  187. if (!next)
  188. break;
  189. val = next;
  190. if (ENABLE_FEATURE_MDEV_EXEC) {
  191. const char *s = "@$*";
  192. const char *s2 = strchr(s, *val);
  193. if (!s2)
  194. bb_error_msg_and_die("bad line %u", lineno);
  195. /* Correlate the position in the "@$*" with the delete
  196. * step so that we get the proper behavior:
  197. * @cmd: run on create
  198. * $cmd: run on delete
  199. * *cmd: run on both
  200. */
  201. if ((s2 - s + 1) /*1/2/3*/ & /*1/2*/ (1 + delete)) {
  202. command = xstrdup(val + 1);
  203. }
  204. }
  205. /* end of field parsing */
  206. break; /* we found matching line, stop */
  207. next_line:
  208. free(line);
  209. } /* end of "while line is read from /etc/mdev.conf" */
  210. free(line); /* in case we used "break" to get here */
  211. fclose(fp);
  212. }
  213. end_parse:
  214. if (!delete && sscanf(dev_maj_min, "%u:%u", &major, &minor) == 2) {
  215. if (ENABLE_FEATURE_MDEV_RENAME)
  216. unlink(device_name);
  217. if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
  218. bb_perror_msg_and_die("mknod %s", device_name);
  219. if (major == root_major && minor == root_minor)
  220. symlink(device_name, "root");
  221. if (ENABLE_FEATURE_MDEV_CONF) {
  222. chown(device_name, uid, gid);
  223. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  224. char *dest;
  225. /* ">bar/": rename to bar/device_name */
  226. /* ">bar[/]baz": rename to bar[/]baz */
  227. dest = strrchr(alias, '/');
  228. if (dest) { /* ">bar/[baz]" ? */
  229. *dest = '\0'; /* mkdir bar */
  230. bb_make_directory(alias, 0755, FILEUTILS_RECUR);
  231. *dest = '/';
  232. if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
  233. dest = alias;
  234. alias = concat_path_file(alias, device_name);
  235. free(dest);
  236. }
  237. }
  238. /* move the device, and optionally
  239. * make a symlink to moved device node */
  240. if (rename(device_name, alias) == 0 && aliaslink == '>')
  241. symlink(alias, device_name);
  242. free(alias);
  243. }
  244. }
  245. }
  246. if (ENABLE_FEATURE_MDEV_EXEC && command) {
  247. /* setenv will leak memory, use putenv/unsetenv/free */
  248. char *s = xasprintf("MDEV=%s", device_name);
  249. putenv(s);
  250. if (system(command) == -1)
  251. bb_perror_msg_and_die("can't run '%s'", command);
  252. s[4] = '\0';
  253. unsetenv(s);
  254. free(s);
  255. free(command);
  256. }
  257. if (delete)
  258. unlink(device_name);
  259. }
  260. /* File callback for /sys/ traversal */
  261. static int fileAction(const char *fileName,
  262. struct stat *statbuf ATTRIBUTE_UNUSED,
  263. void *userData,
  264. int depth ATTRIBUTE_UNUSED)
  265. {
  266. size_t len = strlen(fileName) - 4; /* can't underflow */
  267. char *scratch = userData;
  268. /* len check is for paranoid reasons */
  269. if (strcmp(fileName + len, "/dev") || len >= PATH_MAX)
  270. return FALSE;
  271. strcpy(scratch, fileName);
  272. scratch[len] = '\0';
  273. make_device(scratch, 0);
  274. return TRUE;
  275. }
  276. /* Directory callback for /sys/ traversal */
  277. static int dirAction(const char *fileName ATTRIBUTE_UNUSED,
  278. struct stat *statbuf ATTRIBUTE_UNUSED,
  279. void *userData ATTRIBUTE_UNUSED,
  280. int depth)
  281. {
  282. return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
  283. }
  284. /* For the full gory details, see linux/Documentation/firmware_class/README
  285. *
  286. * Firmware loading works like this:
  287. * - kernel sets FIRMWARE env var
  288. * - userspace checks /lib/firmware/$FIRMWARE
  289. * - userspace waits for /sys/$DEVPATH/loading to appear
  290. * - userspace writes "1" to /sys/$DEVPATH/loading
  291. * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
  292. * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
  293. * - kernel loads firmware into device
  294. */
  295. static void load_firmware(const char *const firmware, const char *const sysfs_path)
  296. {
  297. int cnt;
  298. int firmware_fd, loading_fd, data_fd;
  299. /* check for /lib/firmware/$FIRMWARE */
  300. xchdir("/lib/firmware");
  301. firmware_fd = xopen(firmware, O_RDONLY);
  302. /* in case we goto out ... */
  303. data_fd = -1;
  304. /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
  305. xchdir(sysfs_path);
  306. for (cnt = 0; cnt < 30; ++cnt) {
  307. loading_fd = open("loading", O_WRONLY);
  308. if (loading_fd != -1)
  309. goto loading;
  310. sleep(1);
  311. }
  312. goto out;
  313. loading:
  314. /* tell kernel we're loading by `echo 1 > /sys/$DEVPATH/loading` */
  315. if (full_write(loading_fd, "1", 1) != 1)
  316. goto out;
  317. /* load firmware by `cat /lib/firmware/$FIRMWARE > /sys/$DEVPATH/data */
  318. data_fd = open("data", O_WRONLY);
  319. if (data_fd == -1)
  320. goto out;
  321. cnt = bb_copyfd_eof(firmware_fd, data_fd);
  322. /* tell kernel result by `echo [0|-1] > /sys/$DEVPATH/loading` */
  323. if (cnt > 0)
  324. full_write(loading_fd, "0", 1);
  325. else
  326. full_write(loading_fd, "-1", 2);
  327. out:
  328. if (ENABLE_FEATURE_CLEAN_UP) {
  329. close(firmware_fd);
  330. close(loading_fd);
  331. close(data_fd);
  332. }
  333. }
  334. int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  335. int mdev_main(int argc, char **argv)
  336. {
  337. char *action;
  338. char *env_path;
  339. RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
  340. #ifdef YOU_WANT_TO_DEBUG_HOTPLUG_EVENTS
  341. /* Kernel cannot provide suitable stdio fds for us, do it ourself */
  342. /* Replace LOGFILE by other file or device name if you need */
  343. #define LOGFILE "/dev/console"
  344. xmove_fd(xopen("/dev/null", O_RDONLY), STDIN_FILENO);
  345. xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDOUT_FILENO);
  346. xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDERR_FILENO);
  347. #endif
  348. xchdir("/dev");
  349. if (argc == 2 && !strcmp(argv[1], "-s")) {
  350. /* Scan:
  351. * mdev -s
  352. */
  353. struct stat st;
  354. xstat("/", &st);
  355. root_major = major(st.st_dev);
  356. root_minor = minor(st.st_dev);
  357. recursive_action("/sys/block",
  358. ACTION_RECURSE | ACTION_FOLLOWLINKS,
  359. fileAction, dirAction, temp, 0);
  360. recursive_action("/sys/class",
  361. ACTION_RECURSE | ACTION_FOLLOWLINKS,
  362. fileAction, dirAction, temp, 0);
  363. } else {
  364. /* Hotplug:
  365. * env ACTION=... DEVPATH=... mdev
  366. * ACTION can be "add" or "remove"
  367. * DEVPATH is like "/block/sda" or "/class/input/mice"
  368. */
  369. action = getenv("ACTION");
  370. env_path = getenv("DEVPATH");
  371. if (!action || !env_path)
  372. bb_show_usage();
  373. snprintf(temp, PATH_MAX, "/sys%s", env_path);
  374. if (!strcmp(action, "remove"))
  375. make_device(temp, 1);
  376. else if (!strcmp(action, "add")) {
  377. make_device(temp, 0);
  378. if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
  379. char *fw = getenv("FIRMWARE");
  380. if (fw)
  381. load_firmware(fw, temp);
  382. }
  383. }
  384. }
  385. if (ENABLE_FEATURE_CLEAN_UP)
  386. RELEASE_CONFIG_BUFFER(temp);
  387. return 0;
  388. }