3d067b255d73c1b54e9acdf0fb07f785c520a1dc
[project/ubox.git] / libblkid-tiny / mkdev.c
1 /*
2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15 #define _BSD_SOURCE
16
17 #include <sys/stat.h>
18 #include <sys/types.h>
19
20 #include <stdio.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <stdbool.h>
25 #include <dirent.h>
26 #include <limits.h>
27 #include <fnmatch.h>
28
29 #include "libblkid-tiny.h"
30
31 #include <syslog.h>
32
33 static char buf[PATH_MAX];
34 static char buf2[PATH_MAX];
35 static unsigned int mode = 0600;
36
37 static void make_dev(const char *path, bool block, int major, int minor)
38 {
39 unsigned int _mode = mode | (block ? S_IFBLK : S_IFCHR);
40
41 mknod(path, _mode, makedev(major, minor));
42 }
43
44 static void find_devs(bool block)
45 {
46 char *path = block ? "/sys/dev/block" : "/sys/dev/char";
47 struct dirent *dp;
48 DIR *dir;
49
50 dir = opendir(path);
51 if (!dir)
52 return;
53
54 path = buf2 + sprintf(buf2, "%s/", path);
55 while ((dp = readdir(dir)) != NULL) {
56 char *c;
57 int major = 0, minor = 0;
58 int len;
59
60 if (dp->d_type != DT_LNK)
61 continue;
62
63 if (sscanf(dp->d_name, "%d:%d", &major, &minor) != 2)
64 continue;
65
66 strcpy(path, dp->d_name);
67 len = readlink(buf2, buf, sizeof(buf));
68 if (len <= 0)
69 continue;
70
71 buf[len] = 0;
72
73 c = strrchr(buf, '/');
74 if (!c)
75 continue;
76
77
78 c++;
79 make_dev(c, block, major, minor);
80 }
81 closedir(dir);
82 }
83
84 int mkblkdev(void)
85 {
86 if (chdir("/dev"))
87 return 1;
88
89 mode = 0600;
90 find_devs(true);
91 chdir("/");
92
93 return 0;
94 }