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