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