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