mdev.c 34 KB

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