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