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