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