restart stopped instances on update
[project/procd.git] / 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 "procd.h"
30
31 static char **patterns;
32 static int n_patterns;
33 static char buf[PATH_MAX];
34 static char buf2[PATH_MAX];
35 static unsigned int mode = 0600;
36
37 static bool find_pattern(const char *name)
38 {
39 int i;
40
41 for (i = 0; i < n_patterns; i++)
42 if (!fnmatch(patterns[i], name, 0))
43 return true;
44
45 return false;
46 }
47
48 static void make_dev(const char *path, bool block, int major, int minor)
49 {
50 unsigned int _mode = mode | (block ? S_IFBLK : S_IFCHR);
51 DEBUG(2, "Creating %s device %s(%d,%d)\n",
52 block ? "block" : "character",
53 path, major, minor);
54
55 mknod(path, _mode, makedev(major, minor));
56 }
57
58 static void find_devs(bool block)
59 {
60 char *path = block ? "/sys/dev/block" : "/sys/dev/char";
61 struct dirent *dp;
62 DIR *dir;
63
64 dir = opendir(path);
65 if (!dir)
66 return;
67
68 path = buf2 + sprintf(buf2, "%s/", path);
69 while ((dp = readdir(dir)) != NULL) {
70 char *c;
71 int major = 0, minor = 0;
72 int len;
73
74 if (dp->d_type != DT_LNK)
75 continue;
76
77 if (sscanf(dp->d_name, "%d:%d", &major, &minor) != 2)
78 continue;
79
80 strcpy(path, dp->d_name);
81 len = readlink(buf2, buf, sizeof(buf));
82 if (len <= 0)
83 continue;
84
85 buf[len] = 0;
86 if (!find_pattern(buf))
87 continue;
88
89 c = strrchr(buf, '/');
90 if (!c)
91 continue;
92
93 c++;
94 make_dev(c, block, major, minor);
95 }
96 closedir(dir);
97 }
98
99 static char *add_pattern(const char *name)
100 {
101 char *str = malloc(strlen(name) + 2);
102
103 str[0] = '*';
104 strcpy(str + 1, name);
105 return str;
106 }
107
108 int mkdev(const char *name, int _mode)
109 {
110 char *pattern;
111
112 if (chdir("/dev"))
113 return 1;
114
115 pattern = add_pattern(name);
116 patterns = &pattern;
117 mode = _mode;
118 n_patterns = 1;
119 find_devs(true);
120 find_devs(false);
121 chdir("/");
122
123 return 0;
124 }