Debian Codegraph @

src/libsystemd/sd-device/device-filter.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-device.h"
4
5 #include "alloc-util.h"
6 #include "device-filter.h"
7 #include "hashmap.h"
8 #include "path-util.h"
9 #include "set.h"
10 #include "strv.h"
11
12 int update_match_strv(Hashmap **match_strv, const char *key, const char *value, bool clear_on_null) {
13 char **strv;
14 int r;
15
16 assert(match_strv);
17 assert(key);
18
19 strv = hashmap_get(*match_strv, key);
20 if (strv) {
21 if (!value) {
22 char **v;
23
24 if (strv_isempty(strv) || !clear_on_null)
25 return 0;
26
27 /* Accept all value. Clear previous assignment. */
28
29 v = new0(char*, 1);
30 if (!v)
31 return -ENOMEM;
32
33 strv_free_and_replace(strv, v);
34 } else {
35 if (strv_contains(strv, value))
36 return 0;
37
38 r = strv_extend(&strv, value);
39 if (r < 0)
40 return r;
41 }
42
43 r = hashmap_update(*match_strv, key, strv);
44 if (r < 0)
45 return r;
46
47 } else {
48 _cleanup_strv_free_ char **strv_alloc = NULL;
49 _cleanup_free_ char *key_alloc = NULL;
50
51 key_alloc = strdup(key);
52 if (!key_alloc)
53 return -ENOMEM;
54
55 strv_alloc = strv_new(value);
56 if (!strv_alloc)
57 return -ENOMEM;
58
59 r = hashmap_ensure_put(match_strv, &string_hash_ops_free_strv_free, key_alloc, strv_alloc);
60 if (r < 0)
61 return r;
62
63 TAKE_PTR(key_alloc);
64 TAKE_PTR(strv_alloc);
65 }
66
67 return 1;
68 }
69
70 static bool device_match_sysattr_value(sd_device *device, const char *sysattr, char * const *patterns) {
71 const char *value;
72
73 assert(device);
74 assert(sysattr);
75
76 if (sd_device_get_sysattr_value(device, sysattr, &value) < 0)
77 return false;
78
79 return strv_fnmatch_or_empty(patterns, value, 0);
80 }
81
82 bool device_match_sysattr(sd_device *device, Hashmap *match_sysattr, Hashmap *nomatch_sysattr) {
83 char * const *patterns;
84 const char *sysattr;
85
86 assert(device);
87
88 HASHMAP_FOREACH_KEY(patterns, sysattr, match_sysattr)
89 if (!device_match_sysattr_value(device, sysattr, patterns))
90 return false;
91
92 HASHMAP_FOREACH_KEY(patterns, sysattr, nomatch_sysattr)
93 if (device_match_sysattr_value(device, sysattr, patterns))
94 return false;
95
96 return true;
97 }
98
99 bool device_match_parent(sd_device *device, Set *match_parent, Set *nomatch_parent) {
100 const char *syspath_parent, *syspath;
101
102 assert(device);
103
104 if (sd_device_get_syspath(device, &syspath) < 0)
105 return false;
106
107 SET_FOREACH(syspath_parent, nomatch_parent)
108 if (path_startswith(syspath, syspath_parent))
109 return false;
110
111 if (set_isempty(match_parent))
112 return true;
113
114 SET_FOREACH(syspath_parent, match_parent)
115 if (path_startswith(syspath, syspath_parent))
116 return true;
117
118 return false;
119 }