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