1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "alloc-util.h"
11 #include "device-nodes.h"
12 #include "device-private.h"
13 #include "device-util.h"
14 #include "errno-util.h"
17 #include "path-util.h"
18 #include "stat-util.h"
19 #include "string-util.h"
21 #include "udev-util.h"
24 int udev_parse_config_full(const ConfigTableItem config_table
[]) {
29 r
= config_parse_standard_file_with_dropins(
31 /* sections = */ NULL
,
32 config_item_table_lookup
, config_table
,
34 /* userdata = */ NULL
);
40 int udev_parse_config(void) {
42 const ConfigTableItem config_table
[] = {
43 { NULL
, "udev_log", config_parse_log_level
, 0, &log_val
},
44 { NULL
, "children_max", NULL
, 0, NULL
},
45 { NULL
, "exec_delay", NULL
, 0, NULL
},
46 { NULL
, "event_timeout", NULL
, 0, NULL
},
47 { NULL
, "resolve_names", NULL
, 0, NULL
},
48 { NULL
, "timeout_signal", NULL
, 0, NULL
},
52 r
= udev_parse_config_full(config_table
);
57 log_set_max_level(log_val
);
62 struct DeviceMonitorData
{
68 static void device_monitor_data_free(struct DeviceMonitorData
*d
) {
71 sd_device_unref(d
->device
);
74 static int device_monitor_handler(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
75 struct DeviceMonitorData
*data
= ASSERT_PTR(userdata
);
79 assert(data
->sysname
|| data
->devlink
);
80 assert(!data
->device
);
82 /* Ignore REMOVE events here. We are waiting for initialization after all, not de-initialization. We
83 * might see a REMOVE event from an earlier use of the device (devices by the same name are recycled
84 * by the kernel after all), which we should not get confused by. After all we cannot distinguish use
85 * cycles of the devices, as the udev queue is entirely asynchronous.
87 * If we see a REMOVE event here for the use cycle we actually care about then we won't notice of
88 * course, but that should be OK, given the timeout logic used on the wait loop: this will be noticed
89 * by means of -ETIMEDOUT. Thus we won't notice immediately, but eventually, and that should be
90 * sufficient for an error path that should regularly not happen.
92 * (And yes, we only need to special case REMOVE. It's the only "negative" event type, where a device
93 * ceases to exist. All other event types are "positive": the device exists and is registered in the
94 * udev database, thus whenever we see the event, we can consider it initialized.) */
95 if (device_for_action(device
, SD_DEVICE_REMOVE
))
98 if (data
->sysname
&& sd_device_get_sysname(device
, &sysname
) >= 0 && streq(sysname
, data
->sysname
))
104 FOREACH_DEVICE_DEVLINK(device
, link
)
105 if (path_equal(link
, data
->devlink
))
108 if (sd_device_get_devname(device
, &devlink
) >= 0 && path_equal(devlink
, data
->devlink
))
115 data
->device
= sd_device_ref(device
);
116 return sd_event_exit(sd_device_monitor_get_event(monitor
), 0);
119 static int device_wait_for_initialization_internal(
122 const char *subsystem
,
126 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
127 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
128 /* Ensure that if !_device && devlink, device gets unrefd on errors since it will be new */
129 _cleanup_(sd_device_unrefp
) sd_device
*device
= sd_device_ref(_device
);
130 _cleanup_(device_monitor_data_free
) struct DeviceMonitorData data
= {
135 assert(device
|| (subsystem
&& devlink
));
137 /* Devlink might already exist, if it does get the device to use the sysname filtering */
138 if (!device
&& devlink
) {
139 r
= sd_device_new_from_devname(&device
, devlink
);
140 if (r
< 0 && !ERRNO_IS_DEVICE_ABSENT(r
))
141 return log_error_errno(r
, "Failed to create sd-device object from %s: %m", devlink
);
145 if (device_is_processed(device
) > 0) {
147 *ret
= sd_device_ref(device
);
150 /* We need either the sysname or the devlink for filtering */
151 assert_se(sd_device_get_sysname(device
, &data
.sysname
) >= 0 || devlink
);
154 /* Wait until the device is initialized, so that we can get access to the ID_PATH property */
156 r
= sd_event_new(&event
);
158 return log_error_errno(r
, "Failed to get default event: %m");
160 r
= sd_device_monitor_new(&monitor
);
162 return log_error_errno(r
, "Failed to acquire monitor: %m");
164 if (device
&& !subsystem
) {
165 r
= sd_device_get_subsystem(device
, &subsystem
);
166 if (r
< 0 && r
!= -ENOENT
)
167 return log_device_error_errno(device
, r
, "Failed to get subsystem: %m");
171 r
= sd_device_monitor_filter_add_match_subsystem_devtype(monitor
, subsystem
, NULL
);
173 return log_error_errno(r
, "Failed to add %s subsystem match to monitor: %m", subsystem
);
176 _cleanup_free_
char *desc
= NULL
;
177 const char *sysname
= NULL
;
179 (void) sd_device_get_sysname(device
, &sysname
);
181 desc
= strjoin(sysname
?: subsystem
, devlink
? ":" : ":initialization", devlink
);
183 (void) sd_device_monitor_set_description(monitor
, desc
);
185 r
= sd_device_monitor_attach_event(monitor
, event
);
187 return log_error_errno(r
, "Failed to attach event to device monitor: %m");
189 r
= sd_device_monitor_start(monitor
, device_monitor_handler
, &data
);
191 return log_error_errno(r
, "Failed to start device monitor: %m");
193 if (timeout_usec
!= USEC_INFINITY
) {
194 r
= sd_event_add_time_relative(
196 CLOCK_MONOTONIC
, timeout_usec
, 0,
197 NULL
, INT_TO_PTR(-ETIMEDOUT
));
199 return log_error_errno(r
, "Failed to add timeout event source: %m");
202 /* Check again, maybe things changed. Udev will re-read the db if the device wasn't initialized yet. */
203 if (!device
&& devlink
) {
204 r
= sd_device_new_from_devname(&device
, devlink
);
205 if (r
< 0 && !ERRNO_IS_DEVICE_ABSENT(r
))
206 return log_error_errno(r
, "Failed to create sd-device object from %s: %m", devlink
);
208 if (device
&& device_is_processed(device
) > 0) {
210 *ret
= sd_device_ref(device
);
214 r
= sd_event_loop(event
);
216 return log_error_errno(r
, "Failed to wait for device to be initialized: %m");
219 *ret
= TAKE_PTR(data
.device
);
223 int device_wait_for_initialization(sd_device
*device
, const char *subsystem
, usec_t timeout_usec
, sd_device
**ret
) {
224 return device_wait_for_initialization_internal(device
, NULL
, subsystem
, timeout_usec
, ret
);
227 int device_wait_for_devlink(const char *devlink
, const char *subsystem
, usec_t timeout_usec
, sd_device
**ret
) {
228 return device_wait_for_initialization_internal(NULL
, devlink
, subsystem
, timeout_usec
, ret
);
231 int device_is_renaming(sd_device
*dev
) {
236 r
= device_get_property_bool(dev
, "ID_RENAMING");
238 return false; /* defaults to false */
243 int device_is_processed(sd_device
*dev
) {
248 /* sd_device_get_is_initialized() only checks if the udev database file exists. However, even if the
249 * database file exist, systemd-udevd may be still processing the device, e.g. when the udev rules
250 * for the device have RUN tokens. See issue #30056. Hence, to check if the device is really
251 * processed by systemd-udevd, we also need to read ID_PROCESSING property. */
253 r
= sd_device_get_is_initialized(dev
);
257 r
= device_get_property_bool(dev
, "ID_PROCESSING");
259 return true; /* If the property does not exist, then it means that the device is processed. */
266 bool device_for_action(sd_device
*dev
, sd_device_action_t a
) {
267 sd_device_action_t b
;
274 if (sd_device_get_action(dev
, &b
) < 0)
280 void log_device_uevent(sd_device
*device
, const char *str
) {
281 sd_device_action_t action
= _SD_DEVICE_ACTION_INVALID
;
282 sd_id128_t event_id
= SD_ID128_NULL
;
288 (void) sd_device_get_seqnum(device
, &seqnum
);
289 (void) sd_device_get_action(device
, &action
);
290 (void) sd_device_get_trigger_uuid(device
, &event_id
);
291 log_device_debug(device
, "%s%s(SEQNUM=%"PRIu64
", ACTION=%s%s%s)",
292 strempty(str
), isempty(str
) ? "" : " ",
293 seqnum
, strna(device_action_to_string(action
)),
294 sd_id128_is_null(event_id
) ? "" : ", UUID=",
295 sd_id128_is_null(event_id
) ? "" : SD_ID128_TO_UUID_STRING(event_id
));
298 size_t udev_replace_whitespace(const char *str
, char *to
, size_t len
) {
299 bool is_space
= false;
305 /* Copy from 'str' to 'to', while removing all leading and trailing whitespace, and replacing
306 * each run of consecutive whitespace with a single underscore. The chars from 'str' are copied
307 * up to the \0 at the end of the string, or at most 'len' chars. This appends \0 to 'to', at
308 * the end of the copied characters.
310 * If 'len' chars are copied into 'to', the final \0 is placed at len+1 (i.e. 'to[len] = \0'),
311 * so the 'to' buffer must have at least len+1 chars available.
313 * Note this may be called with 'str' == 'to', i.e. to replace whitespace in-place in a buffer.
314 * This function can handle that situation.
316 * Note that only 'len' characters are read from 'str'. */
318 i
= strspn(str
, WHITESPACE
);
320 for (j
= 0; j
< len
&& i
< len
&& str
[i
] != '\0'; i
++) {
321 if (isspace(str
[i
])) {
340 size_t udev_replace_chars(char *str
, const char *allow
) {
341 size_t i
= 0, replaced
= 0;
345 /* allow chars in allow list, plain ascii, hex-escaping and valid utf8. */
347 while (str
[i
] != '\0') {
350 if (allow_listed_char_for_devnode(str
[i
], allow
)) {
355 /* accept hex encoding */
356 if (str
[i
] == '\\' && str
[i
+1] == 'x') {
361 /* accept valid utf8 */
362 len
= utf8_encoded_valid_unichar(str
+ i
, SIZE_MAX
);
368 /* if space is allowed, replace whitespace with ordinary space */
369 if (isspace(str
[i
]) && allow
&& strchr(allow
, ' ')) {
376 /* everything else is replaced with '_' */
384 int udev_queue_is_empty(void) {
385 return access("/run/udev/queue", F_OK
) < 0 ?
386 (errno
== ENOENT
? true : -errno
) : false;
389 static int cached_udev_availability
= -1;
391 void reset_cached_udev_availability(void) {
392 cached_udev_availability
= -1;
395 bool udev_available(void) {
396 /* The service systemd-udevd is started only when /sys is read write.
397 * See systemd-udevd.service: ConditionPathIsReadWrite=/sys
398 * Also, our container interface (http://systemd.io/CONTAINER_INTERFACE/) states that /sys must
399 * be mounted in read-only mode in containers. */
401 if (cached_udev_availability
>= 0)
402 return cached_udev_availability
;
404 return (cached_udev_availability
= (path_is_read_only_fs("/sys/") <= 0));
407 int device_get_vendor_string(sd_device
*device
, const char **ret
) {
412 FOREACH_STRING(field
, "ID_VENDOR_FROM_DATABASE", "ID_VENDOR") {
413 r
= sd_device_get_property_value(device
, field
, ret
);
421 int device_get_model_string(sd_device
*device
, const char **ret
) {
426 FOREACH_STRING(field
, "ID_MODEL_FROM_DATABASE", "ID_MODEL") {
427 r
= sd_device_get_property_value(device
, field
, ret
);
435 int device_get_property_value_with_fallback(
438 Hashmap
*extra_props
,
447 r
= sd_device_get_property_value(device
, prop
, &value
);
452 value
= hashmap_get(extra_props
, prop
);