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