mdev.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  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 "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 (IOW: to restore NUL if needed)
  499. * path string.
  500. * NB2: "mdev -s" may call us many times, do not leak memory/fds!
  501. *
  502. * device_name = $DEVNAME (may be NULL)
  503. * path = /sys/$DEVPATH
  504. */
  505. static void make_device(char *device_name, char *path, int operation)
  506. {
  507. int major, minor, type, len;
  508. char *path_end = path + strlen(path);
  509. /* Try to read major/minor string. Note that the kernel puts \n after
  510. * the data, so we don't need to worry about null terminating the string
  511. * because sscanf() will stop at the first nondigit, which \n is.
  512. * We also depend on path having writeable space after it.
  513. */
  514. major = -1;
  515. if (operation == OP_add) {
  516. strcpy(path_end, "/dev");
  517. len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
  518. *path_end = '\0';
  519. if (len < 1) {
  520. if (!ENABLE_FEATURE_MDEV_EXEC)
  521. return;
  522. /* no "dev" file, but we can still run scripts
  523. * based on device name */
  524. } else if (sscanf(path_end + 1, "%u:%u", &major, &minor) == 2) {
  525. dbg1("dev %u,%u", major, minor);
  526. } else {
  527. major = -1;
  528. }
  529. }
  530. /* else: for delete, -1 still deletes the node, but < -1 suppresses that */
  531. /* Determine device name */
  532. if (!device_name) {
  533. /*
  534. * There was no $DEVNAME envvar (for example, mdev -s never has).
  535. * But it is very useful: it contains the *path*, not only basename,
  536. * Thankfully, uevent file has it.
  537. * Example of .../sound/card0/controlC0/uevent file on Linux-3.7.7:
  538. * MAJOR=116
  539. * MINOR=7
  540. * DEVNAME=snd/controlC0
  541. */
  542. strcpy(path_end, "/uevent");
  543. len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
  544. if (len < 0)
  545. len = 0;
  546. *path_end = '\0';
  547. path_end[1 + len] = '\0';
  548. device_name = strstr(path_end + 1, "\nDEVNAME=");
  549. if (device_name) {
  550. device_name += sizeof("\nDEVNAME=")-1;
  551. strchrnul(device_name, '\n')[0] = '\0';
  552. } else {
  553. /* Fall back to just basename */
  554. device_name = (char*) bb_basename(path);
  555. }
  556. }
  557. /* Determine device type */
  558. /*
  559. * http://kernel.org/doc/pending/hotplug.txt says that only
  560. * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
  561. * But since 2.6.25 block devices are also in /sys/class/block.
  562. * We use strstr("/block/") to forestall future surprises.
  563. */
  564. type = S_IFCHR;
  565. if (strstr(path, "/block/") || (G.subsystem && is_prefixed_with(G.subsystem, "block")))
  566. type = S_IFBLK;
  567. #if ENABLE_FEATURE_MDEV_CONF
  568. G.rule_idx = 0; /* restart from the beginning (think mdev -s) */
  569. #endif
  570. for (;;) {
  571. const char *str_to_match;
  572. regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
  573. char *command;
  574. char *alias;
  575. char aliaslink = aliaslink; /* for compiler */
  576. char *node_name;
  577. const struct rule *rule;
  578. str_to_match = device_name;
  579. rule = next_rule();
  580. #if ENABLE_FEATURE_MDEV_CONF
  581. if (!env_matches(rule->envmatch))
  582. continue;
  583. if (rule->maj >= 0) { /* @maj,min rule */
  584. if (major != rule->maj)
  585. continue;
  586. if (minor < rule->min0 || minor > rule->min1)
  587. continue;
  588. memset(off, 0, sizeof(off));
  589. goto rule_matches;
  590. }
  591. if (rule->envvar) { /* $envvar=regex rule */
  592. str_to_match = getenv(rule->envvar);
  593. dbg3("getenv('%s'):'%s'", rule->envvar, str_to_match);
  594. if (!str_to_match)
  595. continue;
  596. }
  597. /* else: str_to_match = device_name */
  598. if (rule->regex_compiled) {
  599. int regex_match = regexec(&rule->match, str_to_match, ARRAY_SIZE(off), off, 0);
  600. dbg3("regex_match for '%s':%d", str_to_match, regex_match);
  601. //bb_error_msg("matches:");
  602. //for (int i = 0; i < ARRAY_SIZE(off); i++) {
  603. // if (off[i].rm_so < 0) continue;
  604. // bb_error_msg("match %d: '%.*s'\n", i,
  605. // (int)(off[i].rm_eo - off[i].rm_so),
  606. // device_name + off[i].rm_so);
  607. //}
  608. if (regex_match != 0
  609. /* regexec returns whole pattern as "range" 0 */
  610. || off[0].rm_so != 0
  611. || (int)off[0].rm_eo != (int)strlen(str_to_match)
  612. ) {
  613. continue; /* this rule doesn't match */
  614. }
  615. }
  616. /* else: it's final implicit "match-all" rule */
  617. rule_matches:
  618. dbg2("rule matched, line %d", G.parser ? G.parser->lineno : -1);
  619. #endif
  620. /* Build alias name */
  621. alias = NULL;
  622. if (ENABLE_FEATURE_MDEV_RENAME && rule->ren_mov) {
  623. aliaslink = rule->ren_mov[0];
  624. if (aliaslink == '!') {
  625. /* "!": suppress node creation/deletion */
  626. major = -2;
  627. }
  628. else if (aliaslink == '>' || aliaslink == '=') {
  629. if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
  630. char *s;
  631. char *p;
  632. unsigned n;
  633. /* substitute %1..9 with off[1..9], if any */
  634. n = 0;
  635. s = rule->ren_mov;
  636. while (*s)
  637. if (*s++ == '%')
  638. n++;
  639. p = alias = xzalloc(strlen(rule->ren_mov) + n * strlen(str_to_match));
  640. s = rule->ren_mov + 1;
  641. while (*s) {
  642. *p = *s;
  643. if ('%' == *s) {
  644. unsigned i = (s[1] - '0');
  645. if (i <= 9 && off[i].rm_so >= 0) {
  646. n = off[i].rm_eo - off[i].rm_so;
  647. strncpy(p, str_to_match + off[i].rm_so, n);
  648. p += n - 1;
  649. s++;
  650. }
  651. }
  652. p++;
  653. s++;
  654. }
  655. } else {
  656. alias = xstrdup(rule->ren_mov + 1);
  657. }
  658. }
  659. }
  660. dbg3("alias:'%s'", alias);
  661. command = NULL;
  662. IF_FEATURE_MDEV_EXEC(command = rule->r_cmd;)
  663. if (command) {
  664. /* Are we running this command now?
  665. * Run @cmd on create, $cmd on delete, *cmd on any
  666. */
  667. if ((command[0] == '@' && operation == OP_add)
  668. || (command[0] == '$' && operation == OP_remove)
  669. || (command[0] == '*')
  670. ) {
  671. command++;
  672. } else {
  673. command = NULL;
  674. }
  675. }
  676. dbg3("command:'%s'", command);
  677. /* "Execute" the line we found */
  678. node_name = device_name;
  679. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  680. node_name = alias = build_alias(alias, device_name);
  681. dbg3("alias2:'%s'", alias);
  682. }
  683. if (operation == OP_add && major >= 0) {
  684. char *slash = strrchr(node_name, '/');
  685. if (slash) {
  686. *slash = '\0';
  687. mkdir_recursive(node_name);
  688. *slash = '/';
  689. }
  690. if (ENABLE_FEATURE_MDEV_CONF) {
  691. dbg1("mknod %s (%d,%d) %o"
  692. " %u:%u",
  693. node_name, major, minor, rule->mode | type,
  694. rule->ugid.uid, rule->ugid.gid
  695. );
  696. } else {
  697. dbg1("mknod %s (%d,%d) %o",
  698. node_name, major, minor, rule->mode | type
  699. );
  700. }
  701. if (mknod(node_name, rule->mode | type, makedev(major, minor)) && errno != EEXIST)
  702. bb_perror_msg("can't create '%s'", node_name);
  703. if (ENABLE_FEATURE_MDEV_CONF) {
  704. chmod(node_name, rule->mode);
  705. chown(node_name, rule->ugid.uid, rule->ugid.gid);
  706. }
  707. if (major == G.root_major && minor == G.root_minor)
  708. symlink(node_name, "root");
  709. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  710. if (aliaslink == '>') {
  711. //TODO: on devtmpfs, device_name already exists and symlink() fails.
  712. //End result is that instead of symlink, we have two nodes.
  713. //What should be done?
  714. dbg1("symlink: %s", device_name);
  715. symlink(node_name, device_name);
  716. }
  717. }
  718. }
  719. if (ENABLE_FEATURE_MDEV_EXEC && command) {
  720. /* setenv will leak memory, use putenv/unsetenv/free */
  721. char *s = xasprintf("%s=%s", "MDEV", node_name);
  722. putenv(s);
  723. dbg1("running: %s", command);
  724. if (system(command) == -1)
  725. bb_perror_msg("can't run '%s'", command);
  726. bb_unsetenv_and_free(s);
  727. }
  728. if (operation == OP_remove && major >= -1) {
  729. if (ENABLE_FEATURE_MDEV_RENAME && alias) {
  730. if (aliaslink == '>') {
  731. dbg1("unlink: %s", device_name);
  732. unlink(device_name);
  733. }
  734. }
  735. dbg1("unlink: %s", node_name);
  736. unlink(node_name);
  737. }
  738. if (ENABLE_FEATURE_MDEV_RENAME)
  739. free(alias);
  740. /* We found matching line.
  741. * Stop unless it was prefixed with '-'
  742. */
  743. if (!ENABLE_FEATURE_MDEV_CONF || !rule->keep_matching)
  744. break;
  745. } /* for (;;) */
  746. }
  747. /* File callback for /sys/ traversal */
  748. static int FAST_FUNC fileAction(const char *fileName,
  749. struct stat *statbuf UNUSED_PARAM,
  750. void *userData,
  751. int depth UNUSED_PARAM)
  752. {
  753. size_t len = strlen(fileName) - 4; /* can't underflow */
  754. char *scratch = userData;
  755. /* len check is for paranoid reasons */
  756. if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
  757. return FALSE;
  758. strcpy(scratch, fileName);
  759. scratch[len] = '\0';
  760. make_device(/*DEVNAME:*/ NULL, scratch, OP_add);
  761. return TRUE;
  762. }
  763. /* Directory callback for /sys/ traversal */
  764. static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
  765. struct stat *statbuf UNUSED_PARAM,
  766. void *userData UNUSED_PARAM,
  767. int depth)
  768. {
  769. /* Extract device subsystem -- the name of the directory
  770. * under /sys/class/ */
  771. if (1 == depth) {
  772. free(G.subsystem);
  773. if (G.subsys_env) {
  774. bb_unsetenv_and_free(G.subsys_env);
  775. G.subsys_env = NULL;
  776. }
  777. G.subsystem = strrchr(fileName, '/');
  778. if (G.subsystem) {
  779. G.subsystem = xstrdup(G.subsystem + 1);
  780. G.subsys_env = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
  781. putenv(G.subsys_env);
  782. }
  783. }
  784. return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
  785. }
  786. /* For the full gory details, see linux/Documentation/firmware_class/README
  787. *
  788. * Firmware loading works like this:
  789. * - kernel sets FIRMWARE env var
  790. * - userspace checks /lib/firmware/$FIRMWARE
  791. * - userspace waits for /sys/$DEVPATH/loading to appear
  792. * - userspace writes "1" to /sys/$DEVPATH/loading
  793. * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
  794. * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
  795. * - kernel loads firmware into device
  796. */
  797. static void load_firmware(const char *firmware, const char *sysfs_path)
  798. {
  799. int cnt;
  800. int firmware_fd, loading_fd;
  801. /* check for /lib/firmware/$FIRMWARE */
  802. xchdir("/lib/firmware");
  803. firmware_fd = open(firmware, O_RDONLY); /* can fail */
  804. /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
  805. xchdir(sysfs_path);
  806. for (cnt = 0; cnt < 30; ++cnt) {
  807. loading_fd = open("loading", O_WRONLY);
  808. if (loading_fd >= 0)
  809. goto loading;
  810. sleep(1);
  811. }
  812. goto out;
  813. loading:
  814. cnt = 0;
  815. if (firmware_fd >= 0) {
  816. int data_fd;
  817. /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
  818. if (full_write(loading_fd, "1", 1) != 1)
  819. goto out;
  820. /* load firmware into /sys/$DEVPATH/data */
  821. data_fd = open("data", O_WRONLY);
  822. if (data_fd < 0)
  823. goto out;
  824. cnt = bb_copyfd_eof(firmware_fd, data_fd);
  825. if (ENABLE_FEATURE_CLEAN_UP)
  826. close(data_fd);
  827. }
  828. /* Tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading"
  829. * Note: we emit -1 also if firmware file wasn't found.
  830. * There are cases when otherwise kernel would wait for minutes
  831. * before timing out.
  832. */
  833. if (cnt > 0)
  834. full_write(loading_fd, "0", 1);
  835. else
  836. full_write(loading_fd, "-1", 2);
  837. out:
  838. xchdir("/dev");
  839. if (ENABLE_FEATURE_CLEAN_UP) {
  840. close(firmware_fd);
  841. close(loading_fd);
  842. }
  843. }
  844. static char *curtime(void)
  845. {
  846. struct timeval tv;
  847. gettimeofday(&tv, NULL);
  848. sprintf(
  849. strftime_HHMMSS(G.timestr, sizeof(G.timestr), &tv.tv_sec),
  850. ".%06u",
  851. (unsigned)tv.tv_usec
  852. );
  853. return G.timestr;
  854. }
  855. static void open_mdev_log(const char *seq, unsigned my_pid)
  856. {
  857. int logfd = open("mdev.log", O_WRONLY | O_APPEND);
  858. if (logfd >= 0) {
  859. xmove_fd(logfd, STDERR_FILENO);
  860. G.verbose = 2;
  861. applet_name = xasprintf("%s[%s]", applet_name, seq ? seq : utoa(my_pid));
  862. }
  863. }
  864. /* If it exists, does /dev/mdev.seq match $SEQNUM?
  865. * If it does not match, earlier mdev is running
  866. * in parallel, and we need to wait.
  867. * Active mdev pokes us with SIGCHLD to check the new file.
  868. */
  869. static int
  870. wait_for_seqfile(unsigned expected_seq)
  871. {
  872. /* We time out after 2 sec */
  873. static const struct timespec ts = { 0, 32*1000*1000 };
  874. int timeout = 2000 / 32;
  875. int seq_fd = -1;
  876. int do_once = 1;
  877. sigset_t set_CHLD;
  878. sigemptyset(&set_CHLD);
  879. sigaddset(&set_CHLD, SIGCHLD);
  880. sigprocmask(SIG_BLOCK, &set_CHLD, NULL);
  881. for (;;) {
  882. int seqlen;
  883. char seqbuf[sizeof(long)*3 + 2];
  884. unsigned seqbufnum;
  885. if (seq_fd < 0) {
  886. seq_fd = open("mdev.seq", O_RDWR);
  887. if (seq_fd < 0)
  888. break;
  889. close_on_exec_on(seq_fd);
  890. }
  891. seqlen = pread(seq_fd, seqbuf, sizeof(seqbuf) - 1, 0);
  892. if (seqlen < 0) {
  893. close(seq_fd);
  894. seq_fd = -1;
  895. break;
  896. }
  897. seqbuf[seqlen] = '\0';
  898. if (seqbuf[0] == '\n' || seqbuf[0] == '\0') {
  899. /* seed file: write out seq ASAP */
  900. xwrite_str(seq_fd, utoa(expected_seq));
  901. xlseek(seq_fd, 0, SEEK_SET);
  902. dbg2("first seq written");
  903. break;
  904. }
  905. seqbufnum = atoll(seqbuf);
  906. if (seqbufnum == expected_seq) {
  907. /* correct idx */
  908. break;
  909. }
  910. if (seqbufnum > expected_seq) {
  911. /* a later mdev runs already (this was seen by users to happen) */
  912. /* do not overwrite seqfile on exit */
  913. close(seq_fd);
  914. seq_fd = -1;
  915. break;
  916. }
  917. if (do_once) {
  918. dbg2("%s mdev.seq='%s', need '%u'", curtime(), seqbuf, expected_seq);
  919. do_once = 0;
  920. }
  921. if (sigtimedwait(&set_CHLD, NULL, &ts) >= 0) {
  922. dbg3("woken up");
  923. continue; /* don't decrement timeout! */
  924. }
  925. if (--timeout == 0) {
  926. dbg1("%s mdev.seq='%s'", "timed out", seqbuf);
  927. break;
  928. }
  929. }
  930. sigprocmask(SIG_UNBLOCK, &set_CHLD, NULL);
  931. return seq_fd;
  932. }
  933. static void signal_mdevs(unsigned my_pid)
  934. {
  935. procps_status_t* p = NULL;
  936. while ((p = procps_scan(p, PSSCAN_ARGV0)) != NULL) {
  937. if (p->pid != my_pid
  938. && p->argv0
  939. && strcmp(bb_basename(p->argv0), "mdev") == 0
  940. ) {
  941. kill(p->pid, SIGCHLD);
  942. }
  943. }
  944. }
  945. int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  946. int mdev_main(int argc UNUSED_PARAM, char **argv)
  947. {
  948. RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
  949. INIT_G();
  950. #if ENABLE_FEATURE_MDEV_CONF
  951. G.filename = "/etc/mdev.conf";
  952. #endif
  953. /* We can be called as hotplug helper */
  954. /* Kernel cannot provide suitable stdio fds for us, do it ourself */
  955. bb_sanitize_stdio();
  956. /* Force the configuration file settings exactly */
  957. umask(0);
  958. xchdir("/dev");
  959. if (argv[1] && strcmp(argv[1], "-s") == 0) {
  960. /*
  961. * Scan: mdev -s
  962. */
  963. struct stat st;
  964. #if ENABLE_FEATURE_MDEV_CONF
  965. /* Same as xrealloc_vector(NULL, 4, 0): */
  966. G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
  967. #endif
  968. xstat("/", &st);
  969. G.root_major = major(st.st_dev);
  970. G.root_minor = minor(st.st_dev);
  971. putenv((char*)"ACTION=add");
  972. /* ACTION_FOLLOWLINKS is needed since in newer kernels
  973. * /sys/block/loop* (for example) are symlinks to dirs,
  974. * not real directories.
  975. * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
  976. * but we can't enforce that on users)
  977. */
  978. if (access("/sys/class/block", F_OK) != 0) {
  979. /* Scan obsolete /sys/block only if /sys/class/block
  980. * doesn't exist. Otherwise we'll have dupes.
  981. * Also, do not complain if it doesn't exist.
  982. * Some people configure kernel to have no blockdevs.
  983. */
  984. recursive_action("/sys/block",
  985. ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
  986. fileAction, dirAction, temp, 0);
  987. }
  988. recursive_action("/sys/class",
  989. ACTION_RECURSE | ACTION_FOLLOWLINKS,
  990. fileAction, dirAction, temp, 0);
  991. } else {
  992. char *fw;
  993. char *seq;
  994. char *action;
  995. char *env_devname;
  996. char *env_devpath;
  997. unsigned my_pid;
  998. unsigned seqnum = seqnum; /* for compiler */
  999. int seq_fd;
  1000. smalluint op;
  1001. /* Hotplug:
  1002. * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
  1003. * ACTION can be "add", "remove", "change"
  1004. * DEVPATH is like "/block/sda" or "/class/input/mice"
  1005. */
  1006. env_devname = getenv("DEVNAME"); /* can be NULL */
  1007. G.subsystem = getenv("SUBSYSTEM");
  1008. action = getenv("ACTION");
  1009. env_devpath = getenv("DEVPATH");
  1010. if (!action || !env_devpath /*|| !G.subsystem*/)
  1011. bb_show_usage();
  1012. fw = getenv("FIRMWARE");
  1013. seq = getenv("SEQNUM");
  1014. op = index_in_strings(keywords, action);
  1015. my_pid = getpid();
  1016. open_mdev_log(seq, my_pid);
  1017. seq_fd = -1;
  1018. if (seq) {
  1019. seqnum = atoll(seq);
  1020. seq_fd = wait_for_seqfile(seqnum);
  1021. }
  1022. dbg1("%s "
  1023. "ACTION:%s SUBSYSTEM:%s DEVNAME:%s DEVPATH:%s"
  1024. "%s%s",
  1025. curtime(),
  1026. action, G.subsystem, env_devname, env_devpath,
  1027. fw ? " FW:" : "", fw ? fw : ""
  1028. );
  1029. snprintf(temp, PATH_MAX, "/sys%s", env_devpath);
  1030. if (op == OP_remove) {
  1031. /* Ignoring "remove firmware". It was reported
  1032. * to happen and to cause erroneous deletion
  1033. * of device nodes. */
  1034. if (!fw)
  1035. make_device(env_devname, temp, op);
  1036. }
  1037. else {
  1038. make_device(env_devname, temp, op);
  1039. if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
  1040. if (op == OP_add && fw)
  1041. load_firmware(fw, temp);
  1042. }
  1043. }
  1044. dbg1("%s exiting", curtime());
  1045. if (seq_fd >= 0) {
  1046. xwrite_str(seq_fd, utoa(seqnum + 1));
  1047. signal_mdevs(my_pid);
  1048. }
  1049. }
  1050. if (ENABLE_FEATURE_CLEAN_UP)
  1051. RELEASE_CONFIG_BUFFER(temp);
  1052. return EXIT_SUCCESS;
  1053. }