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