mdev.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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 GPLv2, see file LICENSE in this source tree.
  9. */
  10. //config:config MDEV
  11. //config: bool "mdev (16 kb)"
  12. //config: default y
  13. //config: select PLATFORM_LINUX
  14. //config: help
  15. //config: mdev is a mini-udev implementation for dynamically creating device
  16. //config: nodes in the /dev directory.
  17. //config:
  18. //config: For more information, please see docs/mdev.txt
  19. //config:
  20. //config:config FEATURE_MDEV_CONF
  21. //config: bool "Support /etc/mdev.conf"
  22. //config: default y
  23. //config: depends on MDEV
  24. //config: help
  25. //config: Add support for the mdev config file to control ownership and
  26. //config: permissions of the device nodes.
  27. //config:
  28. //config: For more information, please see docs/mdev.txt
  29. //config:
  30. //config:config FEATURE_MDEV_RENAME
  31. //config: bool "Support subdirs/symlinks"
  32. //config: default y
  33. //config: depends on FEATURE_MDEV_CONF
  34. //config: help
  35. //config: Add support for renaming devices and creating symlinks.
  36. //config:
  37. //config: For more information, please see docs/mdev.txt
  38. //config:
  39. //config:config FEATURE_MDEV_RENAME_REGEXP
  40. //config: bool "Support regular expressions substitutions when renaming device"
  41. //config: default y
  42. //config: depends on FEATURE_MDEV_RENAME
  43. //config: help
  44. //config: Add support for regular expressions substitutions when renaming
  45. //config: device.
  46. //config:
  47. //config:config FEATURE_MDEV_EXEC
  48. //config: bool "Support command execution at device addition/removal"
  49. //config: default y
  50. //config: depends on FEATURE_MDEV_CONF
  51. //config: help
  52. //config: This adds support for an optional field to /etc/mdev.conf for
  53. //config: executing commands when devices are created/removed.
  54. //config:
  55. //config: For more information, please see docs/mdev.txt
  56. //config:
  57. //config:config FEATURE_MDEV_LOAD_FIRMWARE
  58. //config: bool "Support loading of firmware"
  59. //config: default y
  60. //config: depends on MDEV
  61. //config: help
  62. //config: Some devices need to load firmware before they can be usable.
  63. //config:
  64. //config: These devices will request userspace look up the files in
  65. //config: /lib/firmware/ and if it exists, send it to the kernel for
  66. //config: loading into the hardware.
  67. //applet:IF_MDEV(APPLET(mdev, BB_DIR_SBIN, BB_SUID_DROP))
  68. //kbuild:lib-$(CONFIG_MDEV) += mdev.o
  69. //usage:#define mdev_trivial_usage
  70. //usage: "[-s]"
  71. //usage:#define mdev_full_usage "\n\n"
  72. //usage: "mdev -s is to be run during boot to scan /sys and populate /dev.\n"
  73. //usage: "\n"
  74. //usage: "Bare mdev is a kernel hotplug helper. To activate it:\n"
  75. //usage: " echo /sbin/mdev >/proc/sys/kernel/hotplug\n"
  76. //usage: IF_FEATURE_MDEV_CONF(
  77. //usage: "\n"
  78. //usage: "It uses /etc/mdev.conf with lines\n"
  79. //usage: " [-][ENV=regex;]...DEVNAME UID:GID PERM"
  80. //usage: IF_FEATURE_MDEV_RENAME(" [>|=PATH]|[!]")
  81. //usage: IF_FEATURE_MDEV_EXEC(" [@|$|*PROG]")
  82. //usage: "\n"
  83. //usage: "where DEVNAME is device name regex, @major,minor[-minor2], or\n"
  84. //usage: "environment variable regex. A common use of the latter is\n"
  85. //usage: "to load modules for hotplugged devices:\n"
  86. //usage: " $MODALIAS=.* 0:0 660 @modprobe \"$MODALIAS\"\n"
  87. //usage: )
  88. //usage: "\n"
  89. //usage: "If /dev/mdev.seq file exists, mdev will wait for its value\n"
  90. //usage: "to match $SEQNUM variable. This prevents plug/unplug races.\n"
  91. //usage: "To activate this feature, create empty /dev/mdev.seq at boot.\n"
  92. //usage: "\n"
  93. //usage: "If /dev/mdev.log file exists, debug log will be appended to it."
  94. #include "libbb.h"
  95. #include "common_bufsiz.h"
  96. #include "xregex.h"
  97. /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
  98. * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
  99. * contains "4:0\n". Directory name is taken as device name, path component
  100. * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
  101. * Then mdev creates the /dev/device_name node.
  102. * If /sys/class/.../dev file does not exist, mdev still may act
  103. * on this device: see "@|$|*command args..." parameter in config file.
  104. *
  105. * mdev w/o parameters is called as hotplug helper. It takes device
  106. * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
  107. * maj,min from "/sys/$DEVPATH/dev" and also examines
  108. * $ACTION ("add"/"delete") and $FIRMWARE.
  109. *
  110. * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
  111. * (todo: explain "delete" and $FIRMWARE)
  112. *
  113. * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
  114. *
  115. * Leading minus in 1st field means "don't stop on this line", otherwise
  116. * search is stopped after the matching line is encountered.
  117. *
  118. * $envvar=regex format is useful for loading modules for hot-plugged devices
  119. * which do not have driver loaded yet. In this case /sys/class/.../dev
  120. * does not exist, but $MODALIAS is set to needed module's name
  121. * (actually, an alias to it) by kernel. This rule instructs mdev
  122. * to load the module and exit:
  123. * $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
  124. * The kernel will generate another hotplug event when /sys/class/.../dev
  125. * file appears.
  126. *
  127. * When line matches, the device node is created, chmod'ed and chown'ed,
  128. * moved to path, and if >path, a symlink to moved node is created,
  129. * all this if /sys/class/.../dev exists.
  130. * Examples:
  131. * =loop/ - moves to /dev/loop
  132. * >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
  133. *
  134. * Then "command args..." is executed (via sh -c 'command args...').
  135. * @:execute on creation, $:on deletion, *:on both.
  136. * This happens regardless of /sys/class/.../dev existence.
  137. */
  138. /* Kernel's hotplug environment constantly changes.
  139. * Here are new cases I observed on 3.1.0:
  140. *
  141. * Case with $DEVNAME and $DEVICE, not just $DEVPATH:
  142. * ACTION=add
  143. * BUSNUM=001
  144. * DEVICE=/proc/bus/usb/001/003
  145. * DEVNAME=bus/usb/001/003
  146. * DEVNUM=003
  147. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5
  148. * DEVTYPE=usb_device
  149. * MAJOR=189
  150. * MINOR=2
  151. * PRODUCT=18d1/4e12/227
  152. * SUBSYSTEM=usb
  153. * TYPE=0/0/0
  154. *
  155. * Case with $DEVICE, but no $DEVNAME - apparenty, usb iface notification?
  156. * "Please load me a module" thing?
  157. * ACTION=add
  158. * DEVICE=/proc/bus/usb/001/003
  159. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0
  160. * DEVTYPE=usb_interface
  161. * INTERFACE=8/6/80
  162. * MODALIAS=usb:v18D1p4E12d0227dc00dsc00dp00ic08isc06ip50
  163. * PRODUCT=18d1/4e12/227
  164. * SUBSYSTEM=usb
  165. * TYPE=0/0/0
  166. *
  167. * ACTION=add
  168. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5
  169. * DEVTYPE=scsi_host
  170. * SUBSYSTEM=scsi
  171. *
  172. * ACTION=add
  173. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/scsi_host/host5
  174. * SUBSYSTEM=scsi_host
  175. *
  176. * ACTION=add
  177. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0
  178. * DEVTYPE=scsi_target
  179. * SUBSYSTEM=scsi
  180. *
  181. * Case with strange $MODALIAS:
  182. * ACTION=add
  183. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0
  184. * DEVTYPE=scsi_device
  185. * MODALIAS=scsi:t-0x00
  186. * SUBSYSTEM=scsi
  187. *
  188. * ACTION=add
  189. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/scsi_disk/5:0:0:0
  190. * SUBSYSTEM=scsi_disk
  191. *
  192. * ACTION=add
  193. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/scsi_device/5:0:0:0
  194. * SUBSYSTEM=scsi_device
  195. *
  196. * Case with explicit $MAJOR/$MINOR (no need to read /sys/$DEVPATH/dev?):
  197. * ACTION=add
  198. * DEVNAME=bsg/5:0:0:0
  199. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/bsg/5:0:0:0
  200. * MAJOR=253
  201. * MINOR=1
  202. * SUBSYSTEM=bsg
  203. *
  204. * ACTION=add
  205. * DEVPATH=/devices/virtual/bdi/8:16
  206. * SUBSYSTEM=bdi
  207. *
  208. * ACTION=add
  209. * DEVNAME=sdb
  210. * DEVPATH=/block/sdb
  211. * DEVTYPE=disk
  212. * MAJOR=8
  213. * MINOR=16
  214. * SUBSYSTEM=block
  215. *
  216. * Case with ACTION=change:
  217. * ACTION=change
  218. * DEVNAME=sdb
  219. * DEVPATH=/block/sdb
  220. * DEVTYPE=disk
  221. * DISK_MEDIA_CHANGE=1
  222. * MAJOR=8
  223. * MINOR=16
  224. * SUBSYSTEM=block
  225. */
  226. #define DEBUG_LVL 2
  227. #if DEBUG_LVL >= 1
  228. # define dbg1(...) do { if (G.verbose) bb_error_msg(__VA_ARGS__); } while(0)
  229. #else
  230. # define dbg1(...) ((void)0)
  231. #endif
  232. #if DEBUG_LVL >= 2
  233. # define dbg2(...) do { if (G.verbose >= 2) bb_error_msg(__VA_ARGS__); } while(0)
  234. #else
  235. # define dbg2(...) ((void)0)
  236. #endif
  237. #if DEBUG_LVL >= 3
  238. # define dbg3(...) do { if (G.verbose >= 3) bb_error_msg(__VA_ARGS__); } while(0)
  239. #else
  240. # define dbg3(...) ((void)0)
  241. #endif
  242. static const char keywords[] ALIGN1 = "add\0remove\0"; // "change\0"
  243. enum { OP_add, OP_remove };
  244. struct envmatch {
  245. struct envmatch *next;
  246. char *envname;
  247. regex_t match;
  248. };
  249. struct rule {
  250. bool keep_matching;
  251. bool regex_compiled;
  252. mode_t mode;
  253. int maj, min0, min1;
  254. struct bb_uidgid_t ugid;
  255. char *envvar;
  256. char *ren_mov;
  257. IF_FEATURE_MDEV_EXEC(char *r_cmd;)
  258. regex_t match;
  259. struct envmatch *envmatch;
  260. };
  261. struct globals {
  262. int root_major, root_minor;
  263. smallint verbose;
  264. char *subsystem;
  265. char *subsys_env; /* for putenv("SUBSYSTEM=subsystem") */
  266. #if ENABLE_FEATURE_MDEV_CONF
  267. const char *filename;
  268. parser_t *parser;
  269. struct rule **rule_vec;
  270. unsigned rule_idx;
  271. #endif
  272. struct rule cur_rule;
  273. char timestr[sizeof("HH:MM:SS.123456")];
  274. } FIX_ALIASING;
  275. #define G (*(struct globals*)bb_common_bufsiz1)
  276. #define INIT_G() do { \
  277. setup_common_bufsiz(); \
  278. IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.maj = -1;) \
  279. IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.mode = 0660;) \
  280. } while (0)
  281. /* Prevent infinite loops in /sys symlinks */
  282. #define MAX_SYSFS_DEPTH 3
  283. /* We use additional bytes in make_device() */
  284. #define SCRATCH_SIZE 128
  285. #if ENABLE_FEATURE_MDEV_CONF
  286. static void make_default_cur_rule(void)
  287. {
  288. memset(&G.cur_rule, 0, sizeof(G.cur_rule));
  289. G.cur_rule.maj = -1; /* "not a @major,minor rule" */
  290. G.cur_rule.mode = 0660;
  291. }
  292. static void clean_up_cur_rule(void)
  293. {
  294. struct envmatch *e;
  295. free(G.cur_rule.envvar);
  296. free(G.cur_rule.ren_mov);
  297. if (G.cur_rule.regex_compiled)
  298. regfree(&G.cur_rule.match);
  299. IF_FEATURE_MDEV_EXEC(free(G.cur_rule.r_cmd);)
  300. e = G.cur_rule.envmatch;
  301. while (e) {
  302. free(e->envname);
  303. regfree(&e->match);
  304. e = e->next;
  305. }
  306. make_default_cur_rule();
  307. }
  308. static char *parse_envmatch_pfx(char *val)
  309. {
  310. struct envmatch **nextp = &G.cur_rule.envmatch;
  311. for (;;) {
  312. struct envmatch *e;
  313. char *semicolon;
  314. char *eq = strchr(val, '=');
  315. if (!eq /* || eq == val? */)
  316. return val;
  317. if (endofname(val) != eq)
  318. return val;
  319. semicolon = strchr(eq, ';');
  320. if (!semicolon)
  321. return val;
  322. /* ENVVAR=regex;... */
  323. *nextp = e = xzalloc(sizeof(*e));
  324. nextp = &e->next;
  325. e->envname = xstrndup(val, eq - val);
  326. *semicolon = '\0';
  327. xregcomp(&e->match, eq + 1, REG_EXTENDED);
  328. *semicolon = ';';
  329. val = semicolon + 1;
  330. }
  331. }
  332. static void parse_next_rule(void)
  333. {
  334. /* Note: on entry, G.cur_rule is set to default */
  335. while (1) {
  336. char *tokens[4];
  337. char *val;
  338. /* No PARSE_EOL_COMMENTS, because command may contain '#' chars */
  339. if (!config_read(G.parser, tokens, 4, 3, "# \t", PARSE_NORMAL & ~PARSE_EOL_COMMENTS))
  340. break;
  341. /* Fields: [-]regex uid:gid mode [alias] [cmd] */
  342. dbg3("token1:'%s'", tokens[1]);
  343. /* 1st field */
  344. val = tokens[0];
  345. G.cur_rule.keep_matching = ('-' == val[0]);
  346. val += G.cur_rule.keep_matching; /* swallow leading dash */
  347. val = parse_envmatch_pfx(val);
  348. if (val[0] == '@') {
  349. /* @major,minor[-minor2] */
  350. /* (useful when name is ambiguous:
  351. * "/sys/class/usb/lp0" and
  352. * "/sys/class/printer/lp0")
  353. */
  354. int sc = sscanf(val, "@%u,%u-%u", &G.cur_rule.maj, &G.cur_rule.min0, &G.cur_rule.min1);
  355. if (sc < 2 || G.cur_rule.maj < 0) {
  356. bb_error_msg("bad @maj,min on line %d", G.parser->lineno);
  357. goto next_rule;
  358. }
  359. if (sc == 2)
  360. G.cur_rule.min1 = G.cur_rule.min0;
  361. } else {
  362. char *eq = strchr(val, '=');
  363. if (val[0] == '$') {
  364. /* $ENVVAR=regex ... */
  365. val++;
  366. if (!eq) {
  367. bb_error_msg("bad $envvar=regex on line %d", G.parser->lineno);
  368. goto next_rule;
  369. }
  370. G.cur_rule.envvar = xstrndup(val, eq - val);
  371. val = eq + 1;
  372. }
  373. xregcomp(&G.cur_rule.match, val, REG_EXTENDED);
  374. G.cur_rule.regex_compiled = 1;
  375. }
  376. /* 2nd field: uid:gid - device ownership */
  377. if (get_uidgid(&G.cur_rule.ugid, tokens[1]) == 0) {
  378. bb_error_msg("unknown user/group '%s' on line %d", tokens[1], G.parser->lineno);
  379. goto next_rule;
  380. }
  381. /* 3rd field: mode - device permissions */
  382. G.cur_rule.mode = bb_parse_mode(tokens[2], G.cur_rule.mode);
  383. /* 4th field (opt): ">|=alias" or "!" to not create the node */
  384. val = tokens[3];
  385. if (ENABLE_FEATURE_MDEV_RENAME && val && strchr(">=!", val[0])) {
  386. char *s = skip_non_whitespace(val);
  387. G.cur_rule.ren_mov = xstrndup(val, s - val);
  388. val = skip_whitespace(s);
  389. }
  390. if (ENABLE_FEATURE_MDEV_EXEC && val && val[0]) {
  391. const char *s = "$@*";
  392. const char *s2 = strchr(s, val[0]);
  393. if (!s2) {
  394. bb_error_msg("bad line %u", G.parser->lineno);
  395. goto next_rule;
  396. }
  397. IF_FEATURE_MDEV_EXEC(G.cur_rule.r_cmd = xstrdup(val);)
  398. }
  399. return;
  400. next_rule:
  401. clean_up_cur_rule();
  402. } /* while (config_read) */
  403. dbg3("config_close(G.parser)");
  404. config_close(G.parser);
  405. G.parser = NULL;
  406. return;
  407. }
  408. /* If mdev -s, we remember rules in G.rule_vec[].
  409. * Otherwise, there is no point in doing it, and we just
  410. * save only one parsed rule in G.cur_rule.
  411. */
  412. static const struct rule *next_rule(void)
  413. {
  414. struct rule *rule;
  415. /* Open conf file if we didn't do it yet */
  416. if (!G.parser && G.filename) {
  417. dbg3("config_open('%s')", G.filename);
  418. G.parser = config_open2(G.filename, fopen_for_read);
  419. G.filename = NULL;
  420. }
  421. if (G.rule_vec) {
  422. /* mdev -s */
  423. /* Do we have rule parsed already? */
  424. if (G.rule_vec[G.rule_idx]) {
  425. dbg3("< G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
  426. return G.rule_vec[G.rule_idx++];
  427. }
  428. make_default_cur_rule();
  429. } else {
  430. /* not mdev -s */
  431. clean_up_cur_rule();
  432. }
  433. /* Parse one more rule if file isn't fully read */
  434. rule = &G.cur_rule;
  435. if (G.parser) {
  436. parse_next_rule();
  437. if (G.rule_vec) { /* mdev -s */
  438. rule = xmemdup(&G.cur_rule, sizeof(G.cur_rule));
  439. G.rule_vec = xrealloc_vector(G.rule_vec, 4, G.rule_idx);
  440. G.rule_vec[G.rule_idx++] = rule;
  441. dbg3("> G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
  442. }
  443. }
  444. return rule;
  445. }
  446. static int env_matches(struct envmatch *e)
  447. {
  448. while (e) {
  449. int r;
  450. char *val = getenv(e->envname);
  451. if (!val)
  452. return 0;
  453. r = regexec(&e->match, val, /*size*/ 0, /*range[]*/ NULL, /*eflags*/ 0);
  454. if (r != 0) /* no match */
  455. return 0;
  456. e = e->next;
  457. }
  458. return 1;
  459. }
  460. #else
  461. # define next_rule() (&G.cur_rule)
  462. #endif
  463. static void mkdir_recursive(char *name)
  464. {
  465. /* if name has many levels ("dir1/dir2"),
  466. * bb_make_directory() will create dir1 according to umask,
  467. * not according to its "mode" parameter.
  468. * Since we run with umask=0, need to temporarily switch it.
  469. */
  470. umask(022); /* "dir1" (if any) will be 0755 too */
  471. bb_make_directory(name, 0755, FILEUTILS_RECUR);
  472. umask(0);
  473. }
  474. /* Builds an alias path.
  475. * This function potentionally reallocates the alias parameter.
  476. * Only used for ENABLE_FEATURE_MDEV_RENAME
  477. */
  478. static char *build_alias(char *alias, const char *device_name)
  479. {
  480. char *dest;
  481. /* ">bar/": rename to bar/device_name */
  482. /* ">bar[/]baz": rename to bar[/]baz */
  483. dest = strrchr(alias, '/');
  484. if (dest) { /* ">bar/[baz]" ? */
  485. *dest = '\0'; /* mkdir bar */
  486. mkdir_recursive(alias);
  487. *dest = '/';
  488. if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
  489. dest = alias;
  490. alias = concat_path_file(alias, device_name);
  491. free(dest);
  492. }
  493. }
  494. return alias;
  495. }
  496. /* mknod in /dev based on a path like "/sys/block/hda/hda1"
  497. * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
  498. * after NUL, but we promise to not mangle it (IOW: to restore NUL if needed).
  499. * NB2: "mdev -s" may call us many times, do not leak memory/fds!
  500. *
  501. * device_name = $DEVNAME (may be NULL)
  502. * path = /sys/$DEVPATH
  503. */
  504. static void make_device(char *device_name, char *path, int operation)
  505. {
  506. int major, minor, type, len;
  507. char *path_end = path + strlen(path);
  508. /* Try to read major/minor string. Note that the kernel puts \n after
  509. * the data, so we don't need to worry about null terminating the string
  510. * because sscanf() will stop at the first nondigit, which \n is.
  511. * We also depend on path having writeable space after it.
  512. */
  513. major = -1;
  514. if (operation == OP_add) {
  515. strcpy(path_end, "/dev");
  516. len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
  517. *path_end = '\0';
  518. if (len < 1) {
  519. if (!ENABLE_FEATURE_MDEV_EXEC)
  520. return;
  521. /* no "dev" file, but we can still run scripts
  522. * based on device name */
  523. } else if (sscanf(path_end + 1, "%u:%u", &major, &minor) == 2) {
  524. dbg1("dev %u,%u", major, minor);
  525. } else {
  526. major = -1;
  527. }
  528. }
  529. /* else: for delete, -1 still deletes the node, but < -1 suppresses that */
  530. /* Determine device name */
  531. if (!device_name) {
  532. /*
  533. * There was no $DEVNAME envvar (for example, mdev -s never has).
  534. * But it is very useful: it contains the *path*, not only basename,
  535. * Thankfully, uevent file has it.
  536. * Example of .../sound/card0/controlC0/uevent file on Linux-3.7.7:
  537. * MAJOR=116
  538. * MINOR=7
  539. * DEVNAME=snd/controlC0
  540. */
  541. strcpy(path_end, "/uevent");
  542. len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
  543. if (len < 0)
  544. len = 0;
  545. *path_end = '\0';
  546. path_end[1 + len] = '\0';
  547. device_name = strstr(path_end + 1, "\nDEVNAME=");
  548. if (device_name) {
  549. device_name += sizeof("\nDEVNAME=")-1;
  550. strchrnul(device_name, '\n')[0] = '\0';
  551. } else {
  552. /* Fall back to just basename */
  553. device_name = (char*) bb_basename(path);
  554. }
  555. }
  556. /* Determine device type */
  557. /*
  558. * http://kernel.org/doc/pending/hotplug.txt says that only
  559. * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
  560. * But since 2.6.25 block devices are also in /sys/class/block.
  561. * We use strstr("/block/") to forestall future surprises.
  562. */
  563. type = S_IFCHR;
  564. if (strstr(path, "/block/") || (G.subsystem && is_prefixed_with(G.subsystem, "block")))
  565. type = S_IFBLK;
  566. #if ENABLE_FEATURE_MDEV_CONF
  567. G.rule_idx = 0; /* restart from the beginning (think mdev -s) */
  568. #endif
  569. for (;;) {
  570. const char *str_to_match;
  571. regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
  572. char *command;
  573. char *alias;
  574. char aliaslink = aliaslink; /* for compiler */
  575. char *node_name;
  576. const struct rule *rule;
  577. str_to_match = device_name;
  578. rule = next_rule();
  579. #if ENABLE_FEATURE_MDEV_CONF
  580. if (!env_matches(rule->envmatch))
  581. continue;
  582. if (rule->maj >= 0) { /* @maj,min rule */
  583. if (major != rule->maj)
  584. continue;
  585. if (minor < rule->min0 || minor > rule->min1)
  586. continue;
  587. memset(off, 0, sizeof(off));
  588. goto rule_matches;
  589. }
  590. if (rule->envvar) { /* $envvar=regex rule */
  591. str_to_match = getenv(rule->envvar);
  592. dbg3("getenv('%s'):'%s'", rule->envvar, str_to_match);
  593. if (!str_to_match)
  594. continue;
  595. }
  596. /* else: str_to_match = device_name */
  597. if (rule->regex_compiled) {
  598. int regex_match = regexec(&rule->match, str_to_match, ARRAY_SIZE(off), off, 0);
  599. dbg3("regex_match for '%s':%d", str_to_match, regex_match);
  600. //bb_error_msg("matches:");
  601. //for (int i = 0; i < ARRAY_SIZE(off); i++) {
  602. // if (off[i].rm_so < 0) continue;
  603. // bb_error_msg("match %d: '%.*s'\n", i,
  604. // (int)(off[i].rm_eo - off[i].rm_so),
  605. // device_name + off[i].rm_so);
  606. //}
  607. if (regex_match != 0
  608. /* regexec returns whole pattern as "range" 0 */
  609. || off[0].rm_so != 0
  610. || (int)off[0].rm_eo != (int)strlen(str_to_match)
  611. ) {
  612. continue; /* this rule doesn't match */
  613. }
  614. }
  615. /* else: it's final implicit "match-all" rule */
  616. rule_matches:
  617. dbg2("rule matched, line %d", G.parser ? G.parser->lineno : -1);
  618. #endif
  619. /* Build alias name */
  620. alias = NULL;
  621. if (ENABLE_FEATURE_MDEV_RENAME && rule->ren_mov) {
  622. aliaslink = rule->ren_mov[0];
  623. if (aliaslink == '!') {
  624. /* "!": suppress node creation/deletion */
  625. major = -2;
  626. }
  627. else if (aliaslink == '>' || aliaslink == '=') {
  628. if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
  629. char *s;
  630. char *p;
  631. unsigned n;
  632. /* substitute %1..9 with off[1..9], if any */
  633. n = 0;
  634. s = rule->ren_mov;
  635. while (*s)
  636. if (*s++ == '%')
  637. n++;
  638. p = alias = xzalloc(strlen(rule->ren_mov) + n * strlen(str_to_match));
  639. s = rule->ren_mov + 1;
  640. while (*s) {
  641. *p = *s;
  642. if ('%' == *s) {
  643. unsigned i = (s[1] - '0');
  644. if (i <= 9 && off[i].rm_so >= 0) {
  645. n = off[i].rm_eo - off[i].rm_so;
  646. strncpy(p, str_to_match + off[i].rm_so, n);
  647. p += n - 1;
  648. s++;
  649. }
  650. }
  651. p++;
  652. s++;
  653. }
  654. } else {
  655. alias = xstrdup(rule->ren_mov + 1);
  656. }
  657. }
  658. }
  659. dbg3("alias:'%s'", alias);
  660. command = NULL;
  661. IF_FEATURE_MDEV_EXEC(command = rule->r_cmd;)
  662. if (command) {
  663. /* Are we running this command now?
  664. * Run @cmd on create, $cmd on delete, *cmd on any
  665. */
  666. if ((command[0] == '@' && operation == OP_add)
  667. || (command[0] == '$' && operation == OP_remove)
  668. || (command[0] == '*')
  669. ) {
  670. command++;
  671. } else {
  672. command = NULL;
  673. }
  674. }
  675. dbg3("command:'%s'", command);
  676. /* "Execute" the line we found */
  677. node_name = device_name;
  678. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  679. node_name = alias = build_alias(alias, device_name);
  680. dbg3("alias2:'%s'", alias);
  681. }
  682. if (operation == OP_add && major >= 0) {
  683. char *slash = strrchr(node_name, '/');
  684. if (slash) {
  685. *slash = '\0';
  686. mkdir_recursive(node_name);
  687. *slash = '/';
  688. }
  689. if (ENABLE_FEATURE_MDEV_CONF) {
  690. dbg1("mknod %s (%d,%d) %o"
  691. " %u:%u",
  692. node_name, major, minor, rule->mode | type,
  693. rule->ugid.uid, rule->ugid.gid
  694. );
  695. } else {
  696. dbg1("mknod %s (%d,%d) %o",
  697. node_name, major, minor, rule->mode | type
  698. );
  699. }
  700. if (mknod(node_name, rule->mode | type, makedev(major, minor)) && errno != EEXIST)
  701. bb_perror_msg("can't create '%s'", node_name);
  702. if (ENABLE_FEATURE_MDEV_CONF) {
  703. chmod(node_name, rule->mode);
  704. chown(node_name, rule->ugid.uid, rule->ugid.gid);
  705. }
  706. if (major == G.root_major && minor == G.root_minor)
  707. symlink(node_name, "root");
  708. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  709. if (aliaslink == '>') {
  710. //TODO: on devtmpfs, device_name already exists and symlink() fails.
  711. //End result is that instead of symlink, we have two nodes.
  712. //What should be done?
  713. dbg1("symlink: %s", device_name);
  714. symlink(node_name, device_name);
  715. }
  716. }
  717. }
  718. if (ENABLE_FEATURE_MDEV_EXEC && command) {
  719. /* setenv will leak memory, use putenv/unsetenv/free */
  720. char *s = xasprintf("%s=%s", "MDEV", node_name);
  721. putenv(s);
  722. dbg1("running: %s", command);
  723. if (system(command) == -1)
  724. bb_perror_msg("can't run '%s'", command);
  725. bb_unsetenv_and_free(s);
  726. }
  727. if (operation == OP_remove && major >= -1) {
  728. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  729. if (aliaslink == '>') {
  730. dbg1("unlink: %s", device_name);
  731. unlink(device_name);
  732. }
  733. }
  734. dbg1("unlink: %s", node_name);
  735. unlink(node_name);
  736. }
  737. if (ENABLE_FEATURE_MDEV_RENAME)
  738. free(alias);
  739. /* We found matching line.
  740. * Stop unless it was prefixed with '-'
  741. */
  742. if (!ENABLE_FEATURE_MDEV_CONF || !rule->keep_matching)
  743. break;
  744. } /* for (;;) */
  745. }
  746. /* File callback for /sys/ traversal.
  747. * We act only on "/sys/.../dev" (pseudo)file
  748. */
  749. static int FAST_FUNC fileAction(const char *fileName,
  750. struct stat *statbuf UNUSED_PARAM,
  751. void *userData,
  752. int depth UNUSED_PARAM)
  753. {
  754. size_t len = strlen(fileName) - 4; /* can't underflow */
  755. char *path = userData; /* char array[PATH_MAX + SCRATCH_SIZE] */
  756. char subsys[PATH_MAX];
  757. int res;
  758. /* Is it a ".../dev" file? (len check is for paranoid reasons) */
  759. if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX - 32)
  760. return FALSE; /* not .../dev */
  761. strcpy(path, fileName);
  762. path[len] = '\0';
  763. /* Read ".../subsystem" symlink in the same directory where ".../dev" is */
  764. strcpy(subsys, path);
  765. strcpy(subsys + len, "/subsystem");
  766. res = readlink(subsys, subsys, sizeof(subsys)-1);
  767. if (res > 0) {
  768. subsys[res] = '\0';
  769. free(G.subsystem);
  770. if (G.subsys_env) {
  771. bb_unsetenv_and_free(G.subsys_env);
  772. G.subsys_env = NULL;
  773. }
  774. /* Set G.subsystem and $SUBSYSTEM from symlink's last component */
  775. G.subsystem = strrchr(subsys, '/');
  776. if (G.subsystem) {
  777. G.subsystem = xstrdup(G.subsystem + 1);
  778. G.subsys_env = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
  779. putenv(G.subsys_env);
  780. }
  781. }
  782. make_device(/*DEVNAME:*/ NULL, path, OP_add);
  783. return TRUE;
  784. }
  785. /* Directory callback for /sys/ traversal */
  786. static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
  787. struct stat *statbuf UNUSED_PARAM,
  788. void *userData UNUSED_PARAM,
  789. int depth)
  790. {
  791. return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
  792. }
  793. /* For the full gory details, see linux/Documentation/firmware_class/README
  794. *
  795. * Firmware loading works like this:
  796. * - kernel sets FIRMWARE env var
  797. * - userspace checks /lib/firmware/$FIRMWARE
  798. * - userspace waits for /sys/$DEVPATH/loading to appear
  799. * - userspace writes "1" to /sys/$DEVPATH/loading
  800. * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
  801. * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
  802. * - kernel loads firmware into device
  803. */
  804. static void load_firmware(const char *firmware, const char *sysfs_path)
  805. {
  806. int cnt;
  807. int firmware_fd, loading_fd;
  808. /* check for /lib/firmware/$FIRMWARE */
  809. firmware_fd = -1;
  810. if (chdir("/lib/firmware") == 0)
  811. firmware_fd = open(firmware, O_RDONLY); /* can fail */
  812. /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
  813. xchdir(sysfs_path);
  814. for (cnt = 0; cnt < 30; ++cnt) {
  815. loading_fd = open("loading", O_WRONLY);
  816. if (loading_fd >= 0)
  817. goto loading;
  818. sleep(1);
  819. }
  820. goto out;
  821. loading:
  822. cnt = 0;
  823. if (firmware_fd >= 0) {
  824. int data_fd;
  825. /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
  826. if (full_write(loading_fd, "1", 1) != 1)
  827. goto out;
  828. /* load firmware into /sys/$DEVPATH/data */
  829. data_fd = open("data", O_WRONLY);
  830. if (data_fd < 0)
  831. goto out;
  832. cnt = bb_copyfd_eof(firmware_fd, data_fd);
  833. if (ENABLE_FEATURE_CLEAN_UP)
  834. close(data_fd);
  835. }
  836. /* Tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading"
  837. * Note: we emit -1 also if firmware file wasn't found.
  838. * There are cases when otherwise kernel would wait for minutes
  839. * before timing out.
  840. */
  841. if (cnt > 0)
  842. full_write(loading_fd, "0", 1);
  843. else
  844. full_write(loading_fd, "-1", 2);
  845. out:
  846. xchdir("/dev");
  847. if (ENABLE_FEATURE_CLEAN_UP) {
  848. close(firmware_fd);
  849. close(loading_fd);
  850. }
  851. }
  852. static char *curtime(void)
  853. {
  854. struct timeval tv;
  855. gettimeofday(&tv, NULL);
  856. sprintf(
  857. strftime_HHMMSS(G.timestr, sizeof(G.timestr), &tv.tv_sec),
  858. ".%06u",
  859. (unsigned)tv.tv_usec
  860. );
  861. return G.timestr;
  862. }
  863. static void open_mdev_log(const char *seq, unsigned my_pid)
  864. {
  865. int logfd = open("mdev.log", O_WRONLY | O_APPEND);
  866. if (logfd >= 0) {
  867. xmove_fd(logfd, STDERR_FILENO);
  868. G.verbose = 2;
  869. applet_name = xasprintf("%s[%s]", applet_name, seq ? seq : utoa(my_pid));
  870. }
  871. }
  872. /* If it exists, does /dev/mdev.seq match $SEQNUM?
  873. * If it does not match, earlier mdev is running
  874. * in parallel, and we need to wait.
  875. * Active mdev pokes us with SIGCHLD to check the new file.
  876. */
  877. static int
  878. wait_for_seqfile(unsigned expected_seq)
  879. {
  880. /* We time out after 2 sec */
  881. static const struct timespec ts = { 0, 32*1000*1000 };
  882. int timeout = 2000 / 32;
  883. int seq_fd = -1;
  884. int do_once = 1;
  885. sigset_t set_CHLD;
  886. sigemptyset(&set_CHLD);
  887. sigaddset(&set_CHLD, SIGCHLD);
  888. sigprocmask(SIG_BLOCK, &set_CHLD, NULL);
  889. for (;;) {
  890. int seqlen;
  891. char seqbuf[sizeof(long)*3 + 2];
  892. unsigned seqbufnum;
  893. if (seq_fd < 0) {
  894. seq_fd = open("mdev.seq", O_RDWR);
  895. if (seq_fd < 0)
  896. break;
  897. close_on_exec_on(seq_fd);
  898. }
  899. seqlen = pread(seq_fd, seqbuf, sizeof(seqbuf) - 1, 0);
  900. if (seqlen < 0) {
  901. close(seq_fd);
  902. seq_fd = -1;
  903. break;
  904. }
  905. seqbuf[seqlen] = '\0';
  906. if (seqbuf[0] == '\n' || seqbuf[0] == '\0') {
  907. /* seed file: write out seq ASAP */
  908. xwrite_str(seq_fd, utoa(expected_seq));
  909. xlseek(seq_fd, 0, SEEK_SET);
  910. dbg2("first seq written");
  911. break;
  912. }
  913. seqbufnum = atoll(seqbuf);
  914. if (seqbufnum == expected_seq) {
  915. /* correct idx */
  916. break;
  917. }
  918. if (seqbufnum > expected_seq) {
  919. /* a later mdev runs already (this was seen by users to happen) */
  920. /* do not overwrite seqfile on exit */
  921. close(seq_fd);
  922. seq_fd = -1;
  923. break;
  924. }
  925. if (do_once) {
  926. dbg2("%s mdev.seq='%s', need '%u'", curtime(), seqbuf, expected_seq);
  927. do_once = 0;
  928. }
  929. if (sigtimedwait(&set_CHLD, NULL, &ts) >= 0) {
  930. dbg3("woken up");
  931. continue; /* don't decrement timeout! */
  932. }
  933. if (--timeout == 0) {
  934. dbg1("%s mdev.seq='%s'", "timed out", seqbuf);
  935. break;
  936. }
  937. }
  938. sigprocmask(SIG_UNBLOCK, &set_CHLD, NULL);
  939. return seq_fd;
  940. }
  941. static void signal_mdevs(unsigned my_pid)
  942. {
  943. procps_status_t* p = NULL;
  944. while ((p = procps_scan(p, PSSCAN_ARGV0)) != NULL) {
  945. if (p->pid != my_pid
  946. && p->argv0
  947. && strcmp(bb_basename(p->argv0), "mdev") == 0
  948. ) {
  949. kill(p->pid, SIGCHLD);
  950. }
  951. }
  952. }
  953. int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  954. int mdev_main(int argc UNUSED_PARAM, char **argv)
  955. {
  956. RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
  957. INIT_G();
  958. #if ENABLE_FEATURE_MDEV_CONF
  959. G.filename = "/etc/mdev.conf";
  960. #endif
  961. /* We can be called as hotplug helper */
  962. /* Kernel cannot provide suitable stdio fds for us, do it ourself */
  963. bb_sanitize_stdio();
  964. /* Force the configuration file settings exactly */
  965. umask(0);
  966. xchdir("/dev");
  967. if (argv[1] && strcmp(argv[1], "-s") == 0) {
  968. /*
  969. * Scan: mdev -s
  970. */
  971. struct stat st;
  972. #if ENABLE_FEATURE_MDEV_CONF
  973. /* Same as xrealloc_vector(NULL, 4, 0): */
  974. G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
  975. #endif
  976. xstat("/", &st);
  977. G.root_major = major(st.st_dev);
  978. G.root_minor = minor(st.st_dev);
  979. putenv((char*)"ACTION=add");
  980. /* Create all devices from /sys/dev hierarchy */
  981. recursive_action("/sys/dev",
  982. ACTION_RECURSE | ACTION_FOLLOWLINKS,
  983. fileAction, dirAction, temp, 0);
  984. } else {
  985. char *fw;
  986. char *seq;
  987. char *action;
  988. char *env_devname;
  989. char *env_devpath;
  990. unsigned my_pid;
  991. unsigned seqnum = seqnum; /* for compiler */
  992. int seq_fd;
  993. smalluint op;
  994. /* Hotplug:
  995. * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
  996. * ACTION can be "add", "remove", "change"
  997. * DEVPATH is like "/block/sda" or "/class/input/mice"
  998. */
  999. env_devname = getenv("DEVNAME"); /* can be NULL */
  1000. G.subsystem = getenv("SUBSYSTEM");
  1001. action = getenv("ACTION");
  1002. env_devpath = getenv("DEVPATH");
  1003. if (!action || !env_devpath /*|| !G.subsystem*/)
  1004. bb_show_usage();
  1005. fw = getenv("FIRMWARE");
  1006. seq = getenv("SEQNUM");
  1007. op = index_in_strings(keywords, action);
  1008. my_pid = getpid();
  1009. open_mdev_log(seq, my_pid);
  1010. seq_fd = -1;
  1011. if (seq) {
  1012. seqnum = atoll(seq);
  1013. seq_fd = wait_for_seqfile(seqnum);
  1014. }
  1015. dbg1("%s "
  1016. "ACTION:%s SUBSYSTEM:%s DEVNAME:%s DEVPATH:%s"
  1017. "%s%s",
  1018. curtime(),
  1019. action, G.subsystem, env_devname, env_devpath,
  1020. fw ? " FW:" : "", fw ? fw : ""
  1021. );
  1022. snprintf(temp, PATH_MAX, "/sys%s", env_devpath);
  1023. if (op == OP_remove) {
  1024. /* Ignoring "remove firmware". It was reported
  1025. * to happen and to cause erroneous deletion
  1026. * of device nodes. */
  1027. if (!fw)
  1028. make_device(env_devname, temp, op);
  1029. }
  1030. else {
  1031. make_device(env_devname, temp, op);
  1032. if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
  1033. if (op == OP_add && fw)
  1034. load_firmware(fw, temp);
  1035. }
  1036. }
  1037. dbg1("%s exiting", curtime());
  1038. if (seq_fd >= 0) {
  1039. xwrite_str(seq_fd, utoa(seqnum + 1));
  1040. signal_mdevs(my_pid);
  1041. }
  1042. }
  1043. if (ENABLE_FEATURE_CLEAN_UP)
  1044. RELEASE_CONFIG_BUFFER(temp);
  1045. return EXIT_SUCCESS;
  1046. }