mdev.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  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 (17 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. static ssize_t readlink2(char *buf, size_t bufsize)
  747. {
  748. // Grr... gcc 8.1.1:
  749. // "passing argument 2 to restrict-qualified parameter aliases with argument 1"
  750. // dance around that...
  751. char *obuf FIX_ALIASING;
  752. obuf = buf;
  753. return readlink(buf, obuf, bufsize);
  754. }
  755. /* File callback for /sys/ traversal.
  756. * We act only on "/sys/.../dev" (pseudo)file
  757. */
  758. static int FAST_FUNC fileAction(const char *fileName,
  759. struct stat *statbuf UNUSED_PARAM,
  760. void *userData,
  761. int depth UNUSED_PARAM)
  762. {
  763. size_t len = strlen(fileName) - 4; /* can't underflow */
  764. char *path = userData; /* char array[PATH_MAX + SCRATCH_SIZE] */
  765. char subsys[PATH_MAX];
  766. int res;
  767. /* Is it a ".../dev" file? (len check is for paranoid reasons) */
  768. if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX - 32)
  769. return FALSE; /* not .../dev */
  770. strcpy(path, fileName);
  771. path[len] = '\0';
  772. /* Read ".../subsystem" symlink in the same directory where ".../dev" is */
  773. strcpy(subsys, path);
  774. strcpy(subsys + len, "/subsystem");
  775. res = readlink2(subsys, sizeof(subsys)-1);
  776. if (res > 0) {
  777. subsys[res] = '\0';
  778. free(G.subsystem);
  779. if (G.subsys_env) {
  780. bb_unsetenv_and_free(G.subsys_env);
  781. G.subsys_env = NULL;
  782. }
  783. /* Set G.subsystem and $SUBSYSTEM from symlink's last component */
  784. G.subsystem = strrchr(subsys, '/');
  785. if (G.subsystem) {
  786. G.subsystem = xstrdup(G.subsystem + 1);
  787. G.subsys_env = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
  788. putenv(G.subsys_env);
  789. }
  790. }
  791. make_device(/*DEVNAME:*/ NULL, path, OP_add);
  792. return TRUE;
  793. }
  794. /* Directory callback for /sys/ traversal */
  795. static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
  796. struct stat *statbuf UNUSED_PARAM,
  797. void *userData UNUSED_PARAM,
  798. int depth)
  799. {
  800. return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
  801. }
  802. /* For the full gory details, see linux/Documentation/firmware_class/README
  803. *
  804. * Firmware loading works like this:
  805. * - kernel sets FIRMWARE env var
  806. * - userspace checks /lib/firmware/$FIRMWARE
  807. * - userspace waits for /sys/$DEVPATH/loading to appear
  808. * - userspace writes "1" to /sys/$DEVPATH/loading
  809. * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
  810. * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
  811. * - kernel loads firmware into device
  812. */
  813. static void load_firmware(const char *firmware, const char *sysfs_path)
  814. {
  815. int cnt;
  816. int firmware_fd, loading_fd;
  817. /* check for /lib/firmware/$FIRMWARE */
  818. firmware_fd = -1;
  819. if (chdir("/lib/firmware") == 0)
  820. firmware_fd = open(firmware, O_RDONLY); /* can fail */
  821. /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
  822. xchdir(sysfs_path);
  823. for (cnt = 0; cnt < 30; ++cnt) {
  824. loading_fd = open("loading", O_WRONLY);
  825. if (loading_fd >= 0)
  826. goto loading;
  827. sleep(1);
  828. }
  829. goto out;
  830. loading:
  831. cnt = 0;
  832. if (firmware_fd >= 0) {
  833. int data_fd;
  834. /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
  835. if (full_write(loading_fd, "1", 1) != 1)
  836. goto out;
  837. /* load firmware into /sys/$DEVPATH/data */
  838. data_fd = open("data", O_WRONLY);
  839. if (data_fd < 0)
  840. goto out;
  841. cnt = bb_copyfd_eof(firmware_fd, data_fd);
  842. if (ENABLE_FEATURE_CLEAN_UP)
  843. close(data_fd);
  844. }
  845. /* Tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading"
  846. * Note: we emit -1 also if firmware file wasn't found.
  847. * There are cases when otherwise kernel would wait for minutes
  848. * before timing out.
  849. */
  850. if (cnt > 0)
  851. full_write(loading_fd, "0", 1);
  852. else
  853. full_write(loading_fd, "-1", 2);
  854. out:
  855. xchdir("/dev");
  856. if (ENABLE_FEATURE_CLEAN_UP) {
  857. close(firmware_fd);
  858. close(loading_fd);
  859. }
  860. }
  861. static char *curtime(void)
  862. {
  863. struct timeval tv;
  864. gettimeofday(&tv, NULL);
  865. sprintf(
  866. strftime_HHMMSS(G.timestr, sizeof(G.timestr), &tv.tv_sec),
  867. ".%06u",
  868. (unsigned)tv.tv_usec
  869. );
  870. return G.timestr;
  871. }
  872. static void open_mdev_log(const char *seq, unsigned my_pid)
  873. {
  874. int logfd = open("mdev.log", O_WRONLY | O_APPEND);
  875. if (logfd >= 0) {
  876. xmove_fd(logfd, STDERR_FILENO);
  877. G.verbose = 2;
  878. applet_name = xasprintf("%s[%s]", applet_name, seq ? seq : utoa(my_pid));
  879. }
  880. }
  881. /* If it exists, does /dev/mdev.seq match $SEQNUM?
  882. * If it does not match, earlier mdev is running
  883. * in parallel, and we need to wait.
  884. * Active mdev pokes us with SIGCHLD to check the new file.
  885. */
  886. static int
  887. wait_for_seqfile(unsigned expected_seq)
  888. {
  889. /* We time out after 2 sec */
  890. static const struct timespec ts = { 0, 32*1000*1000 };
  891. int timeout = 2000 / 32;
  892. int seq_fd = -1;
  893. int do_once = 1;
  894. sigset_t set_CHLD;
  895. sigemptyset(&set_CHLD);
  896. sigaddset(&set_CHLD, SIGCHLD);
  897. sigprocmask(SIG_BLOCK, &set_CHLD, NULL);
  898. for (;;) {
  899. int seqlen;
  900. char seqbuf[sizeof(long)*3 + 2];
  901. unsigned seqbufnum;
  902. if (seq_fd < 0) {
  903. seq_fd = open("mdev.seq", O_RDWR);
  904. if (seq_fd < 0)
  905. break;
  906. close_on_exec_on(seq_fd);
  907. }
  908. seqlen = pread(seq_fd, seqbuf, sizeof(seqbuf) - 1, 0);
  909. if (seqlen < 0) {
  910. close(seq_fd);
  911. seq_fd = -1;
  912. break;
  913. }
  914. seqbuf[seqlen] = '\0';
  915. if (seqbuf[0] == '\n' || seqbuf[0] == '\0') {
  916. /* seed file: write out seq ASAP */
  917. xwrite_str(seq_fd, utoa(expected_seq));
  918. xlseek(seq_fd, 0, SEEK_SET);
  919. dbg2("first seq written");
  920. break;
  921. }
  922. seqbufnum = atoll(seqbuf);
  923. if (seqbufnum == expected_seq) {
  924. /* correct idx */
  925. break;
  926. }
  927. if (seqbufnum > expected_seq) {
  928. /* a later mdev runs already (this was seen by users to happen) */
  929. /* do not overwrite seqfile on exit */
  930. close(seq_fd);
  931. seq_fd = -1;
  932. break;
  933. }
  934. if (do_once) {
  935. dbg2("%s mdev.seq='%s', need '%u'", curtime(), seqbuf, expected_seq);
  936. do_once = 0;
  937. }
  938. if (sigtimedwait(&set_CHLD, NULL, &ts) >= 0) {
  939. dbg3("woken up");
  940. continue; /* don't decrement timeout! */
  941. }
  942. if (--timeout == 0) {
  943. dbg1("%s mdev.seq='%s'", "timed out", seqbuf);
  944. break;
  945. }
  946. }
  947. sigprocmask(SIG_UNBLOCK, &set_CHLD, NULL);
  948. return seq_fd;
  949. }
  950. static void signal_mdevs(unsigned my_pid)
  951. {
  952. procps_status_t* p = NULL;
  953. while ((p = procps_scan(p, PSSCAN_ARGV0)) != NULL) {
  954. if (p->pid != my_pid
  955. && p->argv0
  956. && strcmp(bb_basename(p->argv0), "mdev") == 0
  957. ) {
  958. kill(p->pid, SIGCHLD);
  959. }
  960. }
  961. }
  962. int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  963. int mdev_main(int argc UNUSED_PARAM, char **argv)
  964. {
  965. RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
  966. INIT_G();
  967. #if ENABLE_FEATURE_MDEV_CONF
  968. G.filename = "/etc/mdev.conf";
  969. #endif
  970. /* We can be called as hotplug helper */
  971. /* Kernel cannot provide suitable stdio fds for us, do it ourself */
  972. bb_sanitize_stdio();
  973. /* Force the configuration file settings exactly */
  974. umask(0);
  975. xchdir("/dev");
  976. if (argv[1] && strcmp(argv[1], "-s") == 0) {
  977. /*
  978. * Scan: mdev -s
  979. */
  980. struct stat st;
  981. #if ENABLE_FEATURE_MDEV_CONF
  982. /* Same as xrealloc_vector(NULL, 4, 0): */
  983. G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
  984. #endif
  985. xstat("/", &st);
  986. G.root_major = major(st.st_dev);
  987. G.root_minor = minor(st.st_dev);
  988. putenv((char*)"ACTION=add");
  989. /* Create all devices from /sys/dev hierarchy */
  990. recursive_action("/sys/dev",
  991. ACTION_RECURSE | ACTION_FOLLOWLINKS,
  992. fileAction, dirAction, temp, 0);
  993. } else {
  994. char *fw;
  995. char *seq;
  996. char *action;
  997. char *env_devname;
  998. char *env_devpath;
  999. unsigned my_pid;
  1000. unsigned seqnum = seqnum; /* for compiler */
  1001. int seq_fd;
  1002. smalluint op;
  1003. /* Hotplug:
  1004. * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
  1005. * ACTION can be "add", "remove", "change"
  1006. * DEVPATH is like "/block/sda" or "/class/input/mice"
  1007. */
  1008. env_devname = getenv("DEVNAME"); /* can be NULL */
  1009. G.subsystem = getenv("SUBSYSTEM");
  1010. action = getenv("ACTION");
  1011. env_devpath = getenv("DEVPATH");
  1012. if (!action || !env_devpath /*|| !G.subsystem*/)
  1013. bb_show_usage();
  1014. fw = getenv("FIRMWARE");
  1015. seq = getenv("SEQNUM");
  1016. op = index_in_strings(keywords, action);
  1017. my_pid = getpid();
  1018. open_mdev_log(seq, my_pid);
  1019. seq_fd = -1;
  1020. if (seq) {
  1021. seqnum = atoll(seq);
  1022. seq_fd = wait_for_seqfile(seqnum);
  1023. }
  1024. dbg1("%s "
  1025. "ACTION:%s SUBSYSTEM:%s DEVNAME:%s DEVPATH:%s"
  1026. "%s%s",
  1027. curtime(),
  1028. action, G.subsystem, env_devname, env_devpath,
  1029. fw ? " FW:" : "", fw ? fw : ""
  1030. );
  1031. snprintf(temp, PATH_MAX, "/sys%s", env_devpath);
  1032. if (op == OP_remove) {
  1033. /* Ignoring "remove firmware". It was reported
  1034. * to happen and to cause erroneous deletion
  1035. * of device nodes. */
  1036. if (!fw)
  1037. make_device(env_devname, temp, op);
  1038. }
  1039. else {
  1040. make_device(env_devname, temp, op);
  1041. if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
  1042. if (op == OP_add && fw)
  1043. load_firmware(fw, temp);
  1044. }
  1045. }
  1046. dbg1("%s exiting", curtime());
  1047. if (seq_fd >= 0) {
  1048. xwrite_str(seq_fd, utoa(seqnum + 1));
  1049. signal_mdevs(my_pid);
  1050. }
  1051. }
  1052. if (ENABLE_FEATURE_CLEAN_UP)
  1053. RELEASE_CONFIG_BUFFER(temp);
  1054. return EXIT_SUCCESS;
  1055. }