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