3
0

mdev.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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 (20 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: "[-vS] " IF_FEATURE_MDEV_DAEMON("{ ") "[-s]" IF_FEATURE_MDEV_DAEMON(" | [-df] }")
  81. //usage:#define mdev_full_usage "\n\n"
  82. //usage: " -v Verbose\n"
  83. //usage: " -S Log to syslog too\n"
  84. //usage: " -s Scan /sys and populate /dev\n"
  85. //usage: IF_FEATURE_MDEV_DAEMON(
  86. //usage: " -d Daemon, listen on netlink\n"
  87. //usage: " -f Run in foreground\n"
  88. //usage: )
  89. //usage: "\n"
  90. //usage: "Bare mdev is a kernel hotplug helper. To activate it:\n"
  91. //usage: " echo /sbin/mdev >/proc/sys/kernel/hotplug\n"
  92. //usage: IF_FEATURE_MDEV_CONF(
  93. //usage: "\n"
  94. //usage: "It uses /etc/mdev.conf with lines\n"
  95. //usage: " [-][ENV=regex;]...DEVNAME UID:GID PERM"
  96. //usage: IF_FEATURE_MDEV_RENAME(" [>|=PATH]|[!]")
  97. //usage: IF_FEATURE_MDEV_EXEC(" [@|$|*PROG]")
  98. //usage: "\n"
  99. //usage: "where DEVNAME is device name regex, @major,minor[-minor2], or\n"
  100. //usage: "environment variable regex. A common use of the latter is\n"
  101. //usage: "to load modules for hotplugged devices:\n"
  102. //usage: " $MODALIAS=.* 0:0 660 @modprobe \"$MODALIAS\"\n"
  103. //usage: )
  104. //usage: "\n"
  105. //usage: "If /dev/mdev.seq file exists, mdev will wait for its value\n"
  106. //usage: "to match $SEQNUM variable. This prevents plug/unplug races.\n"
  107. //usage: "To activate this feature, create empty /dev/mdev.seq at boot.\n"
  108. //usage: "\n"
  109. //usage: "If /dev/mdev.log file exists, debug log will be appended to it."
  110. #include "libbb.h"
  111. #include "common_bufsiz.h"
  112. #include "xregex.h"
  113. #include <linux/netlink.h>
  114. #include <syslog.h>
  115. /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
  116. * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
  117. * contains "4:0\n". Directory name is taken as device name, path component
  118. * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
  119. * Then mdev creates the /dev/device_name node.
  120. * If /sys/class/.../dev file does not exist, mdev still may act
  121. * on this device: see "@|$|*command args..." parameter in config file.
  122. *
  123. * mdev w/o parameters is called as hotplug helper. It takes device
  124. * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
  125. * maj,min from "/sys/$DEVPATH/dev" and also examines
  126. * $ACTION ("add"/"delete") and $FIRMWARE.
  127. *
  128. * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
  129. * (todo: explain "delete" and $FIRMWARE)
  130. *
  131. * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
  132. *
  133. * Leading minus in 1st field means "don't stop on this line", otherwise
  134. * search is stopped after the matching line is encountered.
  135. *
  136. * $envvar=regex format is useful for loading modules for hot-plugged devices
  137. * which do not have driver loaded yet. In this case /sys/class/.../dev
  138. * does not exist, but $MODALIAS is set to needed module's name
  139. * (actually, an alias to it) by kernel. This rule instructs mdev
  140. * to load the module and exit:
  141. * $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
  142. * The kernel will generate another hotplug event when /sys/class/.../dev
  143. * file appears.
  144. *
  145. * When line matches, the device node is created, chmod'ed and chown'ed,
  146. * moved to path, and if >path, a symlink to moved node is created,
  147. * all this if /sys/class/.../dev exists.
  148. * Examples:
  149. * =loop/ - moves to /dev/loop
  150. * >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
  151. *
  152. * Then "command args..." is executed (via sh -c 'command args...').
  153. * @:execute on creation, $:on deletion, *:on both.
  154. * This happens regardless of /sys/class/.../dev existence.
  155. */
  156. /* Kernel's hotplug environment constantly changes.
  157. * Here are new cases I observed on 3.1.0:
  158. *
  159. * Case with $DEVNAME and $DEVICE, not just $DEVPATH:
  160. * ACTION=add
  161. * BUSNUM=001
  162. * DEVICE=/proc/bus/usb/001/003
  163. * DEVNAME=bus/usb/001/003
  164. * DEVNUM=003
  165. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5
  166. * DEVTYPE=usb_device
  167. * MAJOR=189
  168. * MINOR=2
  169. * PRODUCT=18d1/4e12/227
  170. * SUBSYSTEM=usb
  171. * TYPE=0/0/0
  172. *
  173. * Case with $DEVICE, but no $DEVNAME - apparenty, usb iface notification?
  174. * "Please load me a module" thing?
  175. * ACTION=add
  176. * DEVICE=/proc/bus/usb/001/003
  177. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0
  178. * DEVTYPE=usb_interface
  179. * INTERFACE=8/6/80
  180. * MODALIAS=usb:v18D1p4E12d0227dc00dsc00dp00ic08isc06ip50
  181. * PRODUCT=18d1/4e12/227
  182. * SUBSYSTEM=usb
  183. * TYPE=0/0/0
  184. *
  185. * ACTION=add
  186. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5
  187. * DEVTYPE=scsi_host
  188. * SUBSYSTEM=scsi
  189. *
  190. * ACTION=add
  191. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/scsi_host/host5
  192. * SUBSYSTEM=scsi_host
  193. *
  194. * ACTION=add
  195. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0
  196. * DEVTYPE=scsi_target
  197. * SUBSYSTEM=scsi
  198. *
  199. * Case with strange $MODALIAS:
  200. * ACTION=add
  201. * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0
  202. * DEVTYPE=scsi_device
  203. * MODALIAS=scsi:t-0x00
  204. * SUBSYSTEM=scsi
  205. *
  206. * ACTION=add
  207. * 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
  208. * SUBSYSTEM=scsi_disk
  209. *
  210. * ACTION=add
  211. * 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
  212. * SUBSYSTEM=scsi_device
  213. *
  214. * Case with explicit $MAJOR/$MINOR (no need to read /sys/$DEVPATH/dev?):
  215. * ACTION=add
  216. * DEVNAME=bsg/5:0:0:0
  217. * 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
  218. * MAJOR=253
  219. * MINOR=1
  220. * SUBSYSTEM=bsg
  221. *
  222. * ACTION=add
  223. * DEVPATH=/devices/virtual/bdi/8:16
  224. * SUBSYSTEM=bdi
  225. *
  226. * ACTION=add
  227. * DEVNAME=sdb
  228. * DEVPATH=/block/sdb
  229. * DEVTYPE=disk
  230. * MAJOR=8
  231. * MINOR=16
  232. * SUBSYSTEM=block
  233. *
  234. * Case with ACTION=change:
  235. * ACTION=change
  236. * DEVNAME=sdb
  237. * DEVPATH=/block/sdb
  238. * DEVTYPE=disk
  239. * DISK_MEDIA_CHANGE=1
  240. * MAJOR=8
  241. * MINOR=16
  242. * SUBSYSTEM=block
  243. */
  244. #define DEBUG_LVL 2
  245. #if DEBUG_LVL >= 1
  246. # define dbg1(...) do { if (G.verbose) bb_error_msg(__VA_ARGS__); } while(0)
  247. # define dbg1s(msg) do { if (G.verbose) bb_simple_error_msg(msg); } while(0)
  248. #else
  249. # define dbg1(...) ((void)0)
  250. # define dbg1s(msg) ((void)0)
  251. #endif
  252. #if DEBUG_LVL >= 2
  253. # define dbg2(...) do { if (G.verbose >= 2) bb_error_msg(__VA_ARGS__); } while(0)
  254. # define dbg2s(msg) do { if (G.verbose >= 2) bb_simple_error_msg(msg); } while(0)
  255. #else
  256. # define dbg2(...) ((void)0)
  257. # define dbg2s(msg) ((void)0)
  258. #endif
  259. #if DEBUG_LVL >= 3
  260. # define dbg3(...) do { if (G.verbose >= 3) bb_error_msg(__VA_ARGS__); } while(0)
  261. # define dbg3s(msg) do { if (G.verbose >= 3) bb_simple_error_msg(msg); } while(0)
  262. #else
  263. # define dbg3(...) ((void)0)
  264. # define dbg3s(msg) ((void)0)
  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. int 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. sleep1();
  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. xgettimeofday(&tv);
  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. /*
  1056. * The kernel (as of v5.4) will pass up to 32 environment variables with a
  1057. * total of 2kiB on each event. On top of that the action string and device
  1058. * path are added. Using a 3kiB buffer for the event should suffice in any
  1059. * case.
  1060. *
  1061. * As far as the socket receive buffer size is concerned 2MiB proved to be too
  1062. * small (see [1]). Udevd seems to use a whooping 128MiB. The socket receive
  1063. * buffer size is just a resource limit. The buffers are allocated lazily so
  1064. * the memory is not wasted.
  1065. *
  1066. * [1] http://lists.busybox.net/pipermail/busybox/2019-December/087665.html
  1067. */
  1068. # define USER_RCVBUF (3 * 1024)
  1069. # define KERN_RCVBUF (128 * 1024 * 1024)
  1070. # define MAX_ENV 32
  1071. static int daemon_init(char *temp)
  1072. {
  1073. int fd;
  1074. /* Subscribe for UEVENT kernel messages */
  1075. /* Without a sufficiently big RCVBUF, a ton of simultaneous events
  1076. * can trigger ENOBUFS on read, which is unrecoverable.
  1077. * Reproducer:
  1078. * mdev -d
  1079. * find /sys -name uevent -exec sh -c 'echo add >"{}"' ';'
  1080. */
  1081. fd = create_and_bind_to_netlink(NETLINK_KOBJECT_UEVENT, 1 << 0, KERN_RCVBUF);
  1082. /*
  1083. * Make inital scan after the uevent socket is alive and
  1084. * _before_ we fork away. Already open mdev.log because we work
  1085. * in daemon mode.
  1086. */
  1087. initial_scan(temp);
  1088. return fd;
  1089. }
  1090. static void daemon_loop(char *temp, int fd)
  1091. {
  1092. for (;;) {
  1093. char netbuf[USER_RCVBUF];
  1094. char *env[MAX_ENV];
  1095. char *s, *end;
  1096. ssize_t len;
  1097. int idx;
  1098. len = safe_read(fd, netbuf, sizeof(netbuf) - 1);
  1099. if (len < 0) {
  1100. if (errno == ENOBUFS) {
  1101. /*
  1102. * We ran out of socket receive buffer space.
  1103. * Start from scratch.
  1104. */
  1105. dbg1s("uevent overrun, rescanning");
  1106. close(fd);
  1107. fd = daemon_init(temp);
  1108. continue;
  1109. }
  1110. bb_simple_perror_msg_and_die("read");
  1111. }
  1112. end = netbuf + len;
  1113. *end = '\0';
  1114. idx = 0;
  1115. s = netbuf;
  1116. while (s < end && idx < MAX_ENV) {
  1117. if (endofname(s)[0] == '=') {
  1118. env[idx++] = s;
  1119. putenv(s);
  1120. }
  1121. s += strlen(s) + 1;
  1122. }
  1123. process_action(temp, 0);
  1124. while (idx)
  1125. bb_unsetenv(env[--idx]);
  1126. }
  1127. }
  1128. #endif
  1129. int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1130. int mdev_main(int argc UNUSED_PARAM, char **argv)
  1131. {
  1132. enum {
  1133. MDEV_OPT_SCAN = 1 << 0,
  1134. MDEV_OPT_SYSLOG = 1 << 1,
  1135. MDEV_OPT_DAEMON = 1 << 2,
  1136. MDEV_OPT_FOREGROUND = 1 << 3,
  1137. };
  1138. int opt;
  1139. RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
  1140. INIT_G();
  1141. /* We can be called as hotplug helper */
  1142. /* Kernel cannot provide suitable stdio fds for us, do it ourself */
  1143. bb_sanitize_stdio();
  1144. /* Force the configuration file settings exactly */
  1145. umask(0);
  1146. xchdir("/dev");
  1147. opt = getopt32(argv, "^"
  1148. "sS" IF_FEATURE_MDEV_DAEMON("df") "v"
  1149. "\0"
  1150. "vv",
  1151. &G.verbose);
  1152. #if ENABLE_FEATURE_MDEV_CONF
  1153. G.filename = "/etc/mdev.conf";
  1154. if (opt & (MDEV_OPT_SCAN|MDEV_OPT_DAEMON)) {
  1155. /* Same as xrealloc_vector(NULL, 4, 0): */
  1156. G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
  1157. }
  1158. #endif
  1159. if (opt & MDEV_OPT_SYSLOG) {
  1160. openlog(applet_name, LOG_PID, LOG_DAEMON);
  1161. logmode |= LOGMODE_SYSLOG;
  1162. }
  1163. #if ENABLE_FEATURE_MDEV_DAEMON
  1164. if (opt & MDEV_OPT_DAEMON) {
  1165. /* Daemon mode listening on uevent netlink socket. Fork away
  1166. * after initial scan so that caller can be sure everything
  1167. * is up-to-date when mdev process returns.
  1168. */
  1169. int fd = daemon_init(temp);
  1170. if (!(opt & MDEV_OPT_FOREGROUND)) {
  1171. /* there is no point in logging to /dev/null */
  1172. logmode &= ~LOGMODE_STDIO;
  1173. bb_daemonize_or_rexec(0, argv);
  1174. }
  1175. daemon_loop(temp, fd);
  1176. }
  1177. #endif
  1178. if (opt & MDEV_OPT_SCAN) {
  1179. /*
  1180. * Scan: mdev -s
  1181. */
  1182. initial_scan(temp);
  1183. } else {
  1184. process_action(temp, getpid());
  1185. dbg1("%s exiting", curtime());
  1186. }
  1187. if (ENABLE_FEATURE_CLEAN_UP)
  1188. RELEASE_CONFIG_BUFFER(temp);
  1189. return EXIT_SUCCESS;
  1190. }