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