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