mdev.c 31 KB

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