Merge pull request #28577 from yuwata/udev-split-files

udev: split files
This commit is contained in:
Yu Watanabe
2023-08-01 02:12:05 +09:00
committed by GitHub
26 changed files with 3195 additions and 3039 deletions
+8 -5
View File
@@ -192,18 +192,21 @@ _public_ struct udev_list_entry *udev_queue_get_queued_list_entry(struct udev_qu
* Returns: a file descriptor to watch for a queue to become empty.
*/
_public_ int udev_queue_get_fd(struct udev_queue *udev_queue) {
int r;
_cleanup_close_ int fd = -EBADF;
assert_return(udev_queue, -EINVAL);
if (udev_queue->fd >= 0)
return udev_queue->fd;
r = udev_queue_init();
if (r < 0)
return r;
fd = inotify_init1(IN_CLOEXEC);
if (fd < 0)
return -errno;
return udev_queue->fd = r;
if (inotify_add_watch(fd, "/run/udev" , IN_DELETE) < 0)
return -errno;
return udev_queue->fd = TAKE_FD(fd);
}
/**
+26 -248
View File
@@ -2,7 +2,6 @@
#include <ctype.h>
#include <errno.h>
#include <sys/inotify.h>
#include <unistd.h>
#include "alloc-util.h"
@@ -11,7 +10,6 @@
#include "device-util.h"
#include "env-file.h"
#include "errno-util.h"
#include "escape.h"
#include "fd-util.h"
#include "id128-util.h"
#include "log.h"
@@ -19,106 +17,48 @@
#include "parse-util.h"
#include "path-util.h"
#include "signal-util.h"
#include "socket-util.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strxcpyx.h"
#include "udev-util.h"
#include "utf8.h"
static const char* const resolve_name_timing_table[_RESOLVE_NAME_TIMING_MAX] = {
[RESOLVE_NAME_NEVER] = "never",
[RESOLVE_NAME_LATE] = "late",
[RESOLVE_NAME_EARLY] = "early",
};
int udev_set_max_log_level(char *str) {
size_t n;
DEFINE_STRING_TABLE_LOOKUP(resolve_name_timing, ResolveNameTiming);
/* This may modify input string. */
int udev_parse_config_full(
unsigned *ret_children_max,
usec_t *ret_exec_delay_usec,
usec_t *ret_event_timeout_usec,
ResolveNameTiming *ret_resolve_name_timing,
int *ret_timeout_signal) {
if (isempty(str))
return 0;
_cleanup_free_ char *log_val = NULL, *children_max = NULL, *exec_delay = NULL, *event_timeout = NULL, *resolve_names = NULL, *timeout_signal = NULL;
/* unquote */
n = strlen(str);
if (n >= 2 &&
((str[0] == '"' && str[n - 1] == '"') ||
(str[0] == '\'' && str[n - 1] == '\''))) {
str[n - 1] = '\0';
str++;
}
/* we set the udev log level here explicitly, this is supposed
* to regulate the code in libudev/ and udev/. */
return log_set_max_level_from_string(str);
}
int udev_parse_config(void) {
_cleanup_free_ char *log_val = NULL;
int r;
r = parse_env_file(NULL, "/etc/udev/udev.conf",
"udev_log", &log_val,
"children_max", &children_max,
"exec_delay", &exec_delay,
"event_timeout", &event_timeout,
"resolve_names", &resolve_names,
"timeout_signal", &timeout_signal);
"udev_log", &log_val);
if (r == -ENOENT)
return 0;
if (r < 0)
return r;
if (log_val) {
const char *log;
size_t n;
/* unquote */
n = strlen(log_val);
if (n >= 2 &&
((log_val[0] == '"' && log_val[n-1] == '"') ||
(log_val[0] == '\'' && log_val[n-1] == '\''))) {
log_val[n - 1] = '\0';
log = log_val + 1;
} else
log = log_val;
/* we set the udev log level here explicitly, this is supposed
* to regulate the code in libudev/ and udev/. */
r = log_set_max_level_from_string(log);
if (r < 0)
log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
"failed to set udev log level '%s', ignoring: %m", log);
}
if (ret_children_max && children_max) {
r = safe_atou(children_max, ret_children_max);
if (r < 0)
log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
"failed to parse children_max=%s, ignoring: %m", children_max);
}
if (ret_exec_delay_usec && exec_delay) {
r = parse_sec(exec_delay, ret_exec_delay_usec);
if (r < 0)
log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
"failed to parse exec_delay=%s, ignoring: %m", exec_delay);
}
if (ret_event_timeout_usec && event_timeout) {
r = parse_sec(event_timeout, ret_event_timeout_usec);
if (r < 0)
log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
"failed to parse event_timeout=%s, ignoring: %m", event_timeout);
}
if (ret_resolve_name_timing && resolve_names) {
ResolveNameTiming t;
t = resolve_name_timing_from_string(resolve_names);
if (t < 0)
log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
"failed to parse resolve_names=%s, ignoring.", resolve_names);
else
*ret_resolve_name_timing = t;
}
if (ret_timeout_signal && timeout_signal) {
r = signal_from_string(timeout_signal);
if (r < 0)
log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
"failed to parse timeout_signal=%s, ignoring: %m", timeout_signal);
else
*ret_timeout_signal = r;
}
r = udev_set_max_log_level(log_val);
if (r < 0)
log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
"Failed to set udev log level '%s', ignoring: %m", log_val);
return 0;
}
@@ -338,62 +278,6 @@ void log_device_uevent(sd_device *device, const char *str) {
sd_id128_is_null(event_id) ? "" : SD_ID128_TO_UUID_STRING(event_id));
}
int udev_rule_parse_value(char *str, char **ret_value, char **ret_endpos) {
char *i, *j;
bool is_escaped;
/* value must be double quotated */
is_escaped = str[0] == 'e';
str += is_escaped;
if (str[0] != '"')
return -EINVAL;
if (!is_escaped) {
/* unescape double quotation '\"'->'"' */
for (j = str, i = str + 1; *i != '"'; i++, j++) {
if (*i == '\0')
return -EINVAL;
if (i[0] == '\\' && i[1] == '"')
i++;
*j = *i;
}
j[0] = '\0';
/*
* The return value must be terminated by two subsequent NULs
* so it could be safely interpreted as nulstr.
*/
j[1] = '\0';
} else {
_cleanup_free_ char *unescaped = NULL;
ssize_t l;
/* find the end position of value */
for (i = str + 1; *i != '"'; i++) {
if (i[0] == '\\')
i++;
if (*i == '\0')
return -EINVAL;
}
i[0] = '\0';
l = cunescape_length(str + 1, i - (str + 1), 0, &unescaped);
if (l < 0)
return l;
assert(l <= i - (str + 1));
memcpy(str, unescaped, l + 1);
/*
* The return value must be terminated by two subsequent NULs
* so it could be safely interpreted as nulstr.
*/
str[l + 1] = '\0';
}
*ret_value = str;
*ret_endpos = i + 1;
return 0;
}
size_t udev_replace_whitespace(const char *str, char *to, size_t len) {
bool is_space = false;
size_t i, j;
@@ -436,22 +320,6 @@ size_t udev_replace_whitespace(const char *str, char *to, size_t len) {
return j;
}
size_t udev_replace_ifname(char *str) {
size_t replaced = 0;
assert(str);
/* See ifname_valid_full(). */
for (char *p = str; *p != '\0'; p++)
if (!ifname_valid_char(*p)) {
*p = '_';
replaced++;
}
return replaced;
}
size_t udev_replace_chars(char *str, const char *allow) {
size_t i = 0, replaced = 0;
@@ -496,101 +364,11 @@ size_t udev_replace_chars(char *str, const char *allow) {
return replaced;
}
int udev_resolve_subsys_kernel(const char *string, char *result, size_t maxsize, bool read_value) {
_cleanup_(sd_device_unrefp) sd_device *dev = NULL;
_cleanup_free_ char *temp = NULL;
char *subsys, *sysname, *attr;
const char *val;
int r;
assert(string);
assert(result);
/* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
if (string[0] != '[')
return -EINVAL;
temp = strdup(string);
if (!temp)
return -ENOMEM;
subsys = &temp[1];
sysname = strchr(subsys, '/');
if (!sysname)
return -EINVAL;
sysname[0] = '\0';
sysname = &sysname[1];
attr = strchr(sysname, ']');
if (!attr)
return -EINVAL;
attr[0] = '\0';
attr = &attr[1];
if (attr[0] == '/')
attr = &attr[1];
if (attr[0] == '\0')
attr = NULL;
if (read_value && !attr)
return -EINVAL;
r = sd_device_new_from_subsystem_sysname(&dev, subsys, sysname);
if (r < 0)
return r;
if (read_value) {
r = sd_device_get_sysattr_value(dev, attr, &val);
if (r < 0 && !ERRNO_IS_PRIVILEGE(r) && r != -ENOENT)
return r;
if (r >= 0)
strscpy(result, maxsize, val);
else
result[0] = '\0';
log_debug("value '[%s/%s]%s' is '%s'", subsys, sysname, attr, result);
} else {
r = sd_device_get_syspath(dev, &val);
if (r < 0)
return r;
strscpyl(result, maxsize, val, attr ? "/" : NULL, attr ?: NULL, NULL);
log_debug("path '[%s/%s]%s' is '%s'", subsys, sysname, strempty(attr), result);
}
return 0;
}
bool devpath_conflict(const char *a, const char *b) {
/* This returns true when two paths are equivalent, or one is a child of another. */
if (!a || !b)
return false;
for (; *a != '\0' && *b != '\0'; a++, b++)
if (*a != *b)
return false;
return *a == '/' || *b == '/' || *a == *b;
}
int udev_queue_is_empty(void) {
return access("/run/udev/queue", F_OK) < 0 ?
(errno == ENOENT ? true : -errno) : false;
}
int udev_queue_init(void) {
_cleanup_close_ int fd = -EBADF;
fd = inotify_init1(IN_CLOEXEC);
if (fd < 0)
return -errno;
if (inotify_add_watch(fd, "/run/udev" , IN_DELETE) < 0)
return -errno;
return TAKE_FD(fd);
}
bool udev_available(void) {
static int cache = -1;
+2 -63
View File
@@ -1,40 +1,12 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if HAVE_SYS_SDT_H
#define SDT_USE_VARIADIC
#include <sys/sdt.h>
#endif
#include "sd-device.h"
#include "time-util.h"
#define UDEV_NAME_SIZE 512
#define UDEV_PATH_SIZE 1024
#define UDEV_LINE_SIZE 16384
typedef enum ResolveNameTiming {
RESOLVE_NAME_NEVER,
RESOLVE_NAME_LATE,
RESOLVE_NAME_EARLY,
_RESOLVE_NAME_TIMING_MAX,
_RESOLVE_NAME_TIMING_INVALID = -EINVAL,
} ResolveNameTiming;
ResolveNameTiming resolve_name_timing_from_string(const char *s) _pure_;
const char *resolve_name_timing_to_string(ResolveNameTiming i) _const_;
int udev_parse_config_full(
unsigned *ret_children_max,
usec_t *ret_exec_delay_usec,
usec_t *ret_event_timeout_usec,
ResolveNameTiming *ret_resolve_name_timing,
int *ret_timeout_signal);
static inline int udev_parse_config(void) {
return udev_parse_config_full(NULL, NULL, NULL, NULL, NULL);
}
int udev_set_max_log_level(char *str);
int udev_parse_config(void);
int device_wait_for_initialization(sd_device *device, const char *subsystem, usec_t timeout_usec, sd_device **ret);
int device_wait_for_devlink(const char *path, const char *subsystem, usec_t timeout_usec, sd_device **ret);
@@ -44,42 +16,9 @@ bool device_for_action(sd_device *dev, sd_device_action_t action);
void log_device_uevent(sd_device *device, const char *str);
int udev_rule_parse_value(char *str, char **ret_value, char **ret_endpos);
size_t udev_replace_whitespace(const char *str, char *to, size_t len);
size_t udev_replace_ifname(char *str);
size_t udev_replace_chars(char *str, const char *allow);
int udev_resolve_subsys_kernel(const char *string, char *result, size_t maxsize, bool read_value);
bool devpath_conflict(const char *a, const char *b);
int udev_queue_is_empty(void);
int udev_queue_init(void);
bool udev_available(void);
#if HAVE_SYS_SDT_H
/* Each trace point can have different number of additional arguments. Note that when the macro is used only
* additional arguments are listed in the macro invocation!
*
* Default arguments for each trace point are as follows:
* - arg0 - action
* - arg1 - sysname
* - arg2 - syspath
* - arg3 - subsystem
*/
#define DEVICE_TRACE_POINT(name, dev, ...) \
do { \
PROTECT_ERRNO; \
const char *_n = NULL, *_p = NULL, *_s = NULL; \
sd_device *_d = (dev); \
sd_device_action_t _a = _SD_DEVICE_ACTION_INVALID; \
(void) sd_device_get_action(_d, &_a); \
(void) sd_device_get_sysname(_d, &_n); \
(void) sd_device_get_syspath(_d, &_p); \
(void) sd_device_get_subsystem(_d, &_s); \
STAP_PROBEV(udev, name, device_action_to_string(_a), _n, _p, _s __VA_OPT__(,) __VA_ARGS__);\
} while (false);
#else
#define DEVICE_TRACE_POINT(name, dev, ...) ((void) 0)
#endif
-113
View File
@@ -8,76 +8,6 @@
#include "tests.h"
#include "udev-util.h"
static void test_udev_rule_parse_value_one(const char *in, const char *expected_value, int expected_retval) {
_cleanup_free_ char *str = NULL;
char *value = UINT_TO_PTR(0x12345678U);
char *endpos = UINT_TO_PTR(0x87654321U);
log_info("/* %s (%s, %s, %d) */", __func__, in, strnull(expected_value), expected_retval);
assert_se(str = strdup(in));
assert_se(udev_rule_parse_value(str, &value, &endpos) == expected_retval);
if (expected_retval < 0) {
/* not modified on failure */
assert_se(value == UINT_TO_PTR(0x12345678U));
assert_se(endpos == UINT_TO_PTR(0x87654321U));
} else {
assert_se(streq_ptr(value, expected_value));
assert_se(endpos == str + strlen(in));
/*
* The return value must be terminated by two subsequent NULs
* so it could be safely interpreted as nulstr.
*/
assert_se(value[strlen(value) + 1] == '\0');
}
}
TEST(udev_rule_parse_value) {
/* input: "valid operand"
* parsed: valid operand
* use the following command to help generate textual C strings:
* python3 -c 'import json; print(json.dumps(input()))' */
test_udev_rule_parse_value_one("\"valid operand\"", "valid operand", 0);
/* input: "va'l\'id\"op\"erand"
* parsed: va'l\'id"op"erand */
test_udev_rule_parse_value_one("\"va'l\\'id\\\"op\\\"erand\"", "va'l\\'id\"op\"erand", 0);
test_udev_rule_parse_value_one("no quotes", NULL, -EINVAL);
test_udev_rule_parse_value_one("\"\\\\a\\b\\x\\y\"", "\\\\a\\b\\x\\y", 0);
test_udev_rule_parse_value_one("\"reject\0nul\"", NULL, -EINVAL);
/* input: e"" */
test_udev_rule_parse_value_one("e\"\"", "", 0);
/* input: e"1234" */
test_udev_rule_parse_value_one("e\"1234\"", "1234", 0);
/* input: e"\"" */
test_udev_rule_parse_value_one("e\"\\\"\"", "\"", 0);
/* input: e"\ */
test_udev_rule_parse_value_one("e\"\\", NULL, -EINVAL);
/* input: e"\" */
test_udev_rule_parse_value_one("e\"\\\"", NULL, -EINVAL);
/* input: e"\\" */
test_udev_rule_parse_value_one("e\"\\\\\"", "\\", 0);
/* input: e"\\\" */
test_udev_rule_parse_value_one("e\"\\\\\\\"", NULL, -EINVAL);
/* input: e"\\\"" */
test_udev_rule_parse_value_one("e\"\\\\\\\"\"", "\\\"", 0);
/* input: e"\\\\" */
test_udev_rule_parse_value_one("e\"\\\\\\\\\"", "\\\\", 0);
/* input: e"operand with newline\n" */
test_udev_rule_parse_value_one("e\"operand with newline\\n\"", "operand with newline\n", 0);
/* input: e"single\rcharacter\t\aescape\bsequence" */
test_udev_rule_parse_value_one(
"e\"single\\rcharacter\\t\\aescape\\bsequence\"", "single\rcharacter\t\aescape\bsequence", 0);
/* input: e"reject\invalid escape sequence" */
test_udev_rule_parse_value_one("e\"reject\\invalid escape sequence", NULL, -EINVAL);
/* input: e"\ */
test_udev_rule_parse_value_one("e\"\\", NULL, -EINVAL);
/* input: "s\u1d1c\u1d04\u029c \u1d1c\u0274\u026a\u1d04\u1d0f\u1d05\u1d07 \U0001d568\U0001d560\U0001d568" */
test_udev_rule_parse_value_one(
"e\"s\\u1d1c\\u1d04\\u029c \\u1d1c\\u0274\\u026a\\u1d04\\u1d0f\\u1d05\\u1d07 \\U0001d568\\U0001d560\\U0001d568\"",
"s\xe1\xb4\x9c\xe1\xb4\x84\xca\x9c \xe1\xb4\x9c\xc9\xb4\xc9\xaa\xe1\xb4\x84\xe1\xb4\x8f\xe1\xb4\x85\xe1\xb4\x87 \xf0\x9d\x95\xa8\xf0\x9d\x95\xa0\xf0\x9d\x95\xa8",
0);
}
static void test_udev_replace_whitespace_one_len(const char *str, size_t len, const char *expected) {
_cleanup_free_ char *result = NULL;
int r;
@@ -130,47 +60,4 @@ TEST(udev_replace_whitespace) {
test_udev_replace_whitespace_one_len(" hoge hoge ", 0, "");
}
static void test_udev_resolve_subsys_kernel_one(const char *str, bool read_value, int retval, const char *expected) {
char result[PATH_MAX] = "";
int r;
r = udev_resolve_subsys_kernel(str, result, sizeof(result), read_value);
log_info("\"%s\" → expect: \"%s\", %d, actual: \"%s\", %d", str, strnull(expected), retval, result, r);
assert_se(r == retval);
if (r >= 0)
assert_se(streq(result, expected));
}
TEST(udev_resolve_subsys_kernel) {
test_udev_resolve_subsys_kernel_one("hoge", false, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[hoge", false, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[hoge/foo", false, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[hoge/]", false, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[net/lo]", false, 0, "/sys/devices/virtual/net/lo");
test_udev_resolve_subsys_kernel_one("[net/lo]/", false, 0, "/sys/devices/virtual/net/lo");
test_udev_resolve_subsys_kernel_one("[net/lo]hoge", false, 0, "/sys/devices/virtual/net/lo/hoge");
test_udev_resolve_subsys_kernel_one("[net/lo]/hoge", false, 0, "/sys/devices/virtual/net/lo/hoge");
test_udev_resolve_subsys_kernel_one("[net/lo]", true, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[net/lo]/", true, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[net/lo]hoge", true, 0, "");
test_udev_resolve_subsys_kernel_one("[net/lo]/hoge", true, 0, "");
test_udev_resolve_subsys_kernel_one("[net/lo]address", true, 0, "00:00:00:00:00:00");
test_udev_resolve_subsys_kernel_one("[net/lo]/address", true, 0, "00:00:00:00:00:00");
}
TEST(devpath_conflict) {
assert_se(!devpath_conflict(NULL, NULL));
assert_se(!devpath_conflict(NULL, "/devices/pci0000:00/0000:00:1c.4"));
assert_se(!devpath_conflict("/devices/pci0000:00/0000:00:1c.4", NULL));
assert_se(!devpath_conflict("/devices/pci0000:00/0000:00:1c.4", "/devices/pci0000:00/0000:00:00.0"));
assert_se(!devpath_conflict("/devices/virtual/net/veth99", "/devices/virtual/net/veth999"));
assert_se(devpath_conflict("/devices/pci0000:00/0000:00:1c.4", "/devices/pci0000:00/0000:00:1c.4"));
assert_se(devpath_conflict("/devices/pci0000:00/0000:00:1c.4", "/devices/pci0000:00/0000:00:1c.4/0000:3c:00.0"));
assert_se(devpath_conflict("/devices/pci0000:00/0000:00:1c.4/0000:3c:00.0/nvme/nvme0/nvme0n1",
"/devices/pci0000:00/0000:00:1c.4/0000:3c:00.0/nvme/nvme0/nvme0n1/nvme0n1p1"));
}
DEFINE_TEST_MAIN(LOG_INFO);
+1
View File
@@ -24,6 +24,7 @@
#include "string-util.h"
#include "tests.h"
#include "udev-event.h"
#include "udev-spawn.h"
#include "version.h"
static int device_new_from_synthetic_event(sd_device **ret, const char *syspath, const char *action) {
+1 -2
View File
@@ -4,7 +4,7 @@
#include "alloc-util.h"
#include "fuzz.h"
#include "udev-util.h"
#include "udev-rules.h"
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
_cleanup_free_ char *str = NULL;
@@ -17,7 +17,6 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
str[size] = '\0';
r = udev_rule_parse_value(str, &value, &endpos);
if (r < 0) {
/* not modified on failure */
assert_se(value == UINT_TO_PTR(0x12345678U));
+25 -9
View File
@@ -1,29 +1,33 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
udevadm_sources = files(
'udevadm.c',
'udevadm-control.c',
'udevadm-hwdb.c',
'udevadm-info.c',
'udevadm-lock.c',
'udevadm-monitor.c',
'udevadm-settle.c',
'udevadm-test.c',
'udevadm-test-builtin.c',
'udevadm-test.c',
'udevadm-trigger.c',
'udevadm-util.c',
'udevadm-verify.c',
'udevadm-wait.c',
'udevadm.c',
'udevd.c',
)
libudevd_core_sources = files(
'net/link-config.c',
'udev-ctrl.c',
'udev-event.c',
'udev-format.c',
'udev-manager.c',
'udev-node.c',
'udev-rules.c',
'udev-spawn.c',
'udev-watch.c',
'udev-builtin.c',
'udev-worker.c',
'udev-builtin-btrfs.c',
'udev-builtin-hwdb.c',
'udev-builtin-input_id.c',
@@ -32,7 +36,7 @@ libudevd_core_sources = files(
'udev-builtin-net_setup_link.c',
'udev-builtin-path_id.c',
'udev-builtin-usb_id.c',
'net/link-config.c',
'udev-builtin.c',
)
if conf.get('HAVE_KMOD') == 1
@@ -167,10 +171,6 @@ if install_sysconfdir
mkdir_p.format(sysconfdir / 'udev/rules.d'))
endif
simple_fuzzers += files(
'fuzz-udev-rule-parse-value.c',
)
fuzzer_udev_base = {
'link_with' : [libudevd_core, libshared],
'dependencies' : [threads, libacl],
@@ -182,6 +182,10 @@ fuzzers += [
'includes' : udev_includes,
'base' : fuzzer_udev_base,
},
{
'sources' : files('fuzz-udev-rule-parse-value.c'),
'base' : fuzzer_udev_base,
},
{
'sources' : files('fuzz-udev-rules.c'),
'base' : fuzzer_udev_base,
@@ -211,11 +215,23 @@ tests += [
'base' : test_libudev_base,
},
{
'sources' : files('test-udev-event.c'),
'sources' : files('test-udev-format.c'),
'base' : test_libudev_base,
},
{
'sources' : files('test-udev-manager.c'),
'base' : test_libudev_base,
},
{
'sources' : files('test-udev-node.c'),
'base' : test_libudev_base,
},
{
'sources' : files('test-udev-rules.c'),
'base' : test_libudev_base,
},
{
'sources' : files('test-udev-spawn.c'),
'base' : test_libudev_base,
},
]
+37
View File
@@ -0,0 +1,37 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "string-util.h"
#include "tests.h"
#include "udev-format.h"
static void test_udev_resolve_subsys_kernel_one(const char *str, bool read_value, int retval, const char *expected) {
char result[PATH_MAX] = "";
int r;
r = udev_resolve_subsys_kernel(str, result, sizeof(result), read_value);
log_info("\"%s\" → expect: \"%s\", %d, actual: \"%s\", %d", str, strnull(expected), retval, result, r);
assert_se(r == retval);
if (r >= 0)
assert_se(streq(result, expected));
}
TEST(udev_resolve_subsys_kernel) {
test_udev_resolve_subsys_kernel_one("hoge", false, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[hoge", false, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[hoge/foo", false, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[hoge/]", false, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[net/lo]", false, 0, "/sys/devices/virtual/net/lo");
test_udev_resolve_subsys_kernel_one("[net/lo]/", false, 0, "/sys/devices/virtual/net/lo");
test_udev_resolve_subsys_kernel_one("[net/lo]hoge", false, 0, "/sys/devices/virtual/net/lo/hoge");
test_udev_resolve_subsys_kernel_one("[net/lo]/hoge", false, 0, "/sys/devices/virtual/net/lo/hoge");
test_udev_resolve_subsys_kernel_one("[net/lo]", true, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[net/lo]/", true, -EINVAL, NULL);
test_udev_resolve_subsys_kernel_one("[net/lo]hoge", true, 0, "");
test_udev_resolve_subsys_kernel_one("[net/lo]/hoge", true, 0, "");
test_udev_resolve_subsys_kernel_one("[net/lo]address", true, 0, "00:00:00:00:00:00");
test_udev_resolve_subsys_kernel_one("[net/lo]/address", true, 0, "00:00:00:00:00:00");
}
DEFINE_TEST_MAIN(LOG_DEBUG);
+19
View File
@@ -0,0 +1,19 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "tests.h"
#include "udev-manager.h"
TEST(devpath_conflict) {
assert_se(!devpath_conflict(NULL, NULL));
assert_se(!devpath_conflict(NULL, "/devices/pci0000:00/0000:00:1c.4"));
assert_se(!devpath_conflict("/devices/pci0000:00/0000:00:1c.4", NULL));
assert_se(!devpath_conflict("/devices/pci0000:00/0000:00:1c.4", "/devices/pci0000:00/0000:00:00.0"));
assert_se(!devpath_conflict("/devices/virtual/net/veth99", "/devices/virtual/net/veth999"));
assert_se(devpath_conflict("/devices/pci0000:00/0000:00:1c.4", "/devices/pci0000:00/0000:00:1c.4"));
assert_se(devpath_conflict("/devices/pci0000:00/0000:00:1c.4", "/devices/pci0000:00/0000:00:1c.4/0000:3c:00.0"));
assert_se(devpath_conflict("/devices/pci0000:00/0000:00:1c.4/0000:3c:00.0/nvme/nvme0/nvme0n1",
"/devices/pci0000:00/0000:00:1c.4/0000:3c:00.0/nvme/nvme0/nvme0n1/nvme0n1p1"));
}
DEFINE_TEST_MAIN(LOG_DEBUG);
+77
View File
@@ -0,0 +1,77 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "string-util.h"
#include "tests.h"
#include "udev-rules.h"
static void test_udev_rule_parse_value_one(const char *in, const char *expected_value, int expected_retval) {
_cleanup_free_ char *str = NULL;
char *value = UINT_TO_PTR(0x12345678U);
char *endpos = UINT_TO_PTR(0x87654321U);
log_info("/* %s (%s, %s, %d) */", __func__, in, strnull(expected_value), expected_retval);
assert_se(str = strdup(in));
assert_se(udev_rule_parse_value(str, &value, &endpos) == expected_retval);
if (expected_retval < 0) {
/* not modified on failure */
assert_se(value == UINT_TO_PTR(0x12345678U));
assert_se(endpos == UINT_TO_PTR(0x87654321U));
} else {
assert_se(streq_ptr(value, expected_value));
assert_se(endpos == str + strlen(in));
/*
* The return value must be terminated by two subsequent NULs
* so it could be safely interpreted as nulstr.
*/
assert_se(value[strlen(value) + 1] == '\0');
}
}
TEST(udev_rule_parse_value) {
/* input: "valid operand"
* parsed: valid operand
* use the following command to help generate textual C strings:
* python3 -c 'import json; print(json.dumps(input()))' */
test_udev_rule_parse_value_one("\"valid operand\"", "valid operand", 0);
/* input: "va'l\'id\"op\"erand"
* parsed: va'l\'id"op"erand */
test_udev_rule_parse_value_one("\"va'l\\'id\\\"op\\\"erand\"", "va'l\\'id\"op\"erand", 0);
test_udev_rule_parse_value_one("no quotes", NULL, -EINVAL);
test_udev_rule_parse_value_one("\"\\\\a\\b\\x\\y\"", "\\\\a\\b\\x\\y", 0);
test_udev_rule_parse_value_one("\"reject\0nul\"", NULL, -EINVAL);
/* input: e"" */
test_udev_rule_parse_value_one("e\"\"", "", 0);
/* input: e"1234" */
test_udev_rule_parse_value_one("e\"1234\"", "1234", 0);
/* input: e"\"" */
test_udev_rule_parse_value_one("e\"\\\"\"", "\"", 0);
/* input: e"\ */
test_udev_rule_parse_value_one("e\"\\", NULL, -EINVAL);
/* input: e"\" */
test_udev_rule_parse_value_one("e\"\\\"", NULL, -EINVAL);
/* input: e"\\" */
test_udev_rule_parse_value_one("e\"\\\\\"", "\\", 0);
/* input: e"\\\" */
test_udev_rule_parse_value_one("e\"\\\\\\\"", NULL, -EINVAL);
/* input: e"\\\"" */
test_udev_rule_parse_value_one("e\"\\\\\\\"\"", "\\\"", 0);
/* input: e"\\\\" */
test_udev_rule_parse_value_one("e\"\\\\\\\\\"", "\\\\", 0);
/* input: e"operand with newline\n" */
test_udev_rule_parse_value_one("e\"operand with newline\\n\"", "operand with newline\n", 0);
/* input: e"single\rcharacter\t\aescape\bsequence" */
test_udev_rule_parse_value_one(
"e\"single\\rcharacter\\t\\aescape\\bsequence\"", "single\rcharacter\t\aescape\bsequence", 0);
/* input: e"reject\invalid escape sequence" */
test_udev_rule_parse_value_one("e\"reject\\invalid escape sequence", NULL, -EINVAL);
/* input: e"\ */
test_udev_rule_parse_value_one("e\"\\", NULL, -EINVAL);
/* input: "s\u1d1c\u1d04\u029c \u1d1c\u0274\u026a\u1d04\u1d0f\u1d05\u1d07 \U0001d568\U0001d560\U0001d568" */
test_udev_rule_parse_value_one(
"e\"s\\u1d1c\\u1d04\\u029c \\u1d1c\\u0274\\u026a\\u1d04\\u1d0f\\u1d05\\u1d07 \\U0001d568\\U0001d560\\U0001d568\"",
"s\xe1\xb4\x9c\xe1\xb4\x84\xca\x9c \xe1\xb4\x9c\xc9\xb4\xc9\xaa\xe1\xb4\x84\xe1\xb4\x8f\xe1\xb4\x85\xe1\xb4\x87 \xf0\x9d\x95\xa8\xf0\x9d\x95\xa0\xf0\x9d\x95\xa8",
0);
}
DEFINE_TEST_MAIN(LOG_DEBUG);
@@ -5,6 +5,7 @@
#include "strv.h"
#include "tests.h"
#include "udev-event.h"
#include "udev-spawn.h"
#define BUF_SIZE 1024
+1 -832
View File
@@ -1,57 +1,22 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <stddef.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include "sd-event.h"
#include "alloc-util.h"
#include "device-internal.h"
#include "device-private.h"
#include "device-util.h"
#include "fd-util.h"
#include "fs-util.h"
#include "format-util.h"
#include "netif-naming-scheme.h"
#include "netlink-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "process-util.h"
#include "signal-util.h"
#include "stdio-util.h"
#include "string-util.h"
#include "strv.h"
#include "strxcpyx.h"
#include "udev-builtin.h"
#include "udev-event.h"
#include "udev-node.h"
#include "udev-trace.h"
#include "udev-util.h"
#include "udev-watch.h"
#include "user-util.h"
typedef struct Spawn {
sd_device *device;
const char *cmd;
pid_t pid;
usec_t timeout_warn_usec;
usec_t timeout_usec;
int timeout_signal;
usec_t event_birth_usec;
bool accept_failure;
int fd_stdout;
int fd_stderr;
char *result;
size_t result_size;
size_t result_len;
bool truncated;
} Spawn;
UdevEvent *udev_event_new(sd_device *dev, usec_t exec_delay_usec, sd_netlink *rtnl, int log_level) {
UdevEvent *event;
@@ -92,771 +57,6 @@ UdevEvent *udev_event_free(UdevEvent *event) {
return mfree(event);
}
typedef enum {
FORMAT_SUBST_DEVNODE,
FORMAT_SUBST_ATTR,
FORMAT_SUBST_ENV,
FORMAT_SUBST_KERNEL,
FORMAT_SUBST_KERNEL_NUMBER,
FORMAT_SUBST_DRIVER,
FORMAT_SUBST_DEVPATH,
FORMAT_SUBST_ID,
FORMAT_SUBST_MAJOR,
FORMAT_SUBST_MINOR,
FORMAT_SUBST_RESULT,
FORMAT_SUBST_PARENT,
FORMAT_SUBST_NAME,
FORMAT_SUBST_LINKS,
FORMAT_SUBST_ROOT,
FORMAT_SUBST_SYS,
_FORMAT_SUBST_TYPE_MAX,
_FORMAT_SUBST_TYPE_INVALID = -EINVAL,
} FormatSubstitutionType;
struct subst_map_entry {
const char *name;
const char fmt;
FormatSubstitutionType type;
};
static const struct subst_map_entry map[] = {
{ .name = "devnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE },
{ .name = "tempnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE }, /* deprecated */
{ .name = "attr", .fmt = 's', .type = FORMAT_SUBST_ATTR },
{ .name = "sysfs", .fmt = 's', .type = FORMAT_SUBST_ATTR }, /* deprecated */
{ .name = "env", .fmt = 'E', .type = FORMAT_SUBST_ENV },
{ .name = "kernel", .fmt = 'k', .type = FORMAT_SUBST_KERNEL },
{ .name = "number", .fmt = 'n', .type = FORMAT_SUBST_KERNEL_NUMBER },
{ .name = "driver", .fmt = 'd', .type = FORMAT_SUBST_DRIVER },
{ .name = "devpath", .fmt = 'p', .type = FORMAT_SUBST_DEVPATH },
{ .name = "id", .fmt = 'b', .type = FORMAT_SUBST_ID },
{ .name = "major", .fmt = 'M', .type = FORMAT_SUBST_MAJOR },
{ .name = "minor", .fmt = 'm', .type = FORMAT_SUBST_MINOR },
{ .name = "result", .fmt = 'c', .type = FORMAT_SUBST_RESULT },
{ .name = "parent", .fmt = 'P', .type = FORMAT_SUBST_PARENT },
{ .name = "name", .fmt = 'D', .type = FORMAT_SUBST_NAME },
{ .name = "links", .fmt = 'L', .type = FORMAT_SUBST_LINKS },
{ .name = "root", .fmt = 'r', .type = FORMAT_SUBST_ROOT },
{ .name = "sys", .fmt = 'S', .type = FORMAT_SUBST_SYS },
};
static const char *format_type_to_string(FormatSubstitutionType t) {
for (size_t i = 0; i < ELEMENTSOF(map); i++)
if (map[i].type == t)
return map[i].name;
return NULL;
}
static char format_type_to_char(FormatSubstitutionType t) {
for (size_t i = 0; i < ELEMENTSOF(map); i++)
if (map[i].type == t)
return map[i].fmt;
return '\0';
}
static int get_subst_type(const char **str, bool strict, FormatSubstitutionType *ret_type, char ret_attr[static UDEV_PATH_SIZE]) {
const char *p = *str, *q = NULL;
size_t i;
assert(str);
assert(*str);
assert(ret_type);
assert(ret_attr);
if (*p == '$') {
p++;
if (*p == '$') {
*str = p;
return 0;
}
for (i = 0; i < ELEMENTSOF(map); i++)
if ((q = startswith(p, map[i].name)))
break;
} else if (*p == '%') {
p++;
if (*p == '%') {
*str = p;
return 0;
}
for (i = 0; i < ELEMENTSOF(map); i++)
if (*p == map[i].fmt) {
q = p + 1;
break;
}
} else
return 0;
if (!q)
/* When 'strict' flag is set, then '$' and '%' must be escaped. */
return strict ? -EINVAL : 0;
if (*q == '{') {
const char *start, *end;
size_t len;
start = q + 1;
end = strchr(start, '}');
if (!end)
return -EINVAL;
len = end - start;
if (len == 0 || len >= UDEV_PATH_SIZE)
return -EINVAL;
strnscpy(ret_attr, UDEV_PATH_SIZE, start, len);
q = end + 1;
} else
*ret_attr = '\0';
*str = q;
*ret_type = map[i].type;
return 1;
}
static int safe_atou_optional_plus(const char *s, unsigned *ret) {
const char *p;
int r;
assert(s);
assert(ret);
/* Returns 1 if plus, 0 if no plus, negative on error */
p = endswith(s, "+");
if (p)
s = strndupa_safe(s, p - s);
r = safe_atou(s, ret);
if (r < 0)
return r;
return !!p;
}
static ssize_t udev_event_subst_format(
UdevEvent *event,
FormatSubstitutionType type,
const char *attr,
char *dest,
size_t l,
bool *ret_truncated) {
sd_device *parent, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
const char *val = NULL;
bool truncated = false;
char *s = dest;
int r;
switch (type) {
case FORMAT_SUBST_DEVPATH:
r = sd_device_get_devpath(dev, &val);
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_KERNEL:
r = sd_device_get_sysname(dev, &val);
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_KERNEL_NUMBER:
r = sd_device_get_sysnum(dev, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_ID:
if (!event->dev_parent)
goto null_terminate;
r = sd_device_get_sysname(event->dev_parent, &val);
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_DRIVER:
if (!event->dev_parent)
goto null_terminate;
r = sd_device_get_driver(event->dev_parent, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_MAJOR:
case FORMAT_SUBST_MINOR: {
dev_t devnum;
r = sd_device_get_devnum(dev, &devnum);
if (r < 0 && r != -ENOENT)
return r;
strpcpyf_full(&s, l, &truncated, "%u", r < 0 ? 0 : type == FORMAT_SUBST_MAJOR ? major(devnum) : minor(devnum));
break;
}
case FORMAT_SUBST_RESULT: {
unsigned index = 0; /* 0 means whole string */
bool has_plus;
if (!event->program_result)
goto null_terminate;
if (!isempty(attr)) {
r = safe_atou_optional_plus(attr, &index);
if (r < 0)
return r;
has_plus = r;
}
if (index == 0)
strpcpy_full(&s, l, event->program_result, &truncated);
else {
const char *start, *p;
unsigned i;
p = skip_leading_chars(event->program_result, NULL);
for (i = 1; i < index; i++) {
while (*p && !strchr(WHITESPACE, *p))
p++;
p = skip_leading_chars(p, NULL);
if (*p == '\0')
break;
}
if (i != index) {
log_device_debug(dev, "requested part of result string not found");
goto null_terminate;
}
start = p;
/* %c{2+} copies the whole string from the second part on */
if (has_plus)
strpcpy_full(&s, l, start, &truncated);
else {
while (*p && !strchr(WHITESPACE, *p))
p++;
strnpcpy_full(&s, l, start, p - start, &truncated);
}
}
break;
}
case FORMAT_SUBST_ATTR: {
char vbuf[UDEV_NAME_SIZE];
int count;
bool t;
if (isempty(attr))
return -EINVAL;
/* try to read the value specified by "[dmi/id]product_name" */
if (udev_resolve_subsys_kernel(attr, vbuf, sizeof(vbuf), true) == 0)
val = vbuf;
/* try to read the attribute the device */
if (!val)
(void) sd_device_get_sysattr_value(dev, attr, &val);
/* try to read the attribute of the parent device, other matches have selected */
if (!val && event->dev_parent && event->dev_parent != dev)
(void) sd_device_get_sysattr_value(event->dev_parent, attr, &val);
if (!val)
goto null_terminate;
/* strip trailing whitespace, and replace unwanted characters */
if (val != vbuf)
strscpy_full(vbuf, sizeof(vbuf), val, &truncated);
delete_trailing_chars(vbuf, NULL);
count = udev_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
if (count > 0)
log_device_debug(dev, "%i character(s) replaced", count);
strpcpy_full(&s, l, vbuf, &t);
truncated = truncated || t;
break;
}
case FORMAT_SUBST_PARENT:
r = sd_device_get_parent(dev, &parent);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
r = sd_device_get_devname(parent, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
break;
case FORMAT_SUBST_DEVNODE:
r = sd_device_get_devname(dev, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_NAME:
if (event->name)
strpcpy_full(&s, l, event->name, &truncated);
else if (sd_device_get_devname(dev, &val) >= 0)
strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
else {
r = sd_device_get_sysname(dev, &val);
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
}
break;
case FORMAT_SUBST_LINKS:
FOREACH_DEVICE_DEVLINK(dev, link) {
if (s == dest)
strpcpy_full(&s, l, link + STRLEN("/dev/"), &truncated);
else
strpcpyl_full(&s, l, &truncated, " ", link + STRLEN("/dev/"), NULL);
if (truncated)
break;
}
if (s == dest)
goto null_terminate;
break;
case FORMAT_SUBST_ROOT:
strpcpy_full(&s, l, "/dev", &truncated);
break;
case FORMAT_SUBST_SYS:
strpcpy_full(&s, l, "/sys", &truncated);
break;
case FORMAT_SUBST_ENV:
if (isempty(attr))
return -EINVAL;
r = sd_device_get_property_value(dev, attr, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
default:
assert_not_reached();
}
if (ret_truncated)
*ret_truncated = truncated;
return s - dest;
null_terminate:
if (ret_truncated)
*ret_truncated = truncated;
*s = '\0';
return 0;
}
size_t udev_event_apply_format(
UdevEvent *event,
const char *src,
char *dest,
size_t size,
bool replace_whitespace,
bool *ret_truncated) {
bool truncated = false;
const char *s = ASSERT_PTR(src);
int r;
assert(event);
assert(event->dev);
assert(dest);
assert(size > 0);
while (*s) {
FormatSubstitutionType type;
char attr[UDEV_PATH_SIZE];
ssize_t subst_len;
bool t;
r = get_subst_type(&s, false, &type, attr);
if (r < 0) {
log_device_warning_errno(event->dev, r, "Invalid format string, ignoring: %s", src);
break;
} else if (r == 0) {
if (size < 2) {
/* need space for this char and the terminating NUL */
truncated = true;
break;
}
*dest++ = *s++;
size--;
continue;
}
subst_len = udev_event_subst_format(event, type, attr, dest, size, &t);
if (subst_len < 0) {
log_device_warning_errno(event->dev, subst_len,
"Failed to substitute variable '$%s' or apply format '%%%c', ignoring: %m",
format_type_to_string(type), format_type_to_char(type));
break;
}
truncated = truncated || t;
/* FORMAT_SUBST_RESULT handles spaces itself */
if (replace_whitespace && type != FORMAT_SUBST_RESULT)
/* udev_replace_whitespace can replace in-place,
* and does nothing if subst_len == 0 */
subst_len = udev_replace_whitespace(dest, dest, subst_len);
dest += subst_len;
size -= subst_len;
}
assert(size >= 1);
if (ret_truncated)
*ret_truncated = truncated;
*dest = '\0';
return size;
}
int udev_check_format(const char *value, size_t *offset, const char **hint) {
FormatSubstitutionType type;
const char *s = value;
char attr[UDEV_PATH_SIZE];
int r;
while (*s) {
r = get_subst_type(&s, true, &type, attr);
if (r < 0) {
if (offset)
*offset = s - value;
if (hint)
*hint = "invalid substitution type";
return r;
} else if (r == 0) {
s++;
continue;
}
if (IN_SET(type, FORMAT_SUBST_ATTR, FORMAT_SUBST_ENV) && isempty(attr)) {
if (offset)
*offset = s - value;
if (hint)
*hint = "attribute value missing";
return -EINVAL;
}
if (type == FORMAT_SUBST_RESULT && !isempty(attr)) {
unsigned i;
r = safe_atou_optional_plus(attr, &i);
if (r < 0) {
if (offset)
*offset = s - value;
if (hint)
*hint = "attribute value not a valid number";
return r;
}
}
}
return 0;
}
static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
Spawn *spawn = ASSERT_PTR(userdata);
char buf[4096], *p;
size_t size;
ssize_t l;
int r;
assert(fd == spawn->fd_stdout || fd == spawn->fd_stderr);
assert(!spawn->result || spawn->result_len < spawn->result_size);
if (fd == spawn->fd_stdout && spawn->result) {
p = spawn->result + spawn->result_len;
size = spawn->result_size - spawn->result_len;
} else {
p = buf;
size = sizeof(buf);
}
l = read(fd, p, size - (p == buf));
if (l < 0) {
if (errno == EAGAIN)
goto reenable;
log_device_error_errno(spawn->device, errno,
"Failed to read stdout of '%s': %m", spawn->cmd);
return 0;
}
if ((size_t) l == size) {
log_device_warning(spawn->device, "Truncating stdout of '%s' up to %zu byte.",
spawn->cmd, spawn->result_size);
l--;
spawn->truncated = true;
}
p[l] = '\0';
if (fd == spawn->fd_stdout && spawn->result)
spawn->result_len += l;
/* Log output only if we watch stderr. */
if (l > 0 && spawn->fd_stderr >= 0) {
_cleanup_strv_free_ char **v = NULL;
r = strv_split_newlines_full(&v, p, EXTRACT_RETAIN_ESCAPE);
if (r < 0)
log_device_debug(spawn->device,
"Failed to split output from '%s'(%s), ignoring: %m",
spawn->cmd, fd == spawn->fd_stdout ? "out" : "err");
STRV_FOREACH(q, v)
log_device_debug(spawn->device, "'%s'(%s) '%s'", spawn->cmd,
fd == spawn->fd_stdout ? "out" : "err", *q);
}
if (l == 0 || spawn->truncated)
return 0;
reenable:
/* Re-enable the event source if we did not encounter EOF */
r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
if (r < 0)
log_device_error_errno(spawn->device, r,
"Failed to reactivate IO source of '%s'", spawn->cmd);
return 0;
}
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
Spawn *spawn = ASSERT_PTR(userdata);
DEVICE_TRACE_POINT(spawn_timeout, spawn->device, spawn->cmd);
kill_and_sigcont(spawn->pid, spawn->timeout_signal);
log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing",
spawn->cmd, spawn->pid,
FORMAT_TIMESPAN(spawn->timeout_usec, USEC_PER_SEC));
return 1;
}
static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
Spawn *spawn = ASSERT_PTR(userdata);
log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete",
spawn->cmd, spawn->pid,
FORMAT_TIMESPAN(spawn->timeout_warn_usec, USEC_PER_SEC));
return 1;
}
static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
Spawn *spawn = ASSERT_PTR(userdata);
int ret = -EIO;
switch (si->si_code) {
case CLD_EXITED:
if (si->si_status == 0)
log_device_debug(spawn->device, "Process '%s' succeeded.", spawn->cmd);
else
log_device_full(spawn->device, spawn->accept_failure ? LOG_DEBUG : LOG_WARNING,
"Process '%s' failed with exit code %i.", spawn->cmd, si->si_status);
ret = si->si_status;
break;
case CLD_KILLED:
case CLD_DUMPED:
log_device_error(spawn->device, "Process '%s' terminated by signal %s.", spawn->cmd, signal_to_string(si->si_status));
break;
default:
log_device_error(spawn->device, "Process '%s' failed due to unknown reason.", spawn->cmd);
}
DEVICE_TRACE_POINT(spawn_exit, spawn->device, spawn->cmd);
sd_event_exit(sd_event_source_get_event(s), ret);
return 1;
}
static int spawn_wait(Spawn *spawn) {
_cleanup_(sd_event_unrefp) sd_event *e = NULL;
_cleanup_(sd_event_source_disable_unrefp) sd_event_source *sigchld_source = NULL;
_cleanup_(sd_event_source_disable_unrefp) sd_event_source *stdout_source = NULL;
_cleanup_(sd_event_source_disable_unrefp) sd_event_source *stderr_source = NULL;
int r;
assert(spawn);
r = sd_event_new(&e);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to allocate sd-event object: %m");
if (spawn->timeout_usec > 0) {
usec_t usec, age_usec;
usec = now(CLOCK_MONOTONIC);
age_usec = usec - spawn->event_birth_usec;
if (age_usec < spawn->timeout_usec) {
if (spawn->timeout_warn_usec > 0 &&
spawn->timeout_warn_usec < spawn->timeout_usec &&
spawn->timeout_warn_usec > age_usec) {
spawn->timeout_warn_usec -= age_usec;
r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
usec + spawn->timeout_warn_usec, USEC_PER_SEC,
on_spawn_timeout_warning, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create timeout warning event source: %m");
}
spawn->timeout_usec -= age_usec;
r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
usec + spawn->timeout_usec, USEC_PER_SEC, on_spawn_timeout, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create timeout event source: %m");
}
}
if (spawn->fd_stdout >= 0) {
r = sd_event_add_io(e, &stdout_source, spawn->fd_stdout, EPOLLIN, on_spawn_io, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create stdio event source: %m");
r = sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to enable stdio event source: %m");
}
if (spawn->fd_stderr >= 0) {
r = sd_event_add_io(e, &stderr_source, spawn->fd_stderr, EPOLLIN, on_spawn_io, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create stderr event source: %m");
r = sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to enable stderr event source: %m");
}
r = sd_event_add_child(e, &sigchld_source, spawn->pid, WEXITED, on_spawn_sigchld, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create sigchild event source: %m");
/* SIGCHLD should be processed after IO is complete */
r = sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to set priority to sigchild event source: %m");
return sd_event_loop(e);
}
int udev_event_spawn(
UdevEvent *event,
usec_t timeout_usec,
int timeout_signal,
bool accept_failure,
const char *cmd,
char *result,
size_t ressize,
bool *ret_truncated) {
_cleanup_close_pair_ int outpipe[2] = PIPE_EBADF, errpipe[2] = PIPE_EBADF;
_cleanup_strv_free_ char **argv = NULL;
char **envp = NULL;
Spawn spawn;
pid_t pid;
int r;
assert(event);
assert(event->dev);
assert(result || ressize == 0);
/* pipes from child to parent */
if (result || log_get_max_level() >= LOG_INFO)
if (pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) != 0)
return log_device_error_errno(event->dev, errno,
"Failed to create pipe for command '%s': %m", cmd);
if (log_get_max_level() >= LOG_INFO)
if (pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) != 0)
return log_device_error_errno(event->dev, errno,
"Failed to create pipe for command '%s': %m", cmd);
r = strv_split_full(&argv, cmd, NULL, EXTRACT_UNQUOTE | EXTRACT_RELAX | EXTRACT_RETAIN_ESCAPE);
if (r < 0)
return log_device_error_errno(event->dev, r, "Failed to split command: %m");
if (isempty(argv[0]))
return log_device_error_errno(event->dev, SYNTHETIC_ERRNO(EINVAL),
"Invalid command '%s'", cmd);
/* allow programs in /usr/lib/udev/ to be called without the path */
if (!path_is_absolute(argv[0])) {
char *program;
program = path_join(UDEVLIBEXECDIR, argv[0]);
if (!program)
return log_oom();
free_and_replace(argv[0], program);
}
r = device_get_properties_strv(event->dev, &envp);
if (r < 0)
return log_device_error_errno(event->dev, r, "Failed to get device properties");
log_device_debug(event->dev, "Starting '%s'", cmd);
r = safe_fork_full("(spawn)",
(int[]) { -EBADF, outpipe[WRITE_END], errpipe[WRITE_END] },
NULL, 0,
FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_REARRANGE_STDIO|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE,
&pid);
if (r < 0)
return log_device_error_errno(event->dev, r,
"Failed to fork() to execute command '%s': %m", cmd);
if (r == 0) {
DEVICE_TRACE_POINT(spawn_exec, event->dev, cmd);
execve(argv[0], argv, envp);
_exit(EXIT_FAILURE);
}
/* parent closed child's ends of pipes */
outpipe[WRITE_END] = safe_close(outpipe[WRITE_END]);
errpipe[WRITE_END] = safe_close(errpipe[WRITE_END]);
spawn = (Spawn) {
.device = event->dev,
.cmd = cmd,
.pid = pid,
.accept_failure = accept_failure,
.timeout_warn_usec = udev_warn_timeout(timeout_usec),
.timeout_usec = timeout_usec,
.timeout_signal = timeout_signal,
.event_birth_usec = event->birth_usec,
.fd_stdout = outpipe[READ_END],
.fd_stderr = errpipe[READ_END],
.result = result,
.result_size = ressize,
};
r = spawn_wait(&spawn);
if (r < 0)
return log_device_error_errno(event->dev, r,
"Failed to wait for spawned command '%s': %m", cmd);
if (result)
result[spawn.result_len] = '\0';
if (ret_truncated)
*ret_truncated = spawn.truncated;
return r; /* 0 for success, and positive if the program failed */
}
static int device_rename(sd_device *device, const char *name) {
_cleanup_free_ char *new_syspath = NULL;
const char *s;
@@ -1204,34 +404,3 @@ int udev_event_execute_rules(
return 0;
}
void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal) {
const char *command;
void *val;
int r;
ORDERED_HASHMAP_FOREACH_KEY(val, command, event->run_list) {
UdevBuiltinCommand builtin_cmd = PTR_TO_UDEV_BUILTIN_CMD(val);
if (builtin_cmd != _UDEV_BUILTIN_INVALID) {
log_device_debug(event->dev, "Running built-in command \"%s\"", command);
r = udev_builtin_run(event, builtin_cmd, command, false);
if (r < 0)
log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command);
} else {
if (event->exec_delay_usec > 0) {
log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.",
command, FORMAT_TIMESPAN(event->exec_delay_usec, USEC_PER_SEC));
(void) usleep_safe(event->exec_delay_usec);
}
log_device_debug(event->dev, "Running command \"%s\"", command);
r = udev_event_spawn(event, timeout_usec, timeout_signal, false, command, NULL, 0, NULL);
if (r < 0)
log_device_warning_errno(event->dev, r, "Failed to execute '%s', ignoring: %m", command);
else if (r > 0) /* returned value is positive when program fails */
log_device_debug(event->dev, "Command \"%s\" returned %d (error), ignoring.", command, r);
}
}
}
+5 -27
View File
@@ -5,17 +5,17 @@
* Copyright © 2003 Greg Kroah-Hartman <greg@kroah.com>
*/
#include <stdbool.h>
#include <stddef.h>
#include "sd-device.h"
#include "sd-netlink.h"
#include "hashmap.h"
#include "macro.h"
#include "time-util.h"
#include "udev-rules.h"
#include "udev-util.h"
#define READ_END 0
#define WRITE_END 1
#define UDEV_ALLOWED_CHARS_INPUT "/ $%?,"
#include "user-util.h"
typedef struct UdevEvent {
sd_device *dev;
@@ -51,23 +51,6 @@ UdevEvent *udev_event_new(sd_device *dev, usec_t exec_delay_usec, sd_netlink *rt
UdevEvent *udev_event_free(UdevEvent *event);
DEFINE_TRIVIAL_CLEANUP_FUNC(UdevEvent*, udev_event_free);
size_t udev_event_apply_format(
UdevEvent *event,
const char *src,
char *dest,
size_t size,
bool replace_whitespace,
bool *ret_truncated);
int udev_check_format(const char *value, size_t *offset, const char **hint);
int udev_event_spawn(
UdevEvent *event,
usec_t timeout_usec,
int timeout_signal,
bool accept_failure,
const char *cmd,
char *result,
size_t ressize,
bool *ret_truncated);
int udev_event_execute_rules(
UdevEvent *event,
int inotify_fd,
@@ -75,8 +58,3 @@ int udev_event_execute_rules(
int timeout_signal,
Hashmap *properties_list,
UdevRules *rules);
void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal);
static inline usec_t udev_warn_timeout(usec_t timeout_usec) {
return DIV_ROUND_UP(timeout_usec, 3);
}
+548
View File
@@ -0,0 +1,548 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "device-util.h"
#include "errno-util.h"
#include "parse-util.h"
#include "string-util.h"
#include "strxcpyx.h"
#include "udev-event.h"
#include "udev-format.h"
#include "udev-util.h"
typedef enum {
FORMAT_SUBST_DEVNODE,
FORMAT_SUBST_ATTR,
FORMAT_SUBST_ENV,
FORMAT_SUBST_KERNEL,
FORMAT_SUBST_KERNEL_NUMBER,
FORMAT_SUBST_DRIVER,
FORMAT_SUBST_DEVPATH,
FORMAT_SUBST_ID,
FORMAT_SUBST_MAJOR,
FORMAT_SUBST_MINOR,
FORMAT_SUBST_RESULT,
FORMAT_SUBST_PARENT,
FORMAT_SUBST_NAME,
FORMAT_SUBST_LINKS,
FORMAT_SUBST_ROOT,
FORMAT_SUBST_SYS,
_FORMAT_SUBST_TYPE_MAX,
_FORMAT_SUBST_TYPE_INVALID = -EINVAL,
} FormatSubstitutionType;
struct subst_map_entry {
const char *name;
const char fmt;
FormatSubstitutionType type;
};
static const struct subst_map_entry map[] = {
{ .name = "devnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE },
{ .name = "tempnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE }, /* deprecated */
{ .name = "attr", .fmt = 's', .type = FORMAT_SUBST_ATTR },
{ .name = "sysfs", .fmt = 's', .type = FORMAT_SUBST_ATTR }, /* deprecated */
{ .name = "env", .fmt = 'E', .type = FORMAT_SUBST_ENV },
{ .name = "kernel", .fmt = 'k', .type = FORMAT_SUBST_KERNEL },
{ .name = "number", .fmt = 'n', .type = FORMAT_SUBST_KERNEL_NUMBER },
{ .name = "driver", .fmt = 'd', .type = FORMAT_SUBST_DRIVER },
{ .name = "devpath", .fmt = 'p', .type = FORMAT_SUBST_DEVPATH },
{ .name = "id", .fmt = 'b', .type = FORMAT_SUBST_ID },
{ .name = "major", .fmt = 'M', .type = FORMAT_SUBST_MAJOR },
{ .name = "minor", .fmt = 'm', .type = FORMAT_SUBST_MINOR },
{ .name = "result", .fmt = 'c', .type = FORMAT_SUBST_RESULT },
{ .name = "parent", .fmt = 'P', .type = FORMAT_SUBST_PARENT },
{ .name = "name", .fmt = 'D', .type = FORMAT_SUBST_NAME },
{ .name = "links", .fmt = 'L', .type = FORMAT_SUBST_LINKS },
{ .name = "root", .fmt = 'r', .type = FORMAT_SUBST_ROOT },
{ .name = "sys", .fmt = 'S', .type = FORMAT_SUBST_SYS },
};
static const char *format_type_to_string(FormatSubstitutionType t) {
for (size_t i = 0; i < ELEMENTSOF(map); i++)
if (map[i].type == t)
return map[i].name;
return NULL;
}
static char format_type_to_char(FormatSubstitutionType t) {
for (size_t i = 0; i < ELEMENTSOF(map); i++)
if (map[i].type == t)
return map[i].fmt;
return '\0';
}
static int get_subst_type(const char **str, bool strict, FormatSubstitutionType *ret_type, char ret_attr[static UDEV_PATH_SIZE]) {
const char *p = *str, *q = NULL;
size_t i;
assert(str);
assert(*str);
assert(ret_type);
assert(ret_attr);
if (*p == '$') {
p++;
if (*p == '$') {
*str = p;
return 0;
}
for (i = 0; i < ELEMENTSOF(map); i++)
if ((q = startswith(p, map[i].name)))
break;
} else if (*p == '%') {
p++;
if (*p == '%') {
*str = p;
return 0;
}
for (i = 0; i < ELEMENTSOF(map); i++)
if (*p == map[i].fmt) {
q = p + 1;
break;
}
} else
return 0;
if (!q)
/* When 'strict' flag is set, then '$' and '%' must be escaped. */
return strict ? -EINVAL : 0;
if (*q == '{') {
const char *start, *end;
size_t len;
start = q + 1;
end = strchr(start, '}');
if (!end)
return -EINVAL;
len = end - start;
if (len == 0 || len >= UDEV_PATH_SIZE)
return -EINVAL;
strnscpy(ret_attr, UDEV_PATH_SIZE, start, len);
q = end + 1;
} else
*ret_attr = '\0';
*str = q;
*ret_type = map[i].type;
return 1;
}
static int safe_atou_optional_plus(const char *s, unsigned *ret) {
const char *p;
int r;
assert(s);
assert(ret);
/* Returns 1 if plus, 0 if no plus, negative on error */
p = endswith(s, "+");
if (p)
s = strndupa_safe(s, p - s);
r = safe_atou(s, ret);
if (r < 0)
return r;
return !!p;
}
static ssize_t udev_event_subst_format(
UdevEvent *event,
FormatSubstitutionType type,
const char *attr,
char *dest,
size_t l,
bool *ret_truncated) {
sd_device *parent, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
const char *val = NULL;
bool truncated = false;
char *s = dest;
int r;
switch (type) {
case FORMAT_SUBST_DEVPATH:
r = sd_device_get_devpath(dev, &val);
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_KERNEL:
r = sd_device_get_sysname(dev, &val);
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_KERNEL_NUMBER:
r = sd_device_get_sysnum(dev, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_ID:
if (!event->dev_parent)
goto null_terminate;
r = sd_device_get_sysname(event->dev_parent, &val);
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_DRIVER:
if (!event->dev_parent)
goto null_terminate;
r = sd_device_get_driver(event->dev_parent, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_MAJOR:
case FORMAT_SUBST_MINOR: {
dev_t devnum;
r = sd_device_get_devnum(dev, &devnum);
if (r < 0 && r != -ENOENT)
return r;
strpcpyf_full(&s, l, &truncated, "%u", r < 0 ? 0 : type == FORMAT_SUBST_MAJOR ? major(devnum) : minor(devnum));
break;
}
case FORMAT_SUBST_RESULT: {
unsigned index = 0; /* 0 means whole string */
bool has_plus;
if (!event->program_result)
goto null_terminate;
if (!isempty(attr)) {
r = safe_atou_optional_plus(attr, &index);
if (r < 0)
return r;
has_plus = r;
}
if (index == 0)
strpcpy_full(&s, l, event->program_result, &truncated);
else {
const char *start, *p;
unsigned i;
p = skip_leading_chars(event->program_result, NULL);
for (i = 1; i < index; i++) {
while (*p && !strchr(WHITESPACE, *p))
p++;
p = skip_leading_chars(p, NULL);
if (*p == '\0')
break;
}
if (i != index) {
log_device_debug(dev, "requested part of result string not found");
goto null_terminate;
}
start = p;
/* %c{2+} copies the whole string from the second part on */
if (has_plus)
strpcpy_full(&s, l, start, &truncated);
else {
while (*p && !strchr(WHITESPACE, *p))
p++;
strnpcpy_full(&s, l, start, p - start, &truncated);
}
}
break;
}
case FORMAT_SUBST_ATTR: {
char vbuf[UDEV_NAME_SIZE];
int count;
bool t;
if (isempty(attr))
return -EINVAL;
/* try to read the value specified by "[dmi/id]product_name" */
if (udev_resolve_subsys_kernel(attr, vbuf, sizeof(vbuf), true) == 0)
val = vbuf;
/* try to read the attribute the device */
if (!val)
(void) sd_device_get_sysattr_value(dev, attr, &val);
/* try to read the attribute of the parent device, other matches have selected */
if (!val && event->dev_parent && event->dev_parent != dev)
(void) sd_device_get_sysattr_value(event->dev_parent, attr, &val);
if (!val)
goto null_terminate;
/* strip trailing whitespace, and replace unwanted characters */
if (val != vbuf)
strscpy_full(vbuf, sizeof(vbuf), val, &truncated);
delete_trailing_chars(vbuf, NULL);
count = udev_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
if (count > 0)
log_device_debug(dev, "%i character(s) replaced", count);
strpcpy_full(&s, l, vbuf, &t);
truncated = truncated || t;
break;
}
case FORMAT_SUBST_PARENT:
r = sd_device_get_parent(dev, &parent);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
r = sd_device_get_devname(parent, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
break;
case FORMAT_SUBST_DEVNODE:
r = sd_device_get_devname(dev, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
case FORMAT_SUBST_NAME:
if (event->name)
strpcpy_full(&s, l, event->name, &truncated);
else if (sd_device_get_devname(dev, &val) >= 0)
strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
else {
r = sd_device_get_sysname(dev, &val);
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
}
break;
case FORMAT_SUBST_LINKS:
FOREACH_DEVICE_DEVLINK(dev, link) {
if (s == dest)
strpcpy_full(&s, l, link + STRLEN("/dev/"), &truncated);
else
strpcpyl_full(&s, l, &truncated, " ", link + STRLEN("/dev/"), NULL);
if (truncated)
break;
}
if (s == dest)
goto null_terminate;
break;
case FORMAT_SUBST_ROOT:
strpcpy_full(&s, l, "/dev", &truncated);
break;
case FORMAT_SUBST_SYS:
strpcpy_full(&s, l, "/sys", &truncated);
break;
case FORMAT_SUBST_ENV:
if (isempty(attr))
return -EINVAL;
r = sd_device_get_property_value(dev, attr, &val);
if (r == -ENOENT)
goto null_terminate;
if (r < 0)
return r;
strpcpy_full(&s, l, val, &truncated);
break;
default:
assert_not_reached();
}
if (ret_truncated)
*ret_truncated = truncated;
return s - dest;
null_terminate:
if (ret_truncated)
*ret_truncated = truncated;
*s = '\0';
return 0;
}
size_t udev_event_apply_format(
UdevEvent *event,
const char *src,
char *dest,
size_t size,
bool replace_whitespace,
bool *ret_truncated) {
bool truncated = false;
const char *s = ASSERT_PTR(src);
int r;
assert(event);
assert(event->dev);
assert(dest);
assert(size > 0);
while (*s) {
FormatSubstitutionType type;
char attr[UDEV_PATH_SIZE];
ssize_t subst_len;
bool t;
r = get_subst_type(&s, false, &type, attr);
if (r < 0) {
log_device_warning_errno(event->dev, r, "Invalid format string, ignoring: %s", src);
break;
} else if (r == 0) {
if (size < 2) {
/* need space for this char and the terminating NUL */
truncated = true;
break;
}
*dest++ = *s++;
size--;
continue;
}
subst_len = udev_event_subst_format(event, type, attr, dest, size, &t);
if (subst_len < 0) {
log_device_warning_errno(event->dev, subst_len,
"Failed to substitute variable '$%s' or apply format '%%%c', ignoring: %m",
format_type_to_string(type), format_type_to_char(type));
break;
}
truncated = truncated || t;
/* FORMAT_SUBST_RESULT handles spaces itself */
if (replace_whitespace && type != FORMAT_SUBST_RESULT)
/* udev_replace_whitespace can replace in-place,
* and does nothing if subst_len == 0 */
subst_len = udev_replace_whitespace(dest, dest, subst_len);
dest += subst_len;
size -= subst_len;
}
assert(size >= 1);
if (ret_truncated)
*ret_truncated = truncated;
*dest = '\0';
return size;
}
int udev_check_format(const char *value, size_t *offset, const char **hint) {
FormatSubstitutionType type;
const char *s = value;
char attr[UDEV_PATH_SIZE];
int r;
while (*s) {
r = get_subst_type(&s, true, &type, attr);
if (r < 0) {
if (offset)
*offset = s - value;
if (hint)
*hint = "invalid substitution type";
return r;
} else if (r == 0) {
s++;
continue;
}
if (IN_SET(type, FORMAT_SUBST_ATTR, FORMAT_SUBST_ENV) && isempty(attr)) {
if (offset)
*offset = s - value;
if (hint)
*hint = "attribute value missing";
return -EINVAL;
}
if (type == FORMAT_SUBST_RESULT && !isempty(attr)) {
unsigned i;
r = safe_atou_optional_plus(attr, &i);
if (r < 0) {
if (offset)
*offset = s - value;
if (hint)
*hint = "attribute value not a valid number";
return r;
}
}
}
return 0;
}
int udev_resolve_subsys_kernel(const char *string, char *result, size_t maxsize, bool read_value) {
_cleanup_(sd_device_unrefp) sd_device *dev = NULL;
_cleanup_free_ char *temp = NULL;
char *subsys, *sysname, *attr;
const char *val;
int r;
assert(string);
assert(result);
/* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
if (string[0] != '[')
return -EINVAL;
temp = strdup(string);
if (!temp)
return -ENOMEM;
subsys = &temp[1];
sysname = strchr(subsys, '/');
if (!sysname)
return -EINVAL;
sysname[0] = '\0';
sysname = &sysname[1];
attr = strchr(sysname, ']');
if (!attr)
return -EINVAL;
attr[0] = '\0';
attr = &attr[1];
if (attr[0] == '/')
attr = &attr[1];
if (attr[0] == '\0')
attr = NULL;
if (read_value && !attr)
return -EINVAL;
r = sd_device_new_from_subsystem_sysname(&dev, subsys, sysname);
if (r < 0)
return r;
if (read_value) {
r = sd_device_get_sysattr_value(dev, attr, &val);
if (r < 0 && !ERRNO_IS_PRIVILEGE(r) && r != -ENOENT)
return r;
if (r >= 0)
strscpy(result, maxsize, val);
else
result[0] = '\0';
log_debug("value '[%s/%s]%s' is '%s'", subsys, sysname, attr, result);
} else {
r = sd_device_get_syspath(dev, &val);
if (r < 0)
return r;
strscpyl(result, maxsize, val, attr ? "/" : NULL, attr ?: NULL, NULL);
log_debug("path '[%s/%s]%s' is '%s'", subsys, sysname, strempty(attr), result);
}
return 0;
}
+20
View File
@@ -0,0 +1,20 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <stdbool.h>
#include <stddef.h>
typedef struct UdevEvent UdevEvent;
#define UDEV_ALLOWED_CHARS_INPUT "/ $%?,"
size_t udev_event_apply_format(
UdevEvent *event,
const char *src,
char *dest,
size_t size,
bool replace_whitespace,
bool *ret_truncated);
int udev_check_format(const char *value, size_t *offset, const char **hint);
int udev_resolve_subsys_kernel(const char *string, char *result, size_t maxsize, bool read_value);
File diff suppressed because it is too large Load Diff
+62
View File
@@ -0,0 +1,62 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <stdbool.h>
#include "sd-device.h"
#include "sd-event.h"
#include "hashmap.h"
#include "macro.h"
#include "time-util.h"
#include "udev-ctrl.h"
#include "udev-rules.h"
typedef struct Event Event;
typedef struct Worker Worker;
typedef struct Manager {
sd_event *event;
Hashmap *workers;
LIST_HEAD(Event, events);
char *cgroup;
int log_level;
UdevRules *rules;
Hashmap *properties;
sd_device_monitor *monitor;
UdevCtrl *ctrl;
int worker_watch[2];
/* used by udev-watch */
int inotify_fd;
sd_event_source *inotify_event;
sd_event_source *kill_workers_event;
sd_event_source *memory_pressure_event_source;
sd_event_source *sigrtmin18_event_source;
usec_t last_usec;
ResolveNameTiming resolve_name_timing;
unsigned children_max;
usec_t exec_delay_usec;
usec_t timeout_usec;
int timeout_signal;
bool blockdev_read_only;
bool udev_node_needs_cleanup;
bool stop_exec_queue;
bool exit;
} Manager;
Manager* manager_new(void);
Manager* manager_free(Manager *manager);
DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free);
int manager_init(Manager *manager, int fd_ctrl, int fd_uevent);
int manager_main(Manager *manager);
bool devpath_conflict(const char *a, const char *b);
+86
View File
@@ -11,6 +11,7 @@
#include "device-private.h"
#include "device-util.h"
#include "dirent-util.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
@@ -23,15 +24,20 @@
#include "parse-util.h"
#include "path-util.h"
#include "proc-cmdline.h"
#include "socket-util.h"
#include "stat-util.h"
#include "string-table.h"
#include "strv.h"
#include "strxcpyx.h"
#include "sysctl-util.h"
#include "syslog-util.h"
#include "udev-builtin.h"
#include "udev-event.h"
#include "udev-format.h"
#include "udev-node.h"
#include "udev-rules.h"
#include "udev-spawn.h"
#include "udev-trace.h"
#include "udev-util.h"
#include "user-util.h"
#include "virt.h"
@@ -1115,6 +1121,62 @@ static void check_token_delimiters(UdevRuleLine *rule_line, const char *line) {
}
}
int udev_rule_parse_value(char *str, char **ret_value, char **ret_endpos) {
char *i, *j;
bool is_escaped;
/* value must be double quotated */
is_escaped = str[0] == 'e';
str += is_escaped;
if (str[0] != '"')
return -EINVAL;
if (!is_escaped) {
/* unescape double quotation '\"'->'"' */
for (j = str, i = str + 1; *i != '"'; i++, j++) {
if (*i == '\0')
return -EINVAL;
if (i[0] == '\\' && i[1] == '"')
i++;
*j = *i;
}
j[0] = '\0';
/*
* The return value must be terminated by two subsequent NULs
* so it could be safely interpreted as nulstr.
*/
j[1] = '\0';
} else {
_cleanup_free_ char *unescaped = NULL;
ssize_t l;
/* find the end position of value */
for (i = str + 1; *i != '"'; i++) {
if (i[0] == '\\')
i++;
if (*i == '\0')
return -EINVAL;
}
i[0] = '\0';
l = cunescape_length(str + 1, i - (str + 1), 0, &unescaped);
if (l < 0)
return l;
assert(l <= i - (str + 1));
memcpy(str, unescaped, l + 1);
/*
* The return value must be terminated by two subsequent NULs
* so it could be safely interpreted as nulstr.
*/
str[l + 1] = '\0';
}
*ret_value = str;
*ret_endpos = i + 1;
return 0;
}
static int parse_line(char **line, char **ret_key, char **ret_attr, UdevRuleOperatorType *ret_op, char **ret_value) {
char *key_begin, *key_end, *attr, *tmp;
UdevRuleOperatorType op;
@@ -1847,6 +1909,22 @@ static int attr_subst_subdir(char attr[static UDEV_PATH_SIZE]) {
return -ENOENT;
}
static size_t udev_replace_ifname(char *str) {
size_t replaced = 0;
assert(str);
/* See ifname_valid_full(). */
for (char *p = str; *p != '\0'; p++)
if (!ifname_valid_char(*p)) {
*p = '_';
replaced++;
}
return replaced;
}
static int udev_rule_apply_token_to_event(
UdevRuleToken *token,
sd_device *dev,
@@ -2878,3 +2956,11 @@ int udev_rules_apply_static_dev_perms(UdevRules *rules) {
return 0;
}
static const char* const resolve_name_timing_table[_RESOLVE_NAME_TIMING_MAX] = {
[RESOLVE_NAME_NEVER] = "never",
[RESOLVE_NAME_LATE] = "late",
[RESOLVE_NAME_EARLY] = "early",
};
DEFINE_STRING_TABLE_LOOKUP(resolve_name_timing, ResolveNameTiming);
+16 -1
View File
@@ -4,7 +4,10 @@
#include "alloc-util.h"
#include "hashmap.h"
#include "time-util.h"
#include "udev-util.h"
#define UDEV_NAME_SIZE 512
#define UDEV_PATH_SIZE 1024
#define UDEV_LINE_SIZE 16384
typedef struct UdevRuleFile UdevRuleFile;
typedef struct UdevRules UdevRules;
@@ -18,6 +21,15 @@ typedef enum {
_ESCAPE_TYPE_INVALID = -EINVAL,
} UdevRuleEscapeType;
typedef enum ResolveNameTiming {
RESOLVE_NAME_NEVER,
RESOLVE_NAME_LATE,
RESOLVE_NAME_EARLY,
_RESOLVE_NAME_TIMING_MAX,
_RESOLVE_NAME_TIMING_INVALID = -EINVAL,
} ResolveNameTiming;
int udev_rule_parse_value(char *str, char **ret_value, char **ret_endpos);
int udev_rules_parse_file(UdevRules *rules, const char *filename, bool extra_checks, UdevRuleFile **ret);
unsigned udev_rule_file_get_issues(UdevRuleFile *rule_file);
UdevRules* udev_rules_new(ResolveNameTiming resolve_name_timing);
@@ -32,3 +44,6 @@ int udev_rules_apply_to_event(UdevRules *rules, UdevEvent *event,
int timeout_signal,
Hashmap *properties_list);
int udev_rules_apply_static_dev_perms(UdevRules *rules);
ResolveNameTiming resolve_name_timing_from_string(const char *s) _pure_;
const char *resolve_name_timing_to_string(ResolveNameTiming i) _const_;
+355
View File
@@ -0,0 +1,355 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "sd-event.h"
#include "device-private.h"
#include "device-util.h"
#include "fd-util.h"
#include "path-util.h"
#include "process-util.h"
#include "signal-util.h"
#include "string-util.h"
#include "strv.h"
#include "udev-builtin.h"
#include "udev-event.h"
#include "udev-spawn.h"
#include "udev-trace.h"
typedef struct Spawn {
sd_device *device;
const char *cmd;
pid_t pid;
usec_t timeout_warn_usec;
usec_t timeout_usec;
int timeout_signal;
usec_t event_birth_usec;
bool accept_failure;
int fd_stdout;
int fd_stderr;
char *result;
size_t result_size;
size_t result_len;
bool truncated;
} Spawn;
static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
Spawn *spawn = ASSERT_PTR(userdata);
char buf[4096], *p;
size_t size;
ssize_t l;
int r;
assert(fd == spawn->fd_stdout || fd == spawn->fd_stderr);
assert(!spawn->result || spawn->result_len < spawn->result_size);
if (fd == spawn->fd_stdout && spawn->result) {
p = spawn->result + spawn->result_len;
size = spawn->result_size - spawn->result_len;
} else {
p = buf;
size = sizeof(buf);
}
l = read(fd, p, size - (p == buf));
if (l < 0) {
if (errno == EAGAIN)
goto reenable;
log_device_error_errno(spawn->device, errno,
"Failed to read stdout of '%s': %m", spawn->cmd);
return 0;
}
if ((size_t) l == size) {
log_device_warning(spawn->device, "Truncating stdout of '%s' up to %zu byte.",
spawn->cmd, spawn->result_size);
l--;
spawn->truncated = true;
}
p[l] = '\0';
if (fd == spawn->fd_stdout && spawn->result)
spawn->result_len += l;
/* Log output only if we watch stderr. */
if (l > 0 && spawn->fd_stderr >= 0) {
_cleanup_strv_free_ char **v = NULL;
r = strv_split_newlines_full(&v, p, EXTRACT_RETAIN_ESCAPE);
if (r < 0)
log_device_debug(spawn->device,
"Failed to split output from '%s'(%s), ignoring: %m",
spawn->cmd, fd == spawn->fd_stdout ? "out" : "err");
STRV_FOREACH(q, v)
log_device_debug(spawn->device, "'%s'(%s) '%s'", spawn->cmd,
fd == spawn->fd_stdout ? "out" : "err", *q);
}
if (l == 0 || spawn->truncated)
return 0;
reenable:
/* Re-enable the event source if we did not encounter EOF */
r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
if (r < 0)
log_device_error_errno(spawn->device, r,
"Failed to reactivate IO source of '%s'", spawn->cmd);
return 0;
}
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
Spawn *spawn = ASSERT_PTR(userdata);
DEVICE_TRACE_POINT(spawn_timeout, spawn->device, spawn->cmd);
kill_and_sigcont(spawn->pid, spawn->timeout_signal);
log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing",
spawn->cmd, spawn->pid,
FORMAT_TIMESPAN(spawn->timeout_usec, USEC_PER_SEC));
return 1;
}
static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
Spawn *spawn = ASSERT_PTR(userdata);
log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete",
spawn->cmd, spawn->pid,
FORMAT_TIMESPAN(spawn->timeout_warn_usec, USEC_PER_SEC));
return 1;
}
static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
Spawn *spawn = ASSERT_PTR(userdata);
int ret = -EIO;
switch (si->si_code) {
case CLD_EXITED:
if (si->si_status == 0)
log_device_debug(spawn->device, "Process '%s' succeeded.", spawn->cmd);
else
log_device_full(spawn->device, spawn->accept_failure ? LOG_DEBUG : LOG_WARNING,
"Process '%s' failed with exit code %i.", spawn->cmd, si->si_status);
ret = si->si_status;
break;
case CLD_KILLED:
case CLD_DUMPED:
log_device_error(spawn->device, "Process '%s' terminated by signal %s.", spawn->cmd, signal_to_string(si->si_status));
break;
default:
log_device_error(spawn->device, "Process '%s' failed due to unknown reason.", spawn->cmd);
}
DEVICE_TRACE_POINT(spawn_exit, spawn->device, spawn->cmd);
sd_event_exit(sd_event_source_get_event(s), ret);
return 1;
}
static int spawn_wait(Spawn *spawn) {
_cleanup_(sd_event_unrefp) sd_event *e = NULL;
_cleanup_(sd_event_source_disable_unrefp) sd_event_source *sigchld_source = NULL;
_cleanup_(sd_event_source_disable_unrefp) sd_event_source *stdout_source = NULL;
_cleanup_(sd_event_source_disable_unrefp) sd_event_source *stderr_source = NULL;
int r;
assert(spawn);
r = sd_event_new(&e);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to allocate sd-event object: %m");
if (spawn->timeout_usec > 0) {
usec_t usec, age_usec;
usec = now(CLOCK_MONOTONIC);
age_usec = usec - spawn->event_birth_usec;
if (age_usec < spawn->timeout_usec) {
if (spawn->timeout_warn_usec > 0 &&
spawn->timeout_warn_usec < spawn->timeout_usec &&
spawn->timeout_warn_usec > age_usec) {
spawn->timeout_warn_usec -= age_usec;
r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
usec + spawn->timeout_warn_usec, USEC_PER_SEC,
on_spawn_timeout_warning, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create timeout warning event source: %m");
}
spawn->timeout_usec -= age_usec;
r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
usec + spawn->timeout_usec, USEC_PER_SEC, on_spawn_timeout, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create timeout event source: %m");
}
}
if (spawn->fd_stdout >= 0) {
r = sd_event_add_io(e, &stdout_source, spawn->fd_stdout, EPOLLIN, on_spawn_io, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create stdio event source: %m");
r = sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to enable stdio event source: %m");
}
if (spawn->fd_stderr >= 0) {
r = sd_event_add_io(e, &stderr_source, spawn->fd_stderr, EPOLLIN, on_spawn_io, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create stderr event source: %m");
r = sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to enable stderr event source: %m");
}
r = sd_event_add_child(e, &sigchld_source, spawn->pid, WEXITED, on_spawn_sigchld, spawn);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to create sigchild event source: %m");
/* SIGCHLD should be processed after IO is complete */
r = sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1);
if (r < 0)
return log_device_debug_errno(spawn->device, r, "Failed to set priority to sigchild event source: %m");
return sd_event_loop(e);
}
int udev_event_spawn(
UdevEvent *event,
usec_t timeout_usec,
int timeout_signal,
bool accept_failure,
const char *cmd,
char *result,
size_t ressize,
bool *ret_truncated) {
_cleanup_close_pair_ int outpipe[2] = PIPE_EBADF, errpipe[2] = PIPE_EBADF;
_cleanup_strv_free_ char **argv = NULL;
char **envp = NULL;
Spawn spawn;
pid_t pid;
int r;
assert(event);
assert(event->dev);
assert(result || ressize == 0);
/* pipes from child to parent */
if (result || log_get_max_level() >= LOG_INFO)
if (pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) != 0)
return log_device_error_errno(event->dev, errno,
"Failed to create pipe for command '%s': %m", cmd);
if (log_get_max_level() >= LOG_INFO)
if (pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) != 0)
return log_device_error_errno(event->dev, errno,
"Failed to create pipe for command '%s': %m", cmd);
r = strv_split_full(&argv, cmd, NULL, EXTRACT_UNQUOTE | EXTRACT_RELAX | EXTRACT_RETAIN_ESCAPE);
if (r < 0)
return log_device_error_errno(event->dev, r, "Failed to split command: %m");
if (isempty(argv[0]))
return log_device_error_errno(event->dev, SYNTHETIC_ERRNO(EINVAL),
"Invalid command '%s'", cmd);
/* allow programs in /usr/lib/udev/ to be called without the path */
if (!path_is_absolute(argv[0])) {
char *program;
program = path_join(UDEVLIBEXECDIR, argv[0]);
if (!program)
return log_oom();
free_and_replace(argv[0], program);
}
r = device_get_properties_strv(event->dev, &envp);
if (r < 0)
return log_device_error_errno(event->dev, r, "Failed to get device properties");
log_device_debug(event->dev, "Starting '%s'", cmd);
r = safe_fork_full("(spawn)",
(int[]) { -EBADF, outpipe[WRITE_END], errpipe[WRITE_END] },
NULL, 0,
FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_REARRANGE_STDIO|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE,
&pid);
if (r < 0)
return log_device_error_errno(event->dev, r,
"Failed to fork() to execute command '%s': %m", cmd);
if (r == 0) {
DEVICE_TRACE_POINT(spawn_exec, event->dev, cmd);
execve(argv[0], argv, envp);
_exit(EXIT_FAILURE);
}
/* parent closed child's ends of pipes */
outpipe[WRITE_END] = safe_close(outpipe[WRITE_END]);
errpipe[WRITE_END] = safe_close(errpipe[WRITE_END]);
spawn = (Spawn) {
.device = event->dev,
.cmd = cmd,
.pid = pid,
.accept_failure = accept_failure,
.timeout_warn_usec = udev_warn_timeout(timeout_usec),
.timeout_usec = timeout_usec,
.timeout_signal = timeout_signal,
.event_birth_usec = event->birth_usec,
.fd_stdout = outpipe[READ_END],
.fd_stderr = errpipe[READ_END],
.result = result,
.result_size = ressize,
};
r = spawn_wait(&spawn);
if (r < 0)
return log_device_error_errno(event->dev, r,
"Failed to wait for spawned command '%s': %m", cmd);
if (result)
result[spawn.result_len] = '\0';
if (ret_truncated)
*ret_truncated = spawn.truncated;
return r; /* 0 for success, and positive if the program failed */
}
void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal) {
const char *command;
void *val;
int r;
ORDERED_HASHMAP_FOREACH_KEY(val, command, event->run_list) {
UdevBuiltinCommand builtin_cmd = PTR_TO_UDEV_BUILTIN_CMD(val);
if (builtin_cmd != _UDEV_BUILTIN_INVALID) {
log_device_debug(event->dev, "Running built-in command \"%s\"", command);
r = udev_builtin_run(event, builtin_cmd, command, false);
if (r < 0)
log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command);
} else {
if (event->exec_delay_usec > 0) {
log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.",
command, FORMAT_TIMESPAN(event->exec_delay_usec, USEC_PER_SEC));
(void) usleep_safe(event->exec_delay_usec);
}
log_device_debug(event->dev, "Running command \"%s\"", command);
r = udev_event_spawn(event, timeout_usec, timeout_signal, false, command, NULL, 0, NULL);
if (r < 0)
log_device_warning_errno(event->dev, r, "Failed to execute '%s', ignoring: %m", command);
else if (r > 0) /* returned value is positive when program fails */
log_device_debug(event->dev, "Command \"%s\" returned %d (error), ignoring.", command, r);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include "macro.h"
#include "time-util.h"
#define READ_END 0
#define WRITE_END 1
typedef struct UdevEvent UdevEvent;
int udev_event_spawn(
UdevEvent *event,
usec_t timeout_usec,
int timeout_signal,
bool accept_failure,
const char *cmd,
char *result,
size_t ressize,
bool *ret_truncated);
void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal);
static inline usec_t udev_warn_timeout(usec_t timeout_usec) {
return DIV_ROUND_UP(timeout_usec, 3);
}
+35
View File
@@ -0,0 +1,35 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if HAVE_SYS_SDT_H
#define SDT_USE_VARIADIC
#include <sys/sdt.h>
#include "device-private.h"
#include "device-util.h"
#include "errno-util.h"
/* Each trace point can have different number of additional arguments. Note that when the macro is used only
* additional arguments are listed in the macro invocation!
*
* Default arguments for each trace point are as follows:
* - arg0 - action
* - arg1 - sysname
* - arg2 - syspath
* - arg3 - subsystem
*/
#define DEVICE_TRACE_POINT(name, dev, ...) \
do { \
PROTECT_ERRNO; \
const char *_n = NULL, *_p = NULL, *_s = NULL; \
sd_device *_d = (dev); \
sd_device_action_t _a = _SD_DEVICE_ACTION_INVALID; \
(void) sd_device_get_action(_d, &_a); \
(void) sd_device_get_sysname(_d, &_n); \
(void) sd_device_get_syspath(_d, &_p); \
(void) sd_device_get_subsystem(_d, &_s); \
STAP_PROBEV(udev, name, device_action_to_string(_a), _n, _p, _s __VA_OPT__(,) __VA_ARGS__);\
} while (false);
#else
#define DEVICE_TRACE_POINT(name, dev, ...) ((void) 0)
#endif
+352
View File
@@ -0,0 +1,352 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include "alloc-util.h"
#include "blockdev-util.h"
#include "common-signal.h"
#include "device-monitor-private.h"
#include "device-private.h"
#include "device-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "io-util.h"
#include "path-util.h"
#include "process-util.h"
#include "signal-util.h"
#include "string-util.h"
#include "udev-event.h"
#include "udev-spawn.h"
#include "udev-trace.h"
#include "udev-util.h"
#include "udev-watch.h"
#include "udev-worker.h"
void udev_worker_done(UdevWorker *worker) {
assert(worker);
sd_event_unref(worker->event);
sd_netlink_unref(worker->rtnl);
sd_device_monitor_unref(worker->monitor);
hashmap_free(worker->properties);
udev_rules_free(worker->rules);
safe_close(worker->pipe_fd);
}
int udev_get_whole_disk(sd_device *dev, sd_device **ret_device, const char **ret_devname) {
const char *val;
int r;
assert(dev);
if (device_for_action(dev, SD_DEVICE_REMOVE))
goto irrelevant;
r = sd_device_get_sysname(dev, &val);
if (r < 0)
return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
/* Exclude the following devices:
* For "dm-", see the comment added by e918a1b5a94f270186dca59156354acd2a596494.
* For "md", see the commit message of 2e5b17d01347d3c3118be2b8ad63d20415dbb1f0,
* but not sure the assumption is still valid even when partitions are created on the md
* devices, surprisingly which seems to be possible, see PR #22973.
* For "drbd", see the commit message of fee854ee8ccde0cd28e0f925dea18cce35f3993d. */
if (STARTSWITH_SET(val, "dm-", "md", "drbd"))
goto irrelevant;
r = block_device_get_whole_disk(dev, &dev);
if (IN_SET(r,
-ENOTBLK, /* The device is not a block device. */
-ENODEV /* The whole disk device was not found, it may already be removed. */))
goto irrelevant;
if (r < 0)
return log_device_debug_errno(dev, r, "Failed to get whole disk device: %m");
r = sd_device_get_devname(dev, &val);
if (r < 0)
return log_device_debug_errno(dev, r, "Failed to get devname: %m");
if (ret_device)
*ret_device = dev;
if (ret_devname)
*ret_devname = val;
return 1;
irrelevant:
if (ret_device)
*ret_device = NULL;
if (ret_devname)
*ret_devname = NULL;
return 0;
}
static int worker_lock_whole_disk(sd_device *dev, int *ret_fd) {
_cleanup_close_ int fd = -EBADF;
sd_device *dev_whole_disk;
const char *val;
int r;
assert(dev);
assert(ret_fd);
/* Take a shared lock on the device node; this establishes a concept of device "ownership" to
* serialize device access. External processes holding an exclusive lock will cause udev to skip the
* event handling; in the case udev acquired the lock, the external process can block until udev has
* finished its event handling. */
r = udev_get_whole_disk(dev, &dev_whole_disk, &val);
if (r < 0)
return r;
if (r == 0)
goto nolock;
fd = sd_device_open(dev_whole_disk, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
if (fd < 0) {
bool ignore = ERRNO_IS_DEVICE_ABSENT(fd);
log_device_debug_errno(dev, fd, "Failed to open '%s'%s: %m", val, ignore ? ", ignoring" : "");
if (!ignore)
return fd;
goto nolock;
}
if (flock(fd, LOCK_SH|LOCK_NB) < 0)
return log_device_debug_errno(dev, errno, "Failed to flock(%s): %m", val);
*ret_fd = TAKE_FD(fd);
return 1;
nolock:
*ret_fd = -EBADF;
return 0;
}
static int worker_mark_block_device_read_only(sd_device *dev) {
_cleanup_close_ int fd = -EBADF;
const char *val;
int state = 1, r;
assert(dev);
/* Do this only once, when the block device is new. If the device is later retriggered let's not
* toggle the bit again, so that people can boot up with full read-only mode and then unset the bit
* for specific devices only. */
if (!device_for_action(dev, SD_DEVICE_ADD))
return 0;
r = sd_device_get_subsystem(dev, &val);
if (r < 0)
return log_device_debug_errno(dev, r, "Failed to get subsystem: %m");
if (!streq(val, "block"))
return 0;
r = sd_device_get_sysname(dev, &val);
if (r < 0)
return log_device_debug_errno(dev, r, "Failed to get sysname: %m");
/* Exclude synthetic devices for now, this is supposed to be a safety feature to avoid modification
* of physical devices, and what sits on top of those doesn't really matter if we don't allow the
* underlying block devices to receive changes. */
if (STARTSWITH_SET(val, "dm-", "md", "drbd", "loop", "nbd", "zram"))
return 0;
fd = sd_device_open(dev, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
if (fd < 0)
return log_device_debug_errno(dev, fd, "Failed to open '%s', ignoring: %m", val);
if (ioctl(fd, BLKROSET, &state) < 0)
return log_device_warning_errno(dev, errno, "Failed to mark block device '%s' read-only: %m", val);
log_device_info(dev, "Successfully marked block device '%s' read-only.", val);
return 0;
}
static int worker_process_device(UdevWorker *worker, sd_device *dev) {
_cleanup_(udev_event_freep) UdevEvent *udev_event = NULL;
_cleanup_close_ int fd_lock = -EBADF;
int r;
assert(worker);
assert(dev);
log_device_uevent(dev, "Processing device");
udev_event = udev_event_new(dev, worker->exec_delay_usec, worker->rtnl, worker->log_level);
if (!udev_event)
return -ENOMEM;
/* If this is a block device and the device is locked currently via the BSD advisory locks,
* someone else is using it exclusively. We don't run our udev rules now to not interfere.
* Instead of processing the event, we requeue the event and will try again after a delay.
*
* The user-facing side of this: https://systemd.io/BLOCK_DEVICE_LOCKING */
r = worker_lock_whole_disk(dev, &fd_lock);
if (r == -EAGAIN)
return EVENT_RESULT_TRY_AGAIN;
if (r < 0)
return r;
if (worker->blockdev_read_only)
(void) worker_mark_block_device_read_only(dev);
/* apply rules, create node, symlinks */
r = udev_event_execute_rules(
udev_event,
worker->inotify_fd,
worker->timeout_usec,
worker->timeout_signal,
worker->properties,
worker->rules);
if (r < 0)
return r;
udev_event_execute_run(udev_event, worker->timeout_usec, worker->timeout_signal);
if (!worker->rtnl)
/* in case rtnl was initialized */
worker->rtnl = sd_netlink_ref(udev_event->rtnl);
if (udev_event->inotify_watch) {
r = udev_watch_begin(worker->inotify_fd, dev);
if (r < 0 && r != -ENOENT) /* The device may be already removed, ignore -ENOENT. */
log_device_warning_errno(dev, r, "Failed to add inotify watch, ignoring: %m");
}
log_device_uevent(dev, "Device processed");
return 0;
}
void udev_broadcast_result(sd_device_monitor *monitor, sd_device *dev, EventResult result) {
int r;
assert(dev);
/* On exit, manager->monitor is already NULL. */
if (!monitor)
return;
if (result != EVENT_RESULT_SUCCESS) {
(void) device_add_property(dev, "UDEV_WORKER_FAILED", "1");
switch (result) {
case EVENT_RESULT_NERRNO_MIN ... EVENT_RESULT_NERRNO_MAX: {
const char *str;
(void) device_add_propertyf(dev, "UDEV_WORKER_ERRNO", "%i", -result);
str = errno_to_name(result);
if (str)
(void) device_add_property(dev, "UDEV_WORKER_ERRNO_NAME", str);
break;
}
case EVENT_RESULT_EXIT_STATUS_BASE ... EVENT_RESULT_EXIT_STATUS_MAX:
(void) device_add_propertyf(dev, "UDEV_WORKER_EXIT_STATUS", "%i", result - EVENT_RESULT_EXIT_STATUS_BASE);
break;
case EVENT_RESULT_TRY_AGAIN:
assert_not_reached();
break;
case EVENT_RESULT_SIGNAL_BASE ... EVENT_RESULT_SIGNAL_MAX: {
const char *str;
(void) device_add_propertyf(dev, "UDEV_WORKER_SIGNAL", "%i", result - EVENT_RESULT_SIGNAL_BASE);
str = signal_to_string(result - EVENT_RESULT_SIGNAL_BASE);
if (str)
(void) device_add_property(dev, "UDEV_WORKER_SIGNAL_NAME", str);
break;
}
default:
log_device_warning(dev, "Unknown event result \"%i\", ignoring.", result);
}
}
r = device_monitor_send_device(monitor, NULL, dev);
if (r < 0)
log_device_warning_errno(dev, r,
"Failed to broadcast event to libudev listeners, ignoring: %m");
}
static int worker_send_result(UdevWorker *worker, EventResult result) {
assert(worker);
assert(worker->pipe_fd >= 0);
return loop_write(worker->pipe_fd, &result, sizeof(result), /* do_poll = */ false);
}
static int worker_device_monitor_handler(sd_device_monitor *monitor, sd_device *dev, void *userdata) {
UdevWorker *worker = ASSERT_PTR(userdata);
int r;
assert(dev);
r = worker_process_device(worker, dev);
if (r == EVENT_RESULT_TRY_AGAIN)
/* if we couldn't acquire the flock(), then requeue the event */
log_device_debug(dev, "Block device is currently locked, requeueing the event.");
else {
if (r < 0)
log_device_warning_errno(dev, r, "Failed to process device, ignoring: %m");
/* send processed event back to libudev listeners */
udev_broadcast_result(monitor, dev, r);
}
/* send udevd the result of the event execution */
r = worker_send_result(worker, r);
if (r < 0)
log_device_warning_errno(dev, r, "Failed to send signal to main daemon, ignoring: %m");
/* Reset the log level, as it might be changed by "OPTIONS=log_level=". */
log_set_max_level(worker->log_level);
return 1;
}
int udev_worker_main(UdevWorker *worker, sd_device *dev) {
int r;
assert(worker);
assert(worker->monitor);
assert(dev);
DEVICE_TRACE_POINT(worker_spawned, dev, getpid_cached());
assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, -1) >= 0);
/* Reset OOM score, we only protect the main daemon. */
r = set_oom_score_adjust(0);
if (r < 0)
log_debug_errno(r, "Failed to reset OOM score, ignoring: %m");
r = sd_event_new(&worker->event);
if (r < 0)
return log_error_errno(r, "Failed to allocate event loop: %m");
r = sd_event_add_signal(worker->event, NULL, SIGTERM, NULL, NULL);
if (r < 0)
return log_error_errno(r, "Failed to set SIGTERM event: %m");
r = sd_device_monitor_attach_event(worker->monitor, worker->event);
if (r < 0)
return log_error_errno(r, "Failed to attach event loop to device monitor: %m");
r = sd_device_monitor_start(worker->monitor, worker_device_monitor_handler, worker);
if (r < 0)
return log_error_errno(r, "Failed to start device monitor: %m");
/* Process first device */
(void) worker_device_monitor_handler(worker->monitor, dev, worker);
r = sd_event_loop(worker->event);
if (r < 0)
return log_error_errno(r, "Event loop failed: %m");
return 0;
}
+52
View File
@@ -0,0 +1,52 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
#include <stdbool.h>
#include "sd-device.h"
#include "sd-event.h"
#include "sd-netlink.h"
#include "errno-list.h"
#include "hashmap.h"
#include "time-util.h"
typedef struct UdevRules UdevRules;
typedef struct UdevWorker {
sd_event *event;
sd_netlink *rtnl;
sd_device_monitor *monitor;
Hashmap *properties;
UdevRules *rules;
int pipe_fd;
int inotify_fd; /* Do not close! */
usec_t exec_delay_usec;
usec_t timeout_usec;
int timeout_signal;
int log_level;
bool blockdev_read_only;
} UdevWorker;
/* passed from worker to main process */
typedef enum EventResult {
EVENT_RESULT_NERRNO_MIN = -ERRNO_MAX,
EVENT_RESULT_NERRNO_MAX = -1,
EVENT_RESULT_SUCCESS = 0,
EVENT_RESULT_EXIT_STATUS_BASE = 0,
EVENT_RESULT_EXIT_STATUS_MAX = 255,
EVENT_RESULT_TRY_AGAIN = 256, /* when the block device is locked by another process. */
EVENT_RESULT_SIGNAL_BASE = 257,
EVENT_RESULT_SIGNAL_MAX = EVENT_RESULT_SIGNAL_BASE + _NSIG,
_EVENT_RESULT_MAX,
_EVENT_RESULT_INVALID = -EINVAL,
} EventResult;
void udev_worker_done(UdevWorker *worker);
int udev_worker_main(UdevWorker *worker, sd_device *dev);
void udev_broadcast_result(sd_device_monitor *monitor, sd_device *dev, EventResult result);
int udev_get_whole_disk(sd_device *dev, sd_device **ret_device, const char **ret_devname);
+1
View File
@@ -21,6 +21,7 @@
#include "strxcpyx.h"
#include "udev-builtin.h"
#include "udev-event.h"
#include "udev-format.h"
#include "udevadm-util.h"
#include "udevadm.h"
+101 -1739
View File
File diff suppressed because it is too large Load Diff