f6440b19011e9725b76b632edf1468efdfcc910d
[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 #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         const char *device_name;
59         int major, minor, type, len;
60         int mode = 0660;
61 #if ENABLE_FEATURE_MDEV_CONF
62         uid_t uid = 0;
63         gid_t gid = 0;
64         parser_t *parser;
65         char *tokens[5];
66 #endif
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         char *dev_maj_min = path + strlen(path);
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         parser = config_open2("/etc/mdev.conf", fopen_for_read);
108
109         /* If we have config file, look up user settings */
110         if (!parser)
111                 goto end_parse;
112
113         while (config_read(parser, tokens, 4, 3, "# \t", PARSE_LAST_IS_GREEDY)) {
114                 regmatch_t off[1 + 9*ENABLE_FEATURE_MDEV_RENAME_REGEXP];
115                 char *val;
116
117                 /* Fields: regex uid:gid mode [alias] [cmd] */
118
119                 /* 1st field: regex to match this device */
120                 {
121                         regex_t match;
122                         int result;
123
124                         /* Is this it? */
125                         xregcomp(&match, tokens[0], REG_EXTENDED);
126                         result = regexec(&match, device_name, ARRAY_SIZE(off), off, 0);
127                         regfree(&match);
128
129                         //bb_error_msg("matches:");
130                         //for (int i = 0; i < ARRAY_SIZE(off); i++) {
131                         //      if (off[i].rm_so < 0) continue;
132                         //      bb_error_msg("match %d: '%.*s'\n", i,
133                         //              (int)(off[i].rm_eo - off[i].rm_so),
134                         //              device_name + off[i].rm_so);
135                         //}
136
137                         /* If not this device, skip rest of line */
138                         /* (regexec returns whole pattern as "range" 0) */
139                         if (result || off[0].rm_so
140                          || ((int)off[0].rm_eo != (int)strlen(device_name))
141                         ) {
142                                 continue;
143                         }
144                 }
145
146                 /* This line matches: stop parsing the file
147                  * after parsing the rest of fields */
148
149                 /* 2nd field: uid:gid - device ownership */
150                 {
151                         struct passwd *pass;
152                         struct group *grp;
153                         char *str_uid = tokens[1];
154                         char *str_gid = strchrnul(str_uid, ':');
155
156                         if (*str_gid)
157                                 *str_gid++ = '\0';
158                         /* Parse UID */
159                         pass = getpwnam(str_uid);
160                         if (pass)
161                                 uid = pass->pw_uid;
162                         else
163                                 uid = strtoul(str_uid, NULL, 10);
164                         /* Parse GID */
165                         grp = getgrnam(str_gid);
166                         if (grp)
167                                 gid = grp->gr_gid;
168                         else
169                                 gid = strtoul(str_gid, NULL, 10);
170                 }
171
172                 /* 3rd field: mode - device permissions */
173                 mode = strtoul(tokens[2], NULL, 8);
174
175                 val = tokens[3];
176                 /* 4th field (opt): >alias */
177 #if ENABLE_FEATURE_MDEV_RENAME
178                 if (!val)
179                         break;
180                 aliaslink = *val;
181                 if (aliaslink == '>' || aliaslink == '=') {
182                         char *s;
183 #if ENABLE_FEATURE_MDEV_RENAME_REGEXP
184                         char *p;
185                         unsigned i, n;
186 #endif
187                         char *a = val;
188                         s = strchr(val, ' ');
189                         val = (s && s[1]) ? s+1 : NULL;
190 #if ENABLE_FEATURE_MDEV_RENAME_REGEXP
191                         /* substitute %1..9 with off[1..9], if any */
192                         n = 0;
193                         s = a;
194                         while (*s)
195                                 if (*s++ == '%')
196                                         n++;
197
198                         p = alias = xzalloc(strlen(a) + n * strlen(device_name));
199                         s = a + 1;
200                         while (*s) {
201                                 *p = *s;
202                                 if ('%' == *s) {
203                                         i = (s[1] - '0');
204                                         if (i <= 9 && off[i].rm_so >= 0) {
205                                                 n = off[i].rm_eo - off[i].rm_so;
206                                                 strncpy(p, device_name + off[i].rm_so, n);
207                                                 p += n - 1;
208                                                 s++;
209                                         }
210                                 }
211                                 p++;
212                                 s++;
213                         }
214 #else
215                         alias = xstrdup(a + 1);
216 #endif
217                 }
218 #endif /* ENABLE_FEATURE_MDEV_RENAME */
219
220 #if ENABLE_FEATURE_MDEV_EXEC
221                 /* The rest (opt): command to run */
222                 if (!val)
223                         break;
224                 {
225                         const char *s = "@$*";
226                         const char *s2 = strchr(s, *val);
227
228                         if (!s2)
229                                 bb_error_msg_and_die("bad line %u", parser->lineno);
230
231                         /* Correlate the position in the "@$*" with the delete
232                          * step so that we get the proper behavior:
233                          * @cmd: run on create
234                          * $cmd: run on delete
235                          * *cmd: run on both
236                          */
237                         if ((s2 - s + 1) /*1/2/3*/ & /*1/2*/ (1 + delete)) {
238                                 command = xstrdup(val + 1);
239                         }
240                 }
241 #endif
242                 /* end of field parsing */
243                 break; /* we found matching line, stop */
244         } /* end of "while line is read from /etc/mdev.conf" */
245
246         config_close(parser);
247  end_parse:
248 #endif /* ENABLE_FEATURE_MDEV_CONF */
249
250         if (!delete && sscanf(dev_maj_min, "%u:%u", &major, &minor) == 2) {
251
252                 if (ENABLE_FEATURE_MDEV_RENAME)
253                         unlink(device_name);
254
255                 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
256                         bb_perror_msg_and_die("mknod %s", device_name);
257
258                 if (major == root_major && minor == root_minor)
259                         symlink(device_name, "root");
260
261 #if ENABLE_FEATURE_MDEV_CONF
262                 chown(device_name, uid, gid);
263
264 #if ENABLE_FEATURE_MDEV_RENAME
265                 if (alias) {
266                         alias = build_alias(alias, device_name);
267
268                         /* move the device, and optionally
269                          * make a symlink to moved device node */
270                         if (rename(device_name, alias) == 0 && aliaslink == '>')
271                                 symlink(alias, device_name);
272
273                         free(alias);
274                 }
275 #endif
276 #endif
277         }
278
279 #if ENABLE_FEATURE_MDEV_EXEC
280         if (command) {
281                 /* setenv will leak memory, use putenv/unsetenv/free */
282                 char *s = xasprintf("MDEV=%s", device_name);
283                 putenv(s);
284                 if (system(command) == -1)
285                         bb_perror_msg_and_die("can't run '%s'", command);
286                 s[4] = '\0';
287                 unsetenv(s);
288                 free(s);
289                 free(command);
290         }
291 #endif
292
293         if (delete) {
294                 unlink(device_name);
295                 /* At creation time, device might have been moved
296                  * and a symlink might have been created. Undo that. */
297 #if ENABLE_FEATURE_MDEV_RENAME
298                 if (alias) {
299                         alias = build_alias(alias, device_name);
300                         unlink(alias);
301                         free(alias);
302                 }
303 #endif
304         }
305 }
306
307 /* File callback for /sys/ traversal */
308 static int FAST_FUNC fileAction(const char *fileName,
309                 struct stat *statbuf UNUSED_PARAM,
310                 void *userData,
311                 int depth UNUSED_PARAM)
312 {
313         size_t len = strlen(fileName) - 4; /* can't underflow */
314         char *scratch = userData;
315
316         /* len check is for paranoid reasons */
317         if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
318                 return FALSE;
319
320         strcpy(scratch, fileName);
321         scratch[len] = '\0';
322         make_device(scratch, 0);
323
324         return TRUE;
325 }
326
327 /* Directory callback for /sys/ traversal */
328 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
329                 struct stat *statbuf UNUSED_PARAM,
330                 void *userData UNUSED_PARAM,
331                 int depth)
332 {
333         return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
334 }
335
336 /* For the full gory details, see linux/Documentation/firmware_class/README
337  *
338  * Firmware loading works like this:
339  * - kernel sets FIRMWARE env var
340  * - userspace checks /lib/firmware/$FIRMWARE
341  * - userspace waits for /sys/$DEVPATH/loading to appear
342  * - userspace writes "1" to /sys/$DEVPATH/loading
343  * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
344  * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
345  * - kernel loads firmware into device
346  */
347 static void load_firmware(const char *const firmware, const char *const sysfs_path)
348 {
349         int cnt;
350         int firmware_fd, loading_fd, data_fd;
351
352         /* check for /lib/firmware/$FIRMWARE */
353         xchdir("/lib/firmware");
354         firmware_fd = xopen(firmware, O_RDONLY);
355
356         /* in case we goto out ... */
357         data_fd = -1;
358
359         /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
360         xchdir(sysfs_path);
361         for (cnt = 0; cnt < 30; ++cnt) {
362                 loading_fd = open("loading", O_WRONLY);
363                 if (loading_fd != -1)
364                         goto loading;
365                 sleep(1);
366         }
367         goto out;
368
369  loading:
370         /* tell kernel we're loading by `echo 1 > /sys/$DEVPATH/loading` */
371         if (full_write(loading_fd, "1", 1) != 1)
372                 goto out;
373
374         /* load firmware by `cat /lib/firmware/$FIRMWARE > /sys/$DEVPATH/data */
375         data_fd = open("data", O_WRONLY);
376         if (data_fd == -1)
377                 goto out;
378         cnt = bb_copyfd_eof(firmware_fd, data_fd);
379
380         /* tell kernel result by `echo [0|-1] > /sys/$DEVPATH/loading` */
381         if (cnt > 0)
382                 full_write(loading_fd, "0", 1);
383         else
384                 full_write(loading_fd, "-1", 2);
385
386  out:
387         if (ENABLE_FEATURE_CLEAN_UP) {
388                 close(firmware_fd);
389                 close(loading_fd);
390                 close(data_fd);
391         }
392 }
393
394 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
395 int mdev_main(int argc UNUSED_PARAM, char **argv)
396 {
397         RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
398
399         /* We can be called as hotplug helper */
400         /* Kernel cannot provide suitable stdio fds for us, do it ourself */
401 #if 1
402         bb_sanitize_stdio();
403 #else
404         /* Debug code */
405         /* Replace LOGFILE by other file or device name if you need */
406 #define LOGFILE "/dev/console"
407         /* Just making sure fd 0 is not closed,
408          * we don't really intend to read from it */
409         xmove_fd(xopen("/", O_RDONLY), STDIN_FILENO);
410         xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDOUT_FILENO);
411         xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDERR_FILENO);
412 #endif
413
414         xchdir("/dev");
415
416         if (argv[1] && !strcmp(argv[1], "-s")) {
417                 /* Scan:
418                  * mdev -s
419                  */
420                 struct stat st;
421
422                 xstat("/", &st);
423                 root_major = major(st.st_dev);
424                 root_minor = minor(st.st_dev);
425
426                 /* ACTION_FOLLOWLINKS is needed since in newer kernels
427                  * /sys/block/loop* (for example) are symlinks to dirs,
428                  * not real directories.
429                  * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
430                  * but we can't enforce that on users) */
431                 recursive_action("/sys/block",
432                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
433                         fileAction, dirAction, temp, 0);
434                 recursive_action("/sys/class",
435                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
436                         fileAction, dirAction, temp, 0);
437         } else {
438                 char *seq;
439                 char *action;
440                 char *env_path;
441                 char seqbuf[sizeof(int)*3 + 2];
442                 int seqlen = seqlen; /* for compiler */
443
444                 /* Hotplug:
445                  * env ACTION=... DEVPATH=... [SEQNUM=...] mdev
446                  * ACTION can be "add" or "remove"
447                  * DEVPATH is like "/block/sda" or "/class/input/mice"
448                  */
449                 action = getenv("ACTION");
450                 env_path = getenv("DEVPATH");
451                 if (!action || !env_path)
452                         bb_show_usage();
453
454                 seq = getenv("SEQNUM");
455                 if (seq) {
456                         int timeout = 2000 / 32;
457                         do {
458                                 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
459                                 if (seqlen < 0)
460                                         break;
461                                 seqbuf[seqlen] = '\0';
462                                 if (seqbuf[0] == '\n' /* seed file? */
463                                  || strcmp(seq, seqbuf) == 0 /* correct idx? */
464                                 ) {
465                                         break;
466                                 }
467                                 usleep(32*1000);
468                         } while (--timeout);
469                 }
470
471                 snprintf(temp, PATH_MAX, "/sys%s", env_path);
472                 if (!strcmp(action, "remove"))
473                         make_device(temp, 1);
474                 else if (!strcmp(action, "add")) {
475                         make_device(temp, 0);
476
477                         if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
478                                 char *fw = getenv("FIRMWARE");
479                                 if (fw)
480                                         load_firmware(fw, temp);
481                         }
482                 }
483
484                 if (seq && seqlen >= 0) {
485                         xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
486                 }
487         }
488
489         if (ENABLE_FEATURE_CLEAN_UP)
490                 RELEASE_CONFIG_BUFFER(temp);
491
492         return 0;
493 }