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