mdev.c 34 KB

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