1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include <sys/inotify.h>
8 #include "alloc-util.h"
9 #include "device-nodes.h"
10 #include "device-private.h"
11 #include "device-util.h"
13 #include "errno-util.h"
16 #include "id128-util.h"
19 #include "parse-util.h"
20 #include "path-util.h"
21 #include "signal-util.h"
22 #include "socket-util.h"
23 #include "string-table.h"
24 #include "string-util.h"
26 #include "udev-util.h"
29 static const char* const resolve_name_timing_table
[_RESOLVE_NAME_TIMING_MAX
] = {
30 [RESOLVE_NAME_NEVER
] = "never",
31 [RESOLVE_NAME_LATE
] = "late",
32 [RESOLVE_NAME_EARLY
] = "early",
35 DEFINE_STRING_TABLE_LOOKUP(resolve_name_timing
, ResolveNameTiming
);
37 int udev_parse_config_full(
38 unsigned *ret_children_max
,
39 usec_t
*ret_exec_delay_usec
,
40 usec_t
*ret_event_timeout_usec
,
41 ResolveNameTiming
*ret_resolve_name_timing
,
42 int *ret_timeout_signal
) {
44 _cleanup_free_
char *log_val
= NULL
, *children_max
= NULL
, *exec_delay
= NULL
, *event_timeout
= NULL
, *resolve_names
= NULL
, *timeout_signal
= NULL
;
47 r
= parse_env_file(NULL
, "/etc/udev/udev.conf",
49 "children_max", &children_max
,
50 "exec_delay", &exec_delay
,
51 "event_timeout", &event_timeout
,
52 "resolve_names", &resolve_names
,
53 "timeout_signal", &timeout_signal
);
66 ((log_val
[0] == '"' && log_val
[n
-1] == '"') ||
67 (log_val
[0] == '\'' && log_val
[n
-1] == '\''))) {
68 log_val
[n
- 1] = '\0';
73 /* we set the udev log level here explicitly, this is supposed
74 * to regulate the code in libudev/ and udev/. */
75 r
= log_set_max_level_from_string(log
);
77 log_syntax(NULL
, LOG_WARNING
, "/etc/udev/udev.conf", 0, r
,
78 "failed to set udev log level '%s', ignoring: %m", log
);
81 if (ret_children_max
&& children_max
) {
82 r
= safe_atou(children_max
, ret_children_max
);
84 log_syntax(NULL
, LOG_WARNING
, "/etc/udev/udev.conf", 0, r
,
85 "failed to parse children_max=%s, ignoring: %m", children_max
);
88 if (ret_exec_delay_usec
&& exec_delay
) {
89 r
= parse_sec(exec_delay
, ret_exec_delay_usec
);
91 log_syntax(NULL
, LOG_WARNING
, "/etc/udev/udev.conf", 0, r
,
92 "failed to parse exec_delay=%s, ignoring: %m", exec_delay
);
95 if (ret_event_timeout_usec
&& event_timeout
) {
96 r
= parse_sec(event_timeout
, ret_event_timeout_usec
);
98 log_syntax(NULL
, LOG_WARNING
, "/etc/udev/udev.conf", 0, r
,
99 "failed to parse event_timeout=%s, ignoring: %m", event_timeout
);
102 if (ret_resolve_name_timing
&& resolve_names
) {
105 t
= resolve_name_timing_from_string(resolve_names
);
107 log_syntax(NULL
, LOG_WARNING
, "/etc/udev/udev.conf", 0, r
,
108 "failed to parse resolve_names=%s, ignoring.", resolve_names
);
110 *ret_resolve_name_timing
= t
;
113 if (ret_timeout_signal
&& timeout_signal
) {
114 r
= signal_from_string(timeout_signal
);
116 log_syntax(NULL
, LOG_WARNING
, "/etc/udev/udev.conf", 0, r
,
117 "failed to parse timeout_signal=%s, ignoring: %m", timeout_signal
);
119 *ret_timeout_signal
= r
;
125 /* Note that if -ENOENT is returned, it will be logged at debug level rather than error,
126 * because it's an expected, common occurrence that the caller will handle with a fallback */
127 static int device_new_from_dev_path(const char *devlink
, sd_device
**ret_device
) {
133 if (stat(devlink
, &st
) < 0)
134 return log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_ERR
, errno
,
135 "Failed to stat() %s: %m", devlink
);
137 if (!S_ISBLK(st
.st_mode
))
138 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK
),
139 "%s does not point to a block device: %m", devlink
);
141 r
= sd_device_new_from_stat_rdev(ret_device
, &st
);
143 return log_error_errno(r
, "Failed to initialize device from %s: %m", devlink
);
148 struct DeviceMonitorData
{
154 static void device_monitor_data_free(struct DeviceMonitorData
*d
) {
157 sd_device_unref(d
->device
);
160 static int device_monitor_handler(sd_device_monitor
*monitor
, sd_device
*device
, void *userdata
) {
161 struct DeviceMonitorData
*data
= userdata
;
166 assert(data
->sysname
|| data
->devlink
);
167 assert(!data
->device
);
169 /* Ignore REMOVE events here. We are waiting for initialization after all, not de-initialization. We
170 * might see a REMOVE event from an earlier use of the device (devices by the same name are recycled
171 * by the kernel after all), which we should not get confused by. After all we cannot distinguish use
172 * cycles of the devices, as the udev queue is entirely asynchronous.
174 * If we see a REMOVE event here for the use cycle we actually care about then we won't notice of
175 * course, but that should be OK, given the timeout logic used on the wait loop: this will be noticed
176 * by means of -ETIMEDOUT. Thus we won't notice immediately, but eventually, and that should be
177 * sufficient for an error path that should regularly not happen.
179 * (And yes, we only need to special case REMOVE. It's the only "negative" event type, where a device
180 * ceases to exist. All other event types are "positive": the device exists and is registered in the
181 * udev database, thus whenever we see the event, we can consider it initialized.) */
182 if (device_for_action(device
, SD_DEVICE_REMOVE
))
185 if (data
->sysname
&& sd_device_get_sysname(device
, &sysname
) >= 0 && streq(sysname
, data
->sysname
))
191 FOREACH_DEVICE_DEVLINK(device
, devlink
)
192 if (path_equal(devlink
, data
->devlink
))
195 if (sd_device_get_devname(device
, &devlink
) >= 0 && path_equal(devlink
, data
->devlink
))
202 data
->device
= sd_device_ref(device
);
203 return sd_event_exit(sd_device_monitor_get_event(monitor
), 0);
206 static int device_wait_for_initialization_internal(
209 const char *subsystem
,
213 _cleanup_(sd_device_monitor_unrefp
) sd_device_monitor
*monitor
= NULL
;
214 _cleanup_(sd_event_source_unrefp
) sd_event_source
*timeout_source
= NULL
;
215 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
216 /* Ensure that if !_device && devlink, device gets unrefd on errors since it will be new */
217 _cleanup_(sd_device_unrefp
) sd_device
*device
= sd_device_ref(_device
);
218 _cleanup_(device_monitor_data_free
) struct DeviceMonitorData data
= {
223 assert(device
|| (subsystem
&& devlink
));
225 /* Devlink might already exist, if it does get the device to use the sysname filtering */
226 if (!device
&& devlink
) {
227 r
= device_new_from_dev_path(devlink
, &device
);
228 if (r
< 0 && r
!= -ENOENT
)
233 if (sd_device_get_is_initialized(device
) > 0) {
235 *ret
= sd_device_ref(device
);
238 /* We need either the sysname or the devlink for filtering */
239 assert_se(sd_device_get_sysname(device
, &data
.sysname
) >= 0 || devlink
);
242 /* Wait until the device is initialized, so that we can get access to the ID_PATH property */
244 r
= sd_event_new(&event
);
246 return log_error_errno(r
, "Failed to get default event: %m");
248 r
= sd_device_monitor_new(&monitor
);
250 return log_error_errno(r
, "Failed to acquire monitor: %m");
252 if (device
&& !subsystem
) {
253 r
= sd_device_get_subsystem(device
, &subsystem
);
254 if (r
< 0 && r
!= -ENOENT
)
255 return log_device_error_errno(device
, r
, "Failed to get subsystem: %m");
259 r
= sd_device_monitor_filter_add_match_subsystem_devtype(monitor
, subsystem
, NULL
);
261 return log_error_errno(r
, "Failed to add %s subsystem match to monitor: %m", subsystem
);
264 r
= sd_device_monitor_attach_event(monitor
, event
);
266 return log_error_errno(r
, "Failed to attach event to device monitor: %m");
268 r
= sd_device_monitor_start(monitor
, device_monitor_handler
, &data
);
270 return log_error_errno(r
, "Failed to start device monitor: %m");
272 if (deadline
!= USEC_INFINITY
) {
273 r
= sd_event_add_time(
274 event
, &timeout_source
,
275 CLOCK_MONOTONIC
, deadline
, 0,
276 NULL
, INT_TO_PTR(-ETIMEDOUT
));
278 return log_error_errno(r
, "Failed to add timeout event source: %m");
281 /* Check again, maybe things changed. Udev will re-read the db if the device wasn't initialized
283 if (!device
&& devlink
) {
284 r
= device_new_from_dev_path(devlink
, &device
);
285 if (r
< 0 && r
!= -ENOENT
)
288 if (device
&& sd_device_get_is_initialized(device
) > 0) {
290 *ret
= sd_device_ref(device
);
294 r
= sd_event_loop(event
);
296 return log_error_errno(r
, "Failed to wait for device to be initialized: %m");
299 *ret
= TAKE_PTR(data
.device
);
303 int device_wait_for_initialization(sd_device
*device
, const char *subsystem
, usec_t deadline
, sd_device
**ret
) {
304 return device_wait_for_initialization_internal(device
, NULL
, subsystem
, deadline
, ret
);
307 int device_wait_for_devlink(const char *devlink
, const char *subsystem
, usec_t deadline
, sd_device
**ret
) {
308 return device_wait_for_initialization_internal(NULL
, devlink
, subsystem
, deadline
, ret
);
311 int device_is_renaming(sd_device
*dev
) {
316 r
= sd_device_get_property_value(dev
, "ID_RENAMING", NULL
);
325 bool device_for_action(sd_device
*dev
, sd_device_action_t a
) {
326 sd_device_action_t b
;
333 if (sd_device_get_action(dev
, &b
) < 0)
339 void log_device_uevent(sd_device
*device
, const char *str
) {
340 sd_device_action_t action
= _SD_DEVICE_ACTION_INVALID
;
341 sd_id128_t event_id
= SD_ID128_NULL
;
347 (void) sd_device_get_seqnum(device
, &seqnum
);
348 (void) sd_device_get_action(device
, &action
);
349 (void) sd_device_get_trigger_uuid(device
, &event_id
);
350 log_device_debug(device
, "%s%s(SEQNUM=%"PRIu64
", ACTION=%s%s%s)",
351 strempty(str
), isempty(str
) ? "" : " ",
352 seqnum
, strna(device_action_to_string(action
)),
353 sd_id128_is_null(event_id
) ? "" : ", UUID=",
354 sd_id128_is_null(event_id
) ? "" : id128_to_uuid_string(event_id
, (char[ID128_UUID_STRING_MAX
]){}));
357 int udev_rule_parse_value(char *str
, char **ret_value
, char **ret_endpos
) {
361 /* value must be double quotated */
362 is_escaped
= str
[0] == 'e';
369 /* unescape double quotation '\"'->'"' */
370 for (i
= j
= str
; *i
!= '"'; i
++, j
++) {
373 if (i
[0] == '\\' && i
[1] == '"')
379 _cleanup_free_
char *unescaped
= NULL
;
382 /* find the end position of value */
383 for (i
= str
; *i
!= '"'; i
++) {
391 l
= cunescape_length(str
, i
- str
, 0, &unescaped
);
395 assert(l
<= i
- str
);
396 memcpy(str
, unescaped
, l
+ 1);
404 size_t udev_replace_whitespace(const char *str
, char *to
, size_t len
) {
405 bool is_space
= false;
411 /* Copy from 'str' to 'to', while removing all leading and trailing whitespace, and replacing
412 * each run of consecutive whitespace with a single underscore. The chars from 'str' are copied
413 * up to the \0 at the end of the string, or at most 'len' chars. This appends \0 to 'to', at
414 * the end of the copied characters.
416 * If 'len' chars are copied into 'to', the final \0 is placed at len+1 (i.e. 'to[len] = \0'),
417 * so the 'to' buffer must have at least len+1 chars available.
419 * Note this may be called with 'str' == 'to', i.e. to replace whitespace in-place in a buffer.
420 * This function can handle that situation.
422 * Note that only 'len' characters are read from 'str'. */
424 i
= strspn(str
, WHITESPACE
);
426 for (j
= 0; j
< len
&& i
< len
&& str
[i
] != '\0'; i
++) {
427 if (isspace(str
[i
])) {
446 size_t udev_replace_ifname(char *str
) {
451 /* See ifname_valid_full(). */
453 for (char *p
= str
; *p
!= '\0'; p
++)
454 if (!ifname_valid_char(*p
)) {
462 size_t udev_replace_chars(char *str
, const char *allow
) {
463 size_t i
= 0, replaced
= 0;
467 /* allow chars in allow list, plain ascii, hex-escaping and valid utf8. */
469 while (str
[i
] != '\0') {
472 if (allow_listed_char_for_devnode(str
[i
], allow
)) {
477 /* accept hex encoding */
478 if (str
[i
] == '\\' && str
[i
+1] == 'x') {
483 /* accept valid utf8 */
484 len
= utf8_encoded_valid_unichar(str
+ i
, SIZE_MAX
);
490 /* if space is allowed, replace whitespace with ordinary space */
491 if (isspace(str
[i
]) && allow
&& strchr(allow
, ' ')) {
498 /* everything else is replaced with '_' */
506 int udev_resolve_subsys_kernel(const char *string
, char *result
, size_t maxsize
, bool read_value
) {
507 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
508 _cleanup_free_
char *temp
= NULL
;
509 char *subsys
, *sysname
, *attr
;
516 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
518 if (string
[0] != '[')
521 temp
= strdup(string
);
527 sysname
= strchr(subsys
, '/');
531 sysname
= &sysname
[1];
533 attr
= strchr(sysname
, ']');
543 if (read_value
&& !attr
)
546 r
= sd_device_new_from_subsystem_sysname(&dev
, subsys
, sysname
);
551 r
= sd_device_get_sysattr_value(dev
, attr
, &val
);
552 if (r
< 0 && !ERRNO_IS_PRIVILEGE(r
) && r
!= -ENOENT
)
555 strscpy(result
, maxsize
, val
);
558 log_debug("value '[%s/%s]%s' is '%s'", subsys
, sysname
, attr
, result
);
560 r
= sd_device_get_syspath(dev
, &val
);
564 strscpyl(result
, maxsize
, val
, attr
? "/" : NULL
, attr
?: NULL
, NULL
);
565 log_debug("path '[%s/%s]%s' is '%s'", subsys
, sysname
, strempty(attr
), result
);
570 int udev_queue_is_empty(void) {
571 return access("/run/udev/queue", F_OK
) < 0 ?
572 (errno
== ENOENT
? true : -errno
) : false;
575 int udev_queue_init(void) {
576 _cleanup_close_
int fd
= -1;
578 fd
= inotify_init1(IN_CLOEXEC
);
582 if (inotify_add_watch(fd
, "/run/udev" , IN_DELETE
) < 0)
588 static int device_is_power_sink(sd_device
*device
) {
589 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
590 bool found_source
= false, found_sink
= false;
591 sd_device
*parent
, *d
;
596 /* USB-C power supply device has two power roles: source or sink. See,
597 * https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-typec */
599 r
= sd_device_enumerator_new(&e
);
603 r
= sd_device_enumerator_allow_uninitialized(e
);
607 r
= sd_device_enumerator_add_match_subsystem(e
, "typec", true);
611 r
= sd_device_get_parent(device
, &parent
);
615 r
= sd_device_enumerator_add_match_parent(e
, parent
);
619 FOREACH_DEVICE(e
, d
) {
622 r
= sd_device_get_sysattr_value(d
, "power_role", &val
);
625 log_device_debug_errno(d
, r
, "Failed to read 'power_role' sysfs attribute, ignoring: %m");
629 if (strstr(val
, "[source]")) {
631 log_device_debug(d
, "The USB type-C port is in power source mode.");
632 } else if (strstr(val
, "[sink]")) {
634 log_device_debug(d
, "The USB type-C port is in power sink mode.");
639 log_device_debug(device
, "The USB type-C device has at least one port in power sink mode.");
640 else if (!found_source
)
641 log_device_debug(device
, "The USB type-C device has no port in power source mode, assuming the device is in power sink mode.");
643 log_device_debug(device
, "All USB type-C ports are in power source mode.");
645 return found_sink
|| !found_source
;
648 int on_ac_power(void) {
649 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
650 bool found_offline
= false, found_online
= false;
654 r
= sd_device_enumerator_new(&e
);
658 r
= sd_device_enumerator_allow_uninitialized(e
);
662 r
= sd_device_enumerator_add_match_subsystem(e
, "power_supply", true);
666 FOREACH_DEVICE(e
, d
) {
670 r
= sd_device_get_sysattr_value(d
, "type", &val
);
672 log_device_debug_errno(d
, r
, "Failed to read 'type' sysfs attribute, ignoring: %m");
676 /* We assume every power source is AC, except for batteries. See
677 * https://github.com/torvalds/linux/blob/4eef766b7d4d88f0b984781bc1bcb574a6eafdc7/include/linux/power_supply.h#L176
678 * for defined power source types. Also see:
679 * https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-power */
680 if (streq(val
, "Battery")) {
681 log_device_debug(d
, "The power supply is battery, ignoring.");
685 /* Ignore USB-C power supply in source mode. See issue #21988. */
686 if (streq(val
, "USB")) {
687 r
= device_is_power_sink(d
);
690 log_device_debug_errno(d
, r
, "Failed to determine the current power role, ignoring: %m");
692 log_device_debug(d
, "USB power supply is in source mode, ignoring.");
697 r
= sd_device_get_sysattr_value(d
, "online", &val
);
699 log_device_debug_errno(d
, r
, "Failed to read 'online' sysfs attribute, ignoring: %m");
703 r
= safe_atou(val
, &v
);
705 log_device_debug_errno(d
, r
, "Failed to parse 'online' attribute, ignoring: %m");
709 if (v
> 0) /* At least 1 and 2 are defined as different types of 'online' */
712 found_offline
= true;
714 log_device_debug(d
, "The power supply is currently %s.", v
> 0 ? "online" : "offline");
718 log_debug("Found at least one online non-battery power supply, system is running on AC power.");
719 else if (!found_offline
)
720 log_debug("Found no offline non-battery power supply, assuming system is running on AC power.");
722 log_debug("All non-battery power supplies are offline, assuming system is running with battery.");
724 return found_online
|| !found_offline
;