mark Linux-specific configuration options
[oweals/busybox.git] / util-linux / mdev.c
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 GPL version 2, see file LICENSE in this tarball for details.
9  */
10 #include "libbb.h"
11 #include "xregex.h"
12
13 /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
14  * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
15  * contains "4:0\n". Directory name is taken as device name, path component
16  * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
17  * Then mdev creates the /dev/device_name node.
18  * If /sys/class/.../dev file does not exist, mdev still may act
19  * on this device: see "@|$|*command args..." parameter in config file.
20  *
21  * mdev w/o parameters is called as hotplug helper. It takes device
22  * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
23  * maj,min from "/sys/$DEVPATH/dev" and also examines
24  * $ACTION ("add"/"delete") and $FIRMWARE.
25  *
26  * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
27  * (todo: explain "delete" and $FIRMWARE)
28  *
29  * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
30  * /etc/mdev.conf file format:
31  *
32  * [-][subsystem/]device  user:grp  mode  [>|=path] [@|$|*command args...]
33  * [-]@maj,min[-min2]     user:grp  mode  [>|=path] [@|$|*command args...]
34  * [-]$envvar=val         user:grp  mode  [>|=path] [@|$|*command args...]
35  *
36  * Leading minus in 1st field means "don't stop on this line", otherwise
37  * search is stopped after the matching line is encountered.
38  *
39  * The device name or "subsystem/device" combo is matched against 1st field
40  * (which is a regex), or maj,min is matched against 1st field,
41  * or specified environment variable (as regex) is matched against 1st field.
42  *
43  * $envvar=val format is useful for loading modules for hot-plugged devices
44  * which do not have driver loaded yet. In this case /sys/class/.../dev
45  * does not exist, but $MODALIAS is set to needed module's name
46  * (actually, an alias to it) by kernel. This rule instructs mdev
47  * to load the module and exit:
48  *    $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
49  * The kernel will generate another hotplug event when /sys/class/.../dev
50  * file appears.
51  *
52  * When line matches, the device node is created, chmod'ed and chown'ed,
53  * moved to path, and if >path, a symlink to moved node is created,
54  * all this if /sys/class/.../dev exists.
55  *    Examples:
56  *    =loop/      - moves to /dev/loop
57  *    >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
58  *
59  * Then "command args..." is executed (via sh -c 'command args...').
60  * @:execute on creation, $:on deletion, *:on both.
61  * This happens regardless of /sys/class/.../dev existence.
62  */
63
64 struct globals {
65         int root_major, root_minor;
66         char *subsystem;
67 } FIX_ALIASING;
68 #define G (*(struct globals*)&bb_common_bufsiz1)
69
70 /* Prevent infinite loops in /sys symlinks */
71 #define MAX_SYSFS_DEPTH 3
72
73 /* We use additional 64+ bytes in make_device() */
74 #define SCRATCH_SIZE 80
75
76 /* Builds an alias path.
77  * This function potentionally reallocates the alias parameter.
78  * Only used for ENABLE_FEATURE_MDEV_RENAME
79  */
80 static char *build_alias(char *alias, const char *device_name)
81 {
82         char *dest;
83
84         /* ">bar/": rename to bar/device_name */
85         /* ">bar[/]baz": rename to bar[/]baz */
86         dest = strrchr(alias, '/');
87         if (dest) { /* ">bar/[baz]" ? */
88                 *dest = '\0'; /* mkdir bar */
89                 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
90                 *dest = '/';
91                 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
92                         dest = alias;
93                         alias = concat_path_file(alias, device_name);
94                         free(dest);
95                 }
96         }
97
98         return alias;
99 }
100
101 /* mknod in /dev based on a path like "/sys/block/hda/hda1"
102  * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
103  * after NUL, but we promise to not mangle (IOW: to restore if needed)
104  * path string.
105  * NB2: "mdev -s" may call us many times, do not leak memory/fds!
106  */
107 static void make_device(char *path, int delete)
108 {
109         char *device_name, *subsystem_slash_devname;
110         int major, minor, type, len;
111         mode_t mode;
112         parser_t *parser;
113
114         /* Try to read major/minor string.  Note that the kernel puts \n after
115          * the data, so we don't need to worry about null terminating the string
116          * because sscanf() will stop at the first nondigit, which \n is.
117          * We also depend on path having writeable space after it.
118          */
119         major = -1;
120         if (!delete) {
121                 char *dev_maj_min = path + strlen(path);
122
123                 strcpy(dev_maj_min, "/dev");
124                 len = open_read_close(path, dev_maj_min + 1, 64);
125                 *dev_maj_min = '\0';
126                 if (len < 1) {
127                         if (!ENABLE_FEATURE_MDEV_EXEC)
128                                 return;
129                         /* no "dev" file, but we can still run scripts
130                          * based on device name */
131                 } else if (sscanf(++dev_maj_min, "%u:%u", &major, &minor) != 2) {
132                         major = -1;
133                 }
134         }
135
136         /* Determine device name, type, major and minor */
137         device_name = (char*) bb_basename(path);
138         /* http://kernel.org/doc/pending/hotplug.txt says that only
139          * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
140          * But since 2.6.25 block devices are also in /sys/class/block.
141          * We use strstr("/block/") to forestall future surprises. */
142         type = S_IFCHR;
143         if (strstr(path, "/block/") || (G.subsystem && strncmp(G.subsystem, "block", 5) == 0))
144                 type = S_IFBLK;
145
146         /* Make path point to "subsystem/device_name" */
147         subsystem_slash_devname = NULL;
148         /* Check for coldplug invocations first */
149         if (strncmp(path, "/sys/block/", 11) == 0) /* legacy case */
150                 path += sizeof("/sys/") - 1;
151         else if (strncmp(path, "/sys/class/", 11) == 0)
152                 path += sizeof("/sys/class/") - 1;
153         else {
154                 /* Example of a hotplug invocation:
155                  * SUBSYSTEM="block"
156                  * DEVPATH="/sys" + "/devices/virtual/mtd/mtd3/mtdblock3"
157                  * ("/sys" is added by mdev_main)
158                  * - path does not contain subsystem
159                  */
160                 subsystem_slash_devname = concat_path_file(G.subsystem, device_name);
161                 path = subsystem_slash_devname;
162         }
163
164         /* If we have config file, look up user settings */
165         if (ENABLE_FEATURE_MDEV_CONF)
166                 parser = config_open2("/etc/mdev.conf", fopen_for_read);
167
168         do {
169                 int keep_matching;
170                 struct bb_uidgid_t ugid;
171                 char *tokens[4];
172                 char *command = NULL;
173                 char *alias = NULL;
174                 char aliaslink = aliaslink; /* for compiler */
175
176                 /* Defaults in case we won't match any line */
177                 ugid.uid = ugid.gid = 0;
178                 keep_matching = 0;
179                 mode = 0660;
180
181                 if (ENABLE_FEATURE_MDEV_CONF
182                  && config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)
183                 ) {
184                         char *val;
185                         char *str_to_match;
186                         regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
187
188                         val = tokens[0];
189                         keep_matching = ('-' == val[0]);
190                         val += keep_matching; /* swallow leading dash */
191
192                         /* Match against either "subsystem/device_name"
193                          * or "device_name" alone */
194                         str_to_match = strchr(val, '/') ? path : device_name;
195
196                         /* Fields: regex uid:gid mode [alias] [cmd] */
197
198                         if (val[0] == '@') {
199                                 /* @major,minor[-minor2] */
200                                 /* (useful when name is ambiguous:
201                                  * "/sys/class/usb/lp0" and
202                                  * "/sys/class/printer/lp0") */
203                                 int cmaj, cmin0, cmin1, sc;
204                                 if (major < 0)
205                                         continue; /* no dev, no match */
206                                 sc = sscanf(val, "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
207                                 if (sc < 1
208                                  || major != cmaj
209                                  || (sc == 2 && minor != cmin0)
210                                  || (sc == 3 && (minor < cmin0 || minor > cmin1))
211                                 ) {
212                                         continue; /* this line doesn't match */
213                                 }
214                                 goto line_matches;
215                         }
216                         if (val[0] == '$') {
217                                 /* regex to match an environment variable */
218                                 char *eq = strchr(++val, '=');
219                                 if (!eq)
220                                         continue;
221                                 *eq = '\0';
222                                 str_to_match = getenv(val);
223                                 if (!str_to_match)
224                                         continue;
225                                 str_to_match -= strlen(val) + 1;
226                                 *eq = '=';
227                         }
228                         /* else: regex to match [subsystem/]device_name */
229
230                         {
231                                 regex_t match;
232                                 int result;
233
234                                 xregcomp(&match, val, REG_EXTENDED);
235                                 result = regexec(&match, str_to_match, ARRAY_SIZE(off), off, 0);
236                                 regfree(&match);
237                                 //bb_error_msg("matches:");
238                                 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
239                                 //      if (off[i].rm_so < 0) continue;
240                                 //      bb_error_msg("match %d: '%.*s'\n", i,
241                                 //              (int)(off[i].rm_eo - off[i].rm_so),
242                                 //              device_name + off[i].rm_so);
243                                 //}
244
245                                 /* If no match, skip rest of line */
246                                 /* (regexec returns whole pattern as "range" 0) */
247                                 if (result
248                                  || off[0].rm_so
249                                  || ((int)off[0].rm_eo != (int)strlen(str_to_match))
250                                 ) {
251                                         continue; /* this line doesn't match */
252                                 }
253                         }
254  line_matches:
255                         /* This line matches. Stop parsing after parsing
256                          * the rest the line unless keep_matching == 1 */
257
258                         /* 2nd field: uid:gid - device ownership */
259                         if (get_uidgid(&ugid, tokens[1], 1) == 0)
260                                 bb_error_msg("unknown user/group %s on line %d", tokens[1], parser->lineno);
261
262                         /* 3rd field: mode - device permissions */
263                         bb_parse_mode(tokens[2], &mode);
264
265                         val = tokens[3];
266                         /* 4th field (opt): ">|=alias" or "!" to not create the node */
267
268                         if (ENABLE_FEATURE_MDEV_RENAME && val) {
269                                 char *a, *s, *st;
270
271                                 a = val;
272                                 s = strchrnul(val, ' ');
273                                 st = strchrnul(val, '\t');
274                                 if (st < s)
275                                         s = st;
276                                 st = (s[0] && s[1]) ? s+1 : NULL;
277
278                                 aliaslink = a[0];
279                                 if (aliaslink == '!' && s == a+1) {
280                                         val = st;
281                                         /* "!": suppress node creation/deletion */
282                                         major = -1;
283                                 }
284                                 else if (aliaslink == '>' || aliaslink == '=') {
285                                         val = st;
286                                         s[0] = '\0';
287                                         if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
288                                                 char *p;
289                                                 unsigned i, n;
290
291                                                 /* substitute %1..9 with off[1..9], if any */
292                                                 n = 0;
293                                                 s = a;
294                                                 while (*s)
295                                                         if (*s++ == '%')
296                                                                 n++;
297
298                                                 p = alias = xzalloc(strlen(a) + n * strlen(str_to_match));
299                                                 s = a + 1;
300                                                 while (*s) {
301                                                         *p = *s;
302                                                         if ('%' == *s) {
303                                                                 i = (s[1] - '0');
304                                                                 if (i <= 9 && off[i].rm_so >= 0) {
305                                                                         n = off[i].rm_eo - off[i].rm_so;
306                                                                         strncpy(p, str_to_match + off[i].rm_so, n);
307                                                                         p += n - 1;
308                                                                         s++;
309                                                                 }
310                                                         }
311                                                         p++;
312                                                         s++;
313                                                 }
314                                         } else {
315                                                 alias = xstrdup(a + 1);
316                                         }
317                                 }
318                         }
319
320                         if (ENABLE_FEATURE_MDEV_EXEC && val) {
321                                 const char *s = "$@*";
322                                 const char *s2 = strchr(s, val[0]);
323
324                                 if (!s2) {
325                                         bb_error_msg("bad line %u", parser->lineno);
326                                         if (ENABLE_FEATURE_MDEV_RENAME)
327                                                 free(alias);
328                                         continue;
329                                 }
330
331                                 /* Are we running this command now?
332                                  * Run $cmd on delete, @cmd on create, *cmd on both
333                                  */
334                                 if (s2 - s != delete) {
335                                         /* We are here if: '*',
336                                          * or: '@' and delete = 0,
337                                          * or: '$' and delete = 1
338                                          */
339                                         command = xstrdup(val + 1);
340                                 }
341                         }
342                 }
343
344                 /* End of field parsing */
345
346                 /* "Execute" the line we found */
347                 {
348                         const char *node_name;
349
350                         node_name = device_name;
351                         if (ENABLE_FEATURE_MDEV_RENAME && alias)
352                                 node_name = alias = build_alias(alias, device_name);
353
354                         if (!delete && major >= 0) {
355                                 if (mknod(node_name, mode | type, makedev(major, minor)) && errno != EEXIST)
356                                         bb_perror_msg("can't create '%s'", node_name);
357                                 if (major == G.root_major && minor == G.root_minor)
358                                         symlink(node_name, "root");
359                                 if (ENABLE_FEATURE_MDEV_CONF) {
360                                         chmod(node_name, mode);
361                                         chown(node_name, ugid.uid, ugid.gid);
362                                 }
363                                 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
364                                         if (aliaslink == '>')
365                                                 symlink(node_name, device_name);
366                                 }
367                         }
368
369                         if (ENABLE_FEATURE_MDEV_EXEC && command) {
370                                 /* setenv will leak memory, use putenv/unsetenv/free */
371                                 char *s = xasprintf("%s=%s", "MDEV", node_name);
372                                 char *s1 = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
373                                 putenv(s);
374                                 putenv(s1);
375                                 if (system(command) == -1)
376                                         bb_perror_msg("can't run '%s'", command);
377                                 bb_unsetenv_and_free(s1);
378                                 bb_unsetenv_and_free(s);
379                                 free(command);
380                         }
381
382                         if (delete && major >= 0) {
383                                 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
384                                         if (aliaslink == '>')
385                                                 unlink(device_name);
386                                 }
387                                 unlink(node_name);
388                         }
389
390                         if (ENABLE_FEATURE_MDEV_RENAME)
391                                 free(alias);
392                 }
393
394                 /* We found matching line.
395                  * Stop unless it was prefixed with '-' */
396                 if (ENABLE_FEATURE_MDEV_CONF && !keep_matching)
397                         break;
398
399         /* end of "while line is read from /etc/mdev.conf" */
400         } while (ENABLE_FEATURE_MDEV_CONF);
401
402         if (ENABLE_FEATURE_MDEV_CONF)
403                 config_close(parser);
404         free(subsystem_slash_devname);
405 }
406
407 /* File callback for /sys/ traversal */
408 static int FAST_FUNC fileAction(const char *fileName,
409                 struct stat *statbuf UNUSED_PARAM,
410                 void *userData,
411                 int depth UNUSED_PARAM)
412 {
413         size_t len = strlen(fileName) - 4; /* can't underflow */
414         char *scratch = userData;
415
416         /* len check is for paranoid reasons */
417         if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
418                 return FALSE;
419
420         strcpy(scratch, fileName);
421         scratch[len] = '\0';
422         make_device(scratch, /*delete:*/ 0);
423
424         return TRUE;
425 }
426
427 /* Directory callback for /sys/ traversal */
428 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
429                 struct stat *statbuf UNUSED_PARAM,
430                 void *userData UNUSED_PARAM,
431                 int depth)
432 {
433         /* Extract device subsystem -- the name of the directory
434          * under /sys/class/ */
435         if (1 == depth) {
436                 free(G.subsystem);
437                 G.subsystem = strrchr(fileName, '/');
438                 if (G.subsystem)
439                         G.subsystem = xstrdup(G.subsystem + 1);
440         }
441
442         return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
443 }
444
445 /* For the full gory details, see linux/Documentation/firmware_class/README
446  *
447  * Firmware loading works like this:
448  * - kernel sets FIRMWARE env var
449  * - userspace checks /lib/firmware/$FIRMWARE
450  * - userspace waits for /sys/$DEVPATH/loading to appear
451  * - userspace writes "1" to /sys/$DEVPATH/loading
452  * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
453  * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
454  * - kernel loads firmware into device
455  */
456 static void load_firmware(const char *firmware, const char *sysfs_path)
457 {
458         int cnt;
459         int firmware_fd, loading_fd, data_fd;
460
461         /* check for /lib/firmware/$FIRMWARE */
462         xchdir("/lib/firmware");
463         firmware_fd = xopen(firmware, O_RDONLY);
464
465         /* in case we goto out ... */
466         data_fd = -1;
467
468         /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
469         xchdir(sysfs_path);
470         for (cnt = 0; cnt < 30; ++cnt) {
471                 loading_fd = open("loading", O_WRONLY);
472                 if (loading_fd != -1)
473                         goto loading;
474                 sleep(1);
475         }
476         goto out;
477
478  loading:
479         /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
480         if (full_write(loading_fd, "1", 1) != 1)
481                 goto out;
482
483         /* load firmware into /sys/$DEVPATH/data */
484         data_fd = open("data", O_WRONLY);
485         if (data_fd == -1)
486                 goto out;
487         cnt = bb_copyfd_eof(firmware_fd, data_fd);
488
489         /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
490         if (cnt > 0)
491                 full_write(loading_fd, "0", 1);
492         else
493                 full_write(loading_fd, "-1", 2);
494
495  out:
496         if (ENABLE_FEATURE_CLEAN_UP) {
497                 close(firmware_fd);
498                 close(loading_fd);
499                 close(data_fd);
500         }
501 }
502
503 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
504 int mdev_main(int argc UNUSED_PARAM, char **argv)
505 {
506         RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
507
508         /* We can be called as hotplug helper */
509         /* Kernel cannot provide suitable stdio fds for us, do it ourself */
510         bb_sanitize_stdio();
511
512         /* Force the configuration file settings exactly */
513         umask(0);
514
515         xchdir("/dev");
516
517         if (argv[1] && strcmp(argv[1], "-s") == 0) {
518                 /* Scan:
519                  * mdev -s
520                  */
521                 struct stat st;
522
523                 xstat("/", &st);
524                 G.root_major = major(st.st_dev);
525                 G.root_minor = minor(st.st_dev);
526
527                 /* ACTION_FOLLOWLINKS is needed since in newer kernels
528                  * /sys/block/loop* (for example) are symlinks to dirs,
529                  * not real directories.
530                  * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
531                  * but we can't enforce that on users)
532                  */
533                 if (access("/sys/class/block", F_OK) != 0) {
534                         /* Scan obsolete /sys/block only if /sys/class/block
535                          * doesn't exist. Otherwise we'll have dupes.
536                          * Also, do not complain if it doesn't exist.
537                          * Some people configure kernel to have no blockdevs.
538                          */
539                         recursive_action("/sys/block",
540                                 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
541                                 fileAction, dirAction, temp, 0);
542                 }
543                 recursive_action("/sys/class",
544                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
545                         fileAction, dirAction, temp, 0);
546         } else {
547                 char *fw;
548                 char *seq;
549                 char *action;
550                 char *env_path;
551                 static const char keywords[] ALIGN1 = "remove\0add\0";
552                 enum { OP_remove = 0, OP_add };
553                 smalluint op;
554
555                 /* Hotplug:
556                  * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
557                  * ACTION can be "add" or "remove"
558                  * DEVPATH is like "/block/sda" or "/class/input/mice"
559                  */
560                 action = getenv("ACTION");
561                 env_path = getenv("DEVPATH");
562                 G.subsystem = getenv("SUBSYSTEM");
563                 if (!action || !env_path /*|| !G.subsystem*/)
564                         bb_show_usage();
565                 fw = getenv("FIRMWARE");
566                 op = index_in_strings(keywords, action);
567                 /* If it exists, does /dev/mdev.seq match $SEQNUM?
568                  * If it does not match, earlier mdev is running
569                  * in parallel, and we need to wait */
570                 seq = getenv("SEQNUM");
571                 if (seq) {
572                         int timeout = 2000 / 32; /* 2000 msec */
573                         do {
574                                 int seqlen;
575                                 char seqbuf[sizeof(int)*3 + 2];
576
577                                 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
578                                 if (seqlen < 0) {
579                                         seq = NULL;
580                                         break;
581                                 }
582                                 seqbuf[seqlen] = '\0';
583                                 if (seqbuf[0] == '\n' /* seed file? */
584                                  || strcmp(seq, seqbuf) == 0 /* correct idx? */
585                                 ) {
586                                         break;
587                                 }
588                                 usleep(32*1000);
589                         } while (--timeout);
590                 }
591
592                 snprintf(temp, PATH_MAX, "/sys%s", env_path);
593                 if (op == OP_remove) {
594                         /* Ignoring "remove firmware". It was reported
595                          * to happen and to cause erroneous deletion
596                          * of device nodes. */
597                         if (!fw)
598                                 make_device(temp, /*delete:*/ 1);
599                 }
600                 else if (op == OP_add) {
601                         make_device(temp, /*delete:*/ 0);
602                         if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
603                                 if (fw)
604                                         load_firmware(fw, temp);
605                         }
606                 }
607
608                 if (seq) {
609                         xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
610                 }
611         }
612
613         if (ENABLE_FEATURE_CLEAN_UP)
614                 RELEASE_CONFIG_BUFFER(temp);
615
616         return EXIT_SUCCESS;
617 }