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