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