merge fix for blank lines from trunk
[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 /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
25 static void make_device(char *path, int delete)
26 {
27         const char *device_name;
28         int major, minor, type, len;
29         int mode = 0660;
30         uid_t uid = 0;
31         gid_t gid = 0;
32         char *temp = path + strlen(path);
33         char *command = NULL;
34
35         /* Try to read major/minor string.  Note that the kernel puts \n after
36          * the data, so we don't need to worry about null terminating the string
37          * because sscanf() will stop at the first nondigit, which \n is.  We
38          * also depend on path having writeable space after it.
39          */
40         if (!delete) {
41                 strcat(path, "/dev");
42                 len = open_read_close(path, temp + 1, 64);
43                 *temp++ = 0;
44                 if (len < 1)
45                         return;
46         }
47
48         /* Determine device name, type, major and minor */
49         device_name = bb_basename(path);
50         type = (path[5] == 'c' ? S_IFCHR : S_IFBLK);
51
52         if (ENABLE_FEATURE_MDEV_CONF) {
53                 FILE *fp;
54                 char *line, *vline;
55                 unsigned lineno = 0;
56
57                 /* If we have a config file, look up the user settings */
58                 fp = fopen_or_warn("/etc/mdev.conf", "r");
59                 if (!fp)
60                         goto end_parse;
61
62                 while ((vline = line = xmalloc_getline(fp)) != NULL) {
63                         int field;
64
65                         /* A pristine copy for command execution. */
66                         char *orig_line;
67                         if (ENABLE_FEATURE_MDEV_EXEC)
68                                 orig_line = xstrdup(line);
69
70                         ++lineno;
71
72                         /* Three fields: regex, uid:gid, mode */
73                         for (field = 0; field < (3 + ENABLE_FEATURE_MDEV_EXEC); ++field) {
74
75                                 /* Find a non-empty field */
76                                 char *val;
77                                 do {
78                                         val = strtok(vline, " \t");
79                                         vline = NULL;
80                                 } while (val && !*val);
81                                 if (!val) {
82                                         if (field)
83                                                 break;
84                                         else
85                                                 goto next_line;
86                                 }
87
88                                 if (field == 0) {
89
90                                         /* Regex to match this device */
91                                         regex_t match;
92                                         regmatch_t off;
93                                         int result;
94
95                                         /* Is this it? */
96                                         xregcomp(&match, val, REG_EXTENDED);
97                                         result = regexec(&match, device_name, 1, &off, 0);
98                                         regfree(&match);
99
100                                         /* If not this device, skip rest of line */
101                                         if (result || off.rm_so || off.rm_eo != strlen(device_name))
102                                                 goto next_line;
103
104                                 } else if (field == 1) {
105
106                                         /* uid:gid device ownership */
107                                         struct passwd *pass;
108                                         struct group *grp;
109
110                                         char *str_uid = val;
111                                         char *str_gid = strchr(val, ':');
112                                         if (str_gid)
113                                                 *str_gid = '\0', ++str_gid;
114
115                                         /* Parse UID */
116                                         pass = getpwnam(str_uid);
117                                         if (pass)
118                                                 uid = pass->pw_uid;
119                                         else
120                                                 uid = strtoul(str_uid, NULL, 10);
121
122                                         /* parse GID */
123                                         grp = getgrnam(str_gid);
124                                         if (grp)
125                                                 gid = grp->gr_gid;
126                                         else
127                                                 gid = strtoul(str_gid, NULL, 10);
128
129                                 } else if (field == 2) {
130
131                                         /* Mode device permissions */
132                                         mode = strtoul(val, NULL, 8);
133
134                                 } else if (ENABLE_FEATURE_MDEV_EXEC && field == 3) {
135
136                                         /* Optional command to run */
137                                         const char *s = "@$*";
138                                         const char *s2 = strchr(s, *val);
139
140                                         if (!s2) {
141                                                 /* Force error */
142                                                 field = 1;
143                                                 break;
144                                         }
145
146                                         /* Correlate the position in the "@$*" with the delete
147                                          * step so that we get the proper behavior.
148                                          */
149                                         if ((s2 - s + 1) & (1 << delete))
150                                                 command = xstrdup(orig_line + (val + 1 - line));
151                                 }
152                         }
153
154                         /* Did everything parse happily? */
155                         if (field <= 2)
156                                 bb_error_msg_and_die("bad line %u", lineno);
157
158  next_line:
159                         free(line);
160                         if (ENABLE_FEATURE_MDEV_EXEC)
161                                 free(orig_line);
162                 }
163
164                 if (ENABLE_FEATURE_CLEAN_UP)
165                         fclose(fp);
166
167  end_parse:     /* nothing */ ;
168         }
169
170         umask(0);
171         if (!delete) {
172                 if (sscanf(temp, "%d:%d", &major, &minor) != 2)
173                         return;
174                 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
175                         bb_perror_msg_and_die("mknod %s", device_name);
176
177                 if (major == root_major && minor == root_minor)
178                         symlink(device_name, "root");
179
180                 if (ENABLE_FEATURE_MDEV_CONF)
181                         chown(device_name, uid, gid);
182         }
183         if (command) {
184                 /* setenv will leak memory, so use putenv */
185                 char *s = xasprintf("MDEV=%s", device_name);
186                 putenv(s);
187                 if (system(command) == -1)
188                         bb_perror_msg_and_die("cannot run %s", command);
189                 s[4] = '\0';
190                 unsetenv(s);
191                 free(s);
192                 free(command);
193         }
194         if (delete)
195                 remove_file(device_name, FILEUTILS_FORCE);
196 }
197
198 /* File callback for /sys/ traversal */
199 static int fileAction(const char *fileName, struct stat *statbuf,
200                       void *userData, int depth)
201 {
202         size_t len = strlen(fileName) - 4;
203         char *scratch = userData;
204
205         if (strcmp(fileName + len, "/dev"))
206                 return FALSE;
207
208         strcpy(scratch, fileName);
209         scratch[len] = 0;
210         make_device(scratch, 0);
211
212         return TRUE;
213 }
214
215 /* Directory callback for /sys/ traversal */
216 static int dirAction(const char *fileName, struct stat *statbuf,
217                       void *userData, int depth)
218 {
219         return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
220 }
221
222 /* For the full gory details, see linux/Documentation/firmware_class/README
223  *
224  * Firmware loading works like this:
225  * - kernel sets FIRMWARE env var
226  * - userspace checks /lib/firmware/$FIRMWARE
227  * - userspace waits for /sys/$DEVPATH/loading to appear
228  * - userspace writes "1" to /sys/$DEVPATH/loading
229  * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
230  * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
231  * - kernel loads firmware into device
232  */
233 static void load_firmware(const char *const firmware, const char *const sysfs_path)
234 {
235         int cnt;
236         int firmware_fd, loading_fd, data_fd;
237
238         /* check for $FIRMWARE from kernel */
239         /* XXX: dont bother: open(NULL) works same as open("no-such-file")
240          * if (!firmware)
241          *      return;
242          */
243
244         /* check for /lib/firmware/$FIRMWARE */
245         xchdir("/lib/firmware");
246         firmware_fd = xopen(firmware, O_RDONLY);
247
248         /* in case we goto out ... */
249         data_fd = -1;
250
251         /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
252         xchdir(sysfs_path);
253         for (cnt = 0; cnt < 30; ++cnt) {
254                 loading_fd = open("loading", O_WRONLY);
255                 if (loading_fd == -1)
256                         sleep(1);
257                 else
258                         break;
259         }
260         if (loading_fd == -1)
261                 goto out;
262
263         /* tell kernel we're loading by `echo 1 > /sys/$DEVPATH/loading` */
264         if (write(loading_fd, "1", 1) != 1)
265                 goto out;
266
267         /* load firmware by `cat /lib/firmware/$FIRMWARE > /sys/$DEVPATH/data */
268         data_fd = open("data", O_WRONLY);
269         if (data_fd == -1)
270                 goto out;
271         cnt = bb_copyfd_eof(firmware_fd, data_fd);
272
273         /* tell kernel result by `echo [0|-1] > /sys/$DEVPATH/loading` */
274         if (cnt > 0)
275                 write(loading_fd, "0", 1);
276         else
277                 write(loading_fd, "-1", 2);
278
279  out:
280         if (ENABLE_FEATURE_CLEAN_UP) {
281                 close(firmware_fd);
282                 close(loading_fd);
283                 close(data_fd);
284         }
285 }
286
287 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
288 int mdev_main(int argc, char **argv)
289 {
290         char *action;
291         char *env_path;
292         RESERVE_CONFIG_BUFFER(temp,PATH_MAX);
293
294         xchdir("/dev");
295
296         if (argc == 2 && !strcmp(argv[1],"-s")) {
297
298                 /* Scan:
299                  * mdev -s
300                  */
301
302                 struct stat st;
303
304                 xstat("/", &st);
305                 root_major = major(st.st_dev);
306                 root_minor = minor(st.st_dev);
307
308                 recursive_action("/sys/block",
309                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
310                         fileAction, dirAction, temp, 0);
311
312                 recursive_action("/sys/class",
313                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
314                         fileAction, dirAction, temp, 0);
315
316         } else {
317
318                 /* Hotplug:
319                  * env ACTION=... DEVPATH=... mdev
320                  * ACTION can be "add" or "remove"
321                  * DEVPATH is like "/block/sda" or "/class/input/mice"
322                  */
323
324                 action = getenv("ACTION");
325                 env_path = getenv("DEVPATH");
326                 if (!action || !env_path)
327                         bb_show_usage();
328
329                 sprintf(temp, "/sys%s", env_path);
330                 if (!strcmp(action, "remove"))
331                         make_device(temp, 1);
332                 else if (!strcmp(action, "add")) {
333                         make_device(temp, 0);
334
335                         if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE)
336                                 load_firmware(getenv("FIRMWARE"), temp);
337                 }
338         }
339
340         if (ENABLE_FEATURE_CLEAN_UP)
341                 RELEASE_CONFIG_BUFFER(temp);
342
343         return 0;
344 }