]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/udev-util.c
oomd: move oomctl to bindir
[thirdparty/systemd.git] / src / shared / udev-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
b237a168 2
5953d8b9 3#include <ctype.h>
152d0efa 4#include <errno.h>
bee33d05 5#include <sys/inotify.h>
030a0d79 6#include <unistd.h>
b237a168 7
152d0efa 8#include "alloc-util.h"
393fcaf7 9#include "device-nodes.h"
a1130022 10#include "device-private.h"
f822c5d5 11#include "device-util.h"
686d13b9 12#include "env-file.h"
acfc2a1d 13#include "errno-util.h"
aea3253e 14#include "escape.h"
bee33d05 15#include "fd-util.h"
b237a168 16#include "log.h"
aea3253e 17#include "macro.h"
4b3ca79e 18#include "parse-util.h"
030a0d79 19#include "path-util.h"
e2099267 20#include "signal-util.h"
e1ecfef1 21#include "socket-util.h"
bc768f04 22#include "string-table.h"
b237a168 23#include "string-util.h"
1223227f 24#include "strxcpyx.h"
b237a168 25#include "udev-util.h"
aea3253e 26#include "utf8.h"
b237a168 27
bc768f04
ZJS
28static const char* const resolve_name_timing_table[_RESOLVE_NAME_TIMING_MAX] = {
29 [RESOLVE_NAME_NEVER] = "never",
30 [RESOLVE_NAME_LATE] = "late",
31 [RESOLVE_NAME_EARLY] = "early",
32};
33
34DEFINE_STRING_TABLE_LOOKUP(resolve_name_timing, ResolveNameTiming);
35
4b3ca79e
ZJS
36int udev_parse_config_full(
37 unsigned *ret_children_max,
38 usec_t *ret_exec_delay_usec,
a14e7af1 39 usec_t *ret_event_timeout_usec,
e2099267
MS
40 ResolveNameTiming *ret_resolve_name_timing,
41 int *ret_timeout_signal) {
4b3ca79e 42
e2099267 43 _cleanup_free_ char *log_val = NULL, *children_max = NULL, *exec_delay = NULL, *event_timeout = NULL, *resolve_names = NULL, *timeout_signal = NULL;
b237a168
ZJS
44 int r;
45
aa8fbc74 46 r = parse_env_file(NULL, "/etc/udev/udev.conf",
4b3ca79e
ZJS
47 "udev_log", &log_val,
48 "children_max", &children_max,
49 "exec_delay", &exec_delay,
9b2934cb 50 "event_timeout", &event_timeout,
e2099267
MS
51 "resolve_names", &resolve_names,
52 "timeout_signal", &timeout_signal);
4b3ca79e 53 if (r == -ENOENT)
b237a168
ZJS
54 return 0;
55 if (r < 0)
56 return r;
57
4b3ca79e
ZJS
58 if (log_val) {
59 const char *log;
60 size_t n;
61
62 /* unquote */
63 n = strlen(log_val);
64 if (n >= 2 &&
65 ((log_val[0] == '"' && log_val[n-1] == '"') ||
66 (log_val[0] == '\'' && log_val[n-1] == '\''))) {
67 log_val[n - 1] = '\0';
68 log = log_val + 1;
69 } else
70 log = log_val;
71
72 /* we set the udev log level here explicitly, this is supposed
73 * to regulate the code in libudev/ and udev/. */
3cc6b14a 74 r = log_set_max_level_from_string(log);
4b3ca79e 75 if (r < 0)
d7921114
ZJS
76 log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
77 "failed to set udev log level '%s', ignoring: %m", log);
4b3ca79e
ZJS
78 }
79
80 if (ret_children_max && children_max) {
81 r = safe_atou(children_max, ret_children_max);
82 if (r < 0)
d7921114 83 log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
e2099267 84 "failed to parse children_max=%s, ignoring: %m", children_max);
4b3ca79e
ZJS
85 }
86
87 if (ret_exec_delay_usec && exec_delay) {
88 r = parse_sec(exec_delay, ret_exec_delay_usec);
89 if (r < 0)
d7921114 90 log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
e2099267 91 "failed to parse exec_delay=%s, ignoring: %m", exec_delay);
4b3ca79e
ZJS
92 }
93
94 if (ret_event_timeout_usec && event_timeout) {
95 r = parse_sec(event_timeout, ret_event_timeout_usec);
96 if (r < 0)
d7921114 97 log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
e2099267 98 "failed to parse event_timeout=%s, ignoring: %m", event_timeout);
4b3ca79e 99 }
b237a168 100
a14e7af1
ZJS
101 if (ret_resolve_name_timing && resolve_names) {
102 ResolveNameTiming t;
103
104 t = resolve_name_timing_from_string(resolve_names);
105 if (t < 0)
d7921114 106 log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
e2099267 107 "failed to parse resolve_names=%s, ignoring.", resolve_names);
a14e7af1
ZJS
108 else
109 *ret_resolve_name_timing = t;
110 }
e2099267
MS
111
112 if (ret_timeout_signal && timeout_signal) {
113 r = signal_from_string(timeout_signal);
114 if (r < 0)
115 log_syntax(NULL, LOG_WARNING, "/etc/udev/udev.conf", 0, r,
116 "failed to parse timeout_signal=%s, ignoring: %m", timeout_signal);
117 else
118 *ret_timeout_signal = r;
119 }
a14e7af1 120
b237a168
ZJS
121 return 0;
122}
ed435031 123
030a0d79
LB
124/* Note that if -ENOENT is returned, it will be logged at debug level rather than error,
125 * because it's an expected, common occurrence that the caller will handle with a fallback */
126static int device_new_from_dev_path(const char *devlink, sd_device **ret_device) {
127 struct stat st;
128 int r;
129
130 assert(devlink);
131
fe79f107
ZJS
132 if (stat(devlink, &st) < 0)
133 return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
134 "Failed to stat() %s: %m", devlink);
030a0d79
LB
135
136 if (!S_ISBLK(st.st_mode))
fe79f107
ZJS
137 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK),
138 "%s does not point to a block device: %m", devlink);
030a0d79 139
930aa88f 140 r = sd_device_new_from_stat_rdev(ret_device, &st);
030a0d79
LB
141 if (r < 0)
142 return log_error_errno(r, "Failed to initialize device from %s: %m", devlink);
143
144 return 0;
145}
146
ed435031
ZJS
147struct DeviceMonitorData {
148 const char *sysname;
030a0d79 149 const char *devlink;
ed435031
ZJS
150 sd_device *device;
151};
152
ce5eef65
LB
153static void device_monitor_data_free(struct DeviceMonitorData *d) {
154 assert(d);
155
156 sd_device_unref(d->device);
157}
158
ed435031
ZJS
159static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) {
160 struct DeviceMonitorData *data = userdata;
161 const char *sysname;
162
163 assert(device);
164 assert(data);
030a0d79 165 assert(data->sysname || data->devlink);
ed435031
ZJS
166 assert(!data->device);
167
e13d96ca
LP
168 /* Ignore REMOVE events here. We are waiting for initialization after all, not de-initialization. We
169 * might see a REMOVE event from an earlier use of the device (devices by the same name are recycled
170 * by the kernel after all), which we should not get confused by. After all we cannot distinguish use
171 * cycles of the devices, as the udev queue is entirely asynchronous.
172 *
173 * If we see a REMOVE event here for the use cycle we actually care about then we won't notice of
174 * course, but that should be OK, given the timeout logic used on the wait loop: this will be noticed
175 * by means of -ETIMEDOUT. Thus we won't notice immediately, but eventually, and that should be
176 * sufficient for an error path that should regularly not happen.
177 *
178 * (And yes, we only need to special case REMOVE. It's the only "negative" event type, where a device
179 * ceases to exist. All other event types are "positive": the device exists and is registered in the
180 * udev database, thus whenever we see the event, we can consider it initialized.) */
a1130022 181 if (device_for_action(device, SD_DEVICE_REMOVE))
e13d96ca
LP
182 return 0;
183
030a0d79
LB
184 if (data->sysname && sd_device_get_sysname(device, &sysname) >= 0 && streq(sysname, data->sysname))
185 goto found;
186
187 if (data->devlink) {
188 const char *devlink;
189
190 FOREACH_DEVICE_DEVLINK(device, devlink)
191 if (path_equal(devlink, data->devlink))
192 goto found;
193
194 if (sd_device_get_devname(device, &devlink) >= 0 && path_equal(devlink, data->devlink))
195 goto found;
ed435031
ZJS
196 }
197
198 return 0;
030a0d79
LB
199
200found:
201 data->device = sd_device_ref(device);
202 return sd_event_exit(sd_device_monitor_get_event(monitor), 0);
ed435031
ZJS
203}
204
030a0d79
LB
205static int device_wait_for_initialization_internal(
206 sd_device *_device,
207 const char *devlink,
208 const char *subsystem,
9e3d9067 209 usec_t deadline,
030a0d79 210 sd_device **ret) {
9e3d9067 211
ed435031 212 _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL;
1b47436e 213 _cleanup_(sd_event_source_unrefp) sd_event_source *timeout_source = NULL;
ed435031 214 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
030a0d79
LB
215 /* Ensure that if !_device && devlink, device gets unrefd on errors since it will be new */
216 _cleanup_(sd_device_unrefp) sd_device *device = sd_device_ref(_device);
ce5eef65 217 _cleanup_(device_monitor_data_free) struct DeviceMonitorData data = {
030a0d79
LB
218 .devlink = devlink,
219 };
ed435031
ZJS
220 int r;
221
030a0d79 222 assert(device || (subsystem && devlink));
ed435031 223
030a0d79
LB
224 /* Devlink might already exist, if it does get the device to use the sysname filtering */
225 if (!device && devlink) {
226 r = device_new_from_dev_path(devlink, &device);
227 if (r < 0 && r != -ENOENT)
228 return r;
ed435031
ZJS
229 }
230
030a0d79
LB
231 if (device) {
232 if (sd_device_get_is_initialized(device) > 0) {
233 if (ret)
234 *ret = sd_device_ref(device);
235 return 0;
236 }
237 /* We need either the sysname or the devlink for filtering */
238 assert_se(sd_device_get_sysname(device, &data.sysname) >= 0 || devlink);
239 }
ed435031
ZJS
240
241 /* Wait until the device is initialized, so that we can get access to the ID_PATH property */
242
fc40bfa7 243 r = sd_event_new(&event);
ed435031
ZJS
244 if (r < 0)
245 return log_error_errno(r, "Failed to get default event: %m");
246
247 r = sd_device_monitor_new(&monitor);
248 if (r < 0)
249 return log_error_errno(r, "Failed to acquire monitor: %m");
250
030a0d79 251 if (device && !subsystem) {
f822c5d5
YW
252 r = sd_device_get_subsystem(device, &subsystem);
253 if (r < 0 && r != -ENOENT)
254 return log_device_error_errno(device, r, "Failed to get subsystem: %m");
255 }
256
257 if (subsystem) {
258 r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, subsystem, NULL);
259 if (r < 0)
260 return log_error_errno(r, "Failed to add %s subsystem match to monitor: %m", subsystem);
261 }
ed435031
ZJS
262
263 r = sd_device_monitor_attach_event(monitor, event);
264 if (r < 0)
265 return log_error_errno(r, "Failed to attach event to device monitor: %m");
266
267 r = sd_device_monitor_start(monitor, device_monitor_handler, &data);
268 if (r < 0)
269 return log_error_errno(r, "Failed to start device monitor: %m");
270
9e3d9067
LP
271 if (deadline != USEC_INFINITY) {
272 r = sd_event_add_time(
39cf0351 273 event, &timeout_source,
9e3d9067 274 CLOCK_MONOTONIC, deadline, 0,
bac0bfc1 275 NULL, INT_TO_PTR(-ETIMEDOUT));
1b47436e
YW
276 if (r < 0)
277 return log_error_errno(r, "Failed to add timeout event source: %m");
278 }
279
ed435031
ZJS
280 /* Check again, maybe things changed. Udev will re-read the db if the device wasn't initialized
281 * yet. */
030a0d79
LB
282 if (!device && devlink) {
283 r = device_new_from_dev_path(devlink, &device);
284 if (r < 0 && r != -ENOENT)
285 return r;
286 }
287 if (device && sd_device_get_is_initialized(device) > 0) {
ed435031
ZJS
288 if (ret)
289 *ret = sd_device_ref(device);
290 return 0;
291 }
292
293 r = sd_event_loop(event);
294 if (r < 0)
1b47436e 295 return log_error_errno(r, "Failed to wait for device to be initialized: %m");
ed435031
ZJS
296
297 if (ret)
298 *ret = TAKE_PTR(data.device);
299 return 0;
300}
90ba130f 301
9e3d9067
LP
302int device_wait_for_initialization(sd_device *device, const char *subsystem, usec_t deadline, sd_device **ret) {
303 return device_wait_for_initialization_internal(device, NULL, subsystem, deadline, ret);
030a0d79
LB
304}
305
9e3d9067
LP
306int device_wait_for_devlink(const char *devlink, const char *subsystem, usec_t deadline, sd_device **ret) {
307 return device_wait_for_initialization_internal(NULL, devlink, subsystem, deadline, ret);
030a0d79
LB
308}
309
90ba130f
YW
310int device_is_renaming(sd_device *dev) {
311 int r;
312
313 assert(dev);
314
315 r = sd_device_get_property_value(dev, "ID_RENAMING", NULL);
b9daaedb
LP
316 if (r == -ENOENT)
317 return false;
318 if (r < 0)
90ba130f
YW
319 return r;
320
b9daaedb 321 return true;
90ba130f 322}
a707c65b 323
a1130022
LP
324bool device_for_action(sd_device *dev, sd_device_action_t a) {
325 sd_device_action_t b;
a707c65b
YW
326
327 assert(dev);
328
a1130022 329 if (a < 0)
a707c65b
YW
330 return false;
331
a1130022
LP
332 if (sd_device_get_action(dev, &b) < 0)
333 return false;
334
335 return a == b;
a707c65b 336}
aea3253e 337
b2d9e58f 338void log_device_uevent(sd_device *device, const char *str) {
a1130022 339 sd_device_action_t action = _SD_DEVICE_ACTION_INVALID;
b2d9e58f
YW
340 uint64_t seqnum = 0;
341
342 if (!DEBUG_LOGGING)
343 return;
344
a1130022
LP
345 (void) sd_device_get_seqnum(device, &seqnum);
346 (void) sd_device_get_action(device, &action);
b2d9e58f
YW
347 log_device_debug(device, "%s%s(SEQNUM=%"PRIu64", ACTION=%s)",
348 strempty(str), isempty(str) ? "" : " ",
349 seqnum, strna(device_action_to_string(action)));
350}
351
aea3253e
YLY
352int udev_rule_parse_value(char *str, char **ret_value, char **ret_endpos) {
353 char *i, *j;
aea3253e
YLY
354 bool is_escaped;
355
356 /* value must be double quotated */
357 is_escaped = str[0] == 'e';
358 str += is_escaped;
359 if (str[0] != '"')
360 return -EINVAL;
361 str++;
362
363 if (!is_escaped) {
364 /* unescape double quotation '\"'->'"' */
365 for (i = j = str; *i != '"'; i++, j++) {
366 if (*i == '\0')
367 return -EINVAL;
368 if (i[0] == '\\' && i[1] == '"')
369 i++;
370 *j = *i;
371 }
372 j[0] = '\0';
373 } else {
374 _cleanup_free_ char *unescaped = NULL;
e437538f 375 ssize_t l;
aea3253e
YLY
376
377 /* find the end position of value */
378 for (i = str; *i != '"'; i++) {
379 if (i[0] == '\\')
380 i++;
381 if (*i == '\0')
382 return -EINVAL;
383 }
384 i[0] = '\0';
385
e437538f
ZJS
386 l = cunescape_length(str, i - str, 0, &unescaped);
387 if (l < 0)
388 return l;
389
390 assert(l <= i - str);
391 memcpy(str, unescaped, l + 1);
aea3253e
YLY
392 }
393
394 *ret_value = str;
395 *ret_endpos = i + 1;
396 return 0;
397}
5953d8b9
YW
398
399size_t udev_replace_whitespace(const char *str, char *to, size_t len) {
400 bool is_space = false;
401 size_t i, j;
402
403 assert(str);
404 assert(to);
405
406 /* Copy from 'str' to 'to', while removing all leading and trailing whitespace, and replacing
407 * each run of consecutive whitespace with a single underscore. The chars from 'str' are copied
408 * up to the \0 at the end of the string, or at most 'len' chars. This appends \0 to 'to', at
409 * the end of the copied characters.
410 *
411 * If 'len' chars are copied into 'to', the final \0 is placed at len+1 (i.e. 'to[len] = \0'),
412 * so the 'to' buffer must have at least len+1 chars available.
413 *
414 * Note this may be called with 'str' == 'to', i.e. to replace whitespace in-place in a buffer.
415 * This function can handle that situation.
416 *
417 * Note that only 'len' characters are read from 'str'. */
418
419 i = strspn(str, WHITESPACE);
420
421 for (j = 0; j < len && i < len && str[i] != '\0'; i++) {
422 if (isspace(str[i])) {
423 is_space = true;
424 continue;
425 }
426
427 if (is_space) {
428 if (j + 1 >= len)
429 break;
430
431 to[j++] = '_';
432 is_space = false;
433 }
434 to[j++] = str[i];
435 }
436
437 to[j] = '\0';
438 return j;
439}
393fcaf7 440
e1ecfef1
YW
441size_t udev_replace_ifname(char *str) {
442 size_t replaced = 0;
443
444 assert(str);
445
446 /* See ifname_valid_full(). */
447
448 for (char *p = str; *p != '\0'; p++)
449 if (!ifname_valid_char(*p)) {
450 *p = '_';
451 replaced++;
452 }
453
454 return replaced;
455}
456
393fcaf7
YW
457size_t udev_replace_chars(char *str, const char *allow) {
458 size_t i = 0, replaced = 0;
459
460 assert(str);
461
462 /* allow chars in allow list, plain ascii, hex-escaping and valid utf8. */
463
464 while (str[i] != '\0') {
465 int len;
466
467 if (allow_listed_char_for_devnode(str[i], allow)) {
468 i++;
469 continue;
470 }
471
472 /* accept hex encoding */
473 if (str[i] == '\\' && str[i+1] == 'x') {
474 i += 2;
475 continue;
476 }
477
478 /* accept valid utf8 */
f5fbe71d 479 len = utf8_encoded_valid_unichar(str + i, SIZE_MAX);
393fcaf7
YW
480 if (len > 1) {
481 i += len;
482 continue;
483 }
484
485 /* if space is allowed, replace whitespace with ordinary space */
486 if (isspace(str[i]) && allow && strchr(allow, ' ')) {
487 str[i] = ' ';
488 i++;
489 replaced++;
490 continue;
491 }
492
493 /* everything else is replaced with '_' */
494 str[i] = '_';
495 i++;
496 replaced++;
497 }
498 return replaced;
499}
1223227f
YW
500
501int udev_resolve_subsys_kernel(const char *string, char *result, size_t maxsize, bool read_value) {
502 _cleanup_(sd_device_unrefp) sd_device *dev = NULL;
503 _cleanup_free_ char *temp = NULL;
504 char *subsys, *sysname, *attr;
505 const char *val;
506 int r;
507
508 assert(string);
509 assert(result);
510
511 /* handle "[<SUBSYSTEM>/<KERNEL>]<attribute>" format */
512
513 if (string[0] != '[')
514 return -EINVAL;
515
516 temp = strdup(string);
517 if (!temp)
518 return -ENOMEM;
519
520 subsys = &temp[1];
521
522 sysname = strchr(subsys, '/');
523 if (!sysname)
524 return -EINVAL;
525 sysname[0] = '\0';
526 sysname = &sysname[1];
527
528 attr = strchr(sysname, ']');
529 if (!attr)
530 return -EINVAL;
531 attr[0] = '\0';
532 attr = &attr[1];
533 if (attr[0] == '/')
534 attr = &attr[1];
535 if (attr[0] == '\0')
536 attr = NULL;
537
538 if (read_value && !attr)
539 return -EINVAL;
540
541 r = sd_device_new_from_subsystem_sysname(&dev, subsys, sysname);
542 if (r < 0)
543 return r;
544
545 if (read_value) {
546 r = sd_device_get_sysattr_value(dev, attr, &val);
acfc2a1d 547 if (r < 0 && !ERRNO_IS_PRIVILEGE(r) && r != -ENOENT)
1223227f 548 return r;
acfc2a1d 549 if (r >= 0)
1223227f 550 strscpy(result, maxsize, val);
acfc2a1d
YW
551 else
552 result[0] = '\0';
1223227f
YW
553 log_debug("value '[%s/%s]%s' is '%s'", subsys, sysname, attr, result);
554 } else {
555 r = sd_device_get_syspath(dev, &val);
556 if (r < 0)
557 return r;
558
559 strscpyl(result, maxsize, val, attr ? "/" : NULL, attr ?: NULL, NULL);
560 log_debug("path '[%s/%s]%s' is '%s'", subsys, sysname, strempty(attr), result);
561 }
562 return 0;
563}
bee33d05
YW
564
565int udev_queue_is_empty(void) {
566 return access("/run/udev/queue", F_OK) < 0 ?
567 (errno == ENOENT ? true : -errno) : false;
568}
569
570int udev_queue_init(void) {
571 _cleanup_close_ int fd = -1;
572
573 fd = inotify_init1(IN_CLOEXEC);
574 if (fd < 0)
575 return -errno;
576
577 if (inotify_add_watch(fd, "/run/udev" , IN_DELETE) < 0)
578 return -errno;
579
580 return TAKE_FD(fd);
581}