]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udev-event.c
tree-wide: introduce PIPE_EBADF macro
[thirdparty/systemd.git] / src / udev / udev-event.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <net/if.h>
7 #include <stddef.h>
8 #include <stdlib.h>
9 #include <sys/wait.h>
10 #include <unistd.h>
11
12 #include "sd-event.h"
13
14 #include "alloc-util.h"
15 #include "device-private.h"
16 #include "device-util.h"
17 #include "fd-util.h"
18 #include "fs-util.h"
19 #include "format-util.h"
20 #include "netif-naming-scheme.h"
21 #include "netlink-util.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
25 #include "rlimit-util.h"
26 #include "signal-util.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "strv.h"
30 #include "strxcpyx.h"
31 #include "udev-builtin.h"
32 #include "udev-event.h"
33 #include "udev-node.h"
34 #include "udev-util.h"
35 #include "udev-watch.h"
36 #include "user-util.h"
37
38 typedef struct Spawn {
39 sd_device *device;
40 const char *cmd;
41 pid_t pid;
42 usec_t timeout_warn_usec;
43 usec_t timeout_usec;
44 int timeout_signal;
45 usec_t event_birth_usec;
46 bool accept_failure;
47 int fd_stdout;
48 int fd_stderr;
49 char *result;
50 size_t result_size;
51 size_t result_len;
52 bool truncated;
53 } Spawn;
54
55 UdevEvent *udev_event_new(sd_device *dev, usec_t exec_delay_usec, sd_netlink *rtnl, int log_level) {
56 UdevEvent *event;
57
58 assert(dev);
59
60 event = new(UdevEvent, 1);
61 if (!event)
62 return NULL;
63
64 *event = (UdevEvent) {
65 .dev = sd_device_ref(dev),
66 .birth_usec = now(CLOCK_MONOTONIC),
67 .exec_delay_usec = exec_delay_usec,
68 .rtnl = sd_netlink_ref(rtnl),
69 .uid = UID_INVALID,
70 .gid = GID_INVALID,
71 .mode = MODE_INVALID,
72 .log_level_was_debug = log_level == LOG_DEBUG,
73 .default_log_level = log_level,
74 };
75
76 return event;
77 }
78
79 UdevEvent *udev_event_free(UdevEvent *event) {
80 if (!event)
81 return NULL;
82
83 sd_device_unref(event->dev);
84 sd_device_unref(event->dev_db_clone);
85 sd_netlink_unref(event->rtnl);
86 ordered_hashmap_free_free_key(event->run_list);
87 ordered_hashmap_free_free_free(event->seclabel_list);
88 free(event->program_result);
89 free(event->name);
90
91 return mfree(event);
92 }
93
94 typedef enum {
95 FORMAT_SUBST_DEVNODE,
96 FORMAT_SUBST_ATTR,
97 FORMAT_SUBST_ENV,
98 FORMAT_SUBST_KERNEL,
99 FORMAT_SUBST_KERNEL_NUMBER,
100 FORMAT_SUBST_DRIVER,
101 FORMAT_SUBST_DEVPATH,
102 FORMAT_SUBST_ID,
103 FORMAT_SUBST_MAJOR,
104 FORMAT_SUBST_MINOR,
105 FORMAT_SUBST_RESULT,
106 FORMAT_SUBST_PARENT,
107 FORMAT_SUBST_NAME,
108 FORMAT_SUBST_LINKS,
109 FORMAT_SUBST_ROOT,
110 FORMAT_SUBST_SYS,
111 _FORMAT_SUBST_TYPE_MAX,
112 _FORMAT_SUBST_TYPE_INVALID = -EINVAL,
113 } FormatSubstitutionType;
114
115 struct subst_map_entry {
116 const char *name;
117 const char fmt;
118 FormatSubstitutionType type;
119 };
120
121 static const struct subst_map_entry map[] = {
122 { .name = "devnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE },
123 { .name = "tempnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE }, /* deprecated */
124 { .name = "attr", .fmt = 's', .type = FORMAT_SUBST_ATTR },
125 { .name = "sysfs", .fmt = 's', .type = FORMAT_SUBST_ATTR }, /* deprecated */
126 { .name = "env", .fmt = 'E', .type = FORMAT_SUBST_ENV },
127 { .name = "kernel", .fmt = 'k', .type = FORMAT_SUBST_KERNEL },
128 { .name = "number", .fmt = 'n', .type = FORMAT_SUBST_KERNEL_NUMBER },
129 { .name = "driver", .fmt = 'd', .type = FORMAT_SUBST_DRIVER },
130 { .name = "devpath", .fmt = 'p', .type = FORMAT_SUBST_DEVPATH },
131 { .name = "id", .fmt = 'b', .type = FORMAT_SUBST_ID },
132 { .name = "major", .fmt = 'M', .type = FORMAT_SUBST_MAJOR },
133 { .name = "minor", .fmt = 'm', .type = FORMAT_SUBST_MINOR },
134 { .name = "result", .fmt = 'c', .type = FORMAT_SUBST_RESULT },
135 { .name = "parent", .fmt = 'P', .type = FORMAT_SUBST_PARENT },
136 { .name = "name", .fmt = 'D', .type = FORMAT_SUBST_NAME },
137 { .name = "links", .fmt = 'L', .type = FORMAT_SUBST_LINKS },
138 { .name = "root", .fmt = 'r', .type = FORMAT_SUBST_ROOT },
139 { .name = "sys", .fmt = 'S', .type = FORMAT_SUBST_SYS },
140 };
141
142 static const char *format_type_to_string(FormatSubstitutionType t) {
143 for (size_t i = 0; i < ELEMENTSOF(map); i++)
144 if (map[i].type == t)
145 return map[i].name;
146 return NULL;
147 }
148
149 static char format_type_to_char(FormatSubstitutionType t) {
150 for (size_t i = 0; i < ELEMENTSOF(map); i++)
151 if (map[i].type == t)
152 return map[i].fmt;
153 return '\0';
154 }
155
156 static int get_subst_type(const char **str, bool strict, FormatSubstitutionType *ret_type, char ret_attr[static UDEV_PATH_SIZE]) {
157 const char *p = *str, *q = NULL;
158 size_t i;
159
160 assert(str);
161 assert(*str);
162 assert(ret_type);
163 assert(ret_attr);
164
165 if (*p == '$') {
166 p++;
167 if (*p == '$') {
168 *str = p;
169 return 0;
170 }
171 for (i = 0; i < ELEMENTSOF(map); i++)
172 if ((q = startswith(p, map[i].name)))
173 break;
174 } else if (*p == '%') {
175 p++;
176 if (*p == '%') {
177 *str = p;
178 return 0;
179 }
180
181 for (i = 0; i < ELEMENTSOF(map); i++)
182 if (*p == map[i].fmt) {
183 q = p + 1;
184 break;
185 }
186 } else
187 return 0;
188 if (!q)
189 /* When 'strict' flag is set, then '$' and '%' must be escaped. */
190 return strict ? -EINVAL : 0;
191
192 if (*q == '{') {
193 const char *start, *end;
194 size_t len;
195
196 start = q + 1;
197 end = strchr(start, '}');
198 if (!end)
199 return -EINVAL;
200
201 len = end - start;
202 if (len == 0 || len >= UDEV_PATH_SIZE)
203 return -EINVAL;
204
205 strnscpy(ret_attr, UDEV_PATH_SIZE, start, len);
206 q = end + 1;
207 } else
208 *ret_attr = '\0';
209
210 *str = q;
211 *ret_type = map[i].type;
212 return 1;
213 }
214
215 static int safe_atou_optional_plus(const char *s, unsigned *ret) {
216 const char *p;
217 int r;
218
219 assert(s);
220 assert(ret);
221
222 /* Returns 1 if plus, 0 if no plus, negative on error */
223
224 p = endswith(s, "+");
225 if (p)
226 s = strndupa_safe(s, p - s);
227
228 r = safe_atou(s, ret);
229 if (r < 0)
230 return r;
231
232 return !!p;
233 }
234
235 static ssize_t udev_event_subst_format(
236 UdevEvent *event,
237 FormatSubstitutionType type,
238 const char *attr,
239 char *dest,
240 size_t l,
241 bool *ret_truncated) {
242
243 sd_device *parent, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
244 const char *val = NULL;
245 bool truncated = false;
246 char *s = dest;
247 int r;
248
249 switch (type) {
250 case FORMAT_SUBST_DEVPATH:
251 r = sd_device_get_devpath(dev, &val);
252 if (r < 0)
253 return r;
254 strpcpy_full(&s, l, val, &truncated);
255 break;
256 case FORMAT_SUBST_KERNEL:
257 r = sd_device_get_sysname(dev, &val);
258 if (r < 0)
259 return r;
260 strpcpy_full(&s, l, val, &truncated);
261 break;
262 case FORMAT_SUBST_KERNEL_NUMBER:
263 r = sd_device_get_sysnum(dev, &val);
264 if (r == -ENOENT)
265 goto null_terminate;
266 if (r < 0)
267 return r;
268 strpcpy_full(&s, l, val, &truncated);
269 break;
270 case FORMAT_SUBST_ID:
271 if (!event->dev_parent)
272 goto null_terminate;
273 r = sd_device_get_sysname(event->dev_parent, &val);
274 if (r < 0)
275 return r;
276 strpcpy_full(&s, l, val, &truncated);
277 break;
278 case FORMAT_SUBST_DRIVER:
279 if (!event->dev_parent)
280 goto null_terminate;
281 r = sd_device_get_driver(event->dev_parent, &val);
282 if (r == -ENOENT)
283 goto null_terminate;
284 if (r < 0)
285 return r;
286 strpcpy_full(&s, l, val, &truncated);
287 break;
288 case FORMAT_SUBST_MAJOR:
289 case FORMAT_SUBST_MINOR: {
290 dev_t devnum;
291
292 r = sd_device_get_devnum(dev, &devnum);
293 if (r < 0 && r != -ENOENT)
294 return r;
295 strpcpyf_full(&s, l, &truncated, "%u", r < 0 ? 0 : type == FORMAT_SUBST_MAJOR ? major(devnum) : minor(devnum));
296 break;
297 }
298 case FORMAT_SUBST_RESULT: {
299 unsigned index = 0; /* 0 means whole string */
300 bool has_plus;
301
302 if (!event->program_result)
303 goto null_terminate;
304
305 if (!isempty(attr)) {
306 r = safe_atou_optional_plus(attr, &index);
307 if (r < 0)
308 return r;
309
310 has_plus = r;
311 }
312
313 if (index == 0)
314 strpcpy_full(&s, l, event->program_result, &truncated);
315 else {
316 const char *start, *p;
317 unsigned i;
318
319 p = skip_leading_chars(event->program_result, NULL);
320
321 for (i = 1; i < index; i++) {
322 while (*p && !strchr(WHITESPACE, *p))
323 p++;
324 p = skip_leading_chars(p, NULL);
325 if (*p == '\0')
326 break;
327 }
328 if (i != index) {
329 log_device_debug(dev, "requested part of result string not found");
330 goto null_terminate;
331 }
332
333 start = p;
334 /* %c{2+} copies the whole string from the second part on */
335 if (has_plus)
336 strpcpy_full(&s, l, start, &truncated);
337 else {
338 while (*p && !strchr(WHITESPACE, *p))
339 p++;
340 strnpcpy_full(&s, l, start, p - start, &truncated);
341 }
342 }
343 break;
344 }
345 case FORMAT_SUBST_ATTR: {
346 char vbuf[UDEV_NAME_SIZE];
347 int count;
348 bool t;
349
350 if (isempty(attr))
351 return -EINVAL;
352
353 /* try to read the value specified by "[dmi/id]product_name" */
354 if (udev_resolve_subsys_kernel(attr, vbuf, sizeof(vbuf), true) == 0)
355 val = vbuf;
356
357 /* try to read the attribute the device */
358 if (!val)
359 (void) sd_device_get_sysattr_value(dev, attr, &val);
360
361 /* try to read the attribute of the parent device, other matches have selected */
362 if (!val && event->dev_parent && event->dev_parent != dev)
363 (void) sd_device_get_sysattr_value(event->dev_parent, attr, &val);
364
365 if (!val)
366 goto null_terminate;
367
368 /* strip trailing whitespace, and replace unwanted characters */
369 if (val != vbuf)
370 strscpy_full(vbuf, sizeof(vbuf), val, &truncated);
371 delete_trailing_chars(vbuf, NULL);
372 count = udev_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
373 if (count > 0)
374 log_device_debug(dev, "%i character(s) replaced", count);
375 strpcpy_full(&s, l, vbuf, &t);
376 truncated = truncated || t;
377 break;
378 }
379 case FORMAT_SUBST_PARENT:
380 r = sd_device_get_parent(dev, &parent);
381 if (r == -ENOENT)
382 goto null_terminate;
383 if (r < 0)
384 return r;
385 r = sd_device_get_devname(parent, &val);
386 if (r == -ENOENT)
387 goto null_terminate;
388 if (r < 0)
389 return r;
390 strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
391 break;
392 case FORMAT_SUBST_DEVNODE:
393 r = sd_device_get_devname(dev, &val);
394 if (r == -ENOENT)
395 goto null_terminate;
396 if (r < 0)
397 return r;
398 strpcpy_full(&s, l, val, &truncated);
399 break;
400 case FORMAT_SUBST_NAME:
401 if (event->name)
402 strpcpy_full(&s, l, event->name, &truncated);
403 else if (sd_device_get_devname(dev, &val) >= 0)
404 strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
405 else {
406 r = sd_device_get_sysname(dev, &val);
407 if (r < 0)
408 return r;
409 strpcpy_full(&s, l, val, &truncated);
410 }
411 break;
412 case FORMAT_SUBST_LINKS:
413 FOREACH_DEVICE_DEVLINK(dev, val) {
414 if (s == dest)
415 strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
416 else
417 strpcpyl_full(&s, l, &truncated, " ", val + STRLEN("/dev/"), NULL);
418 if (truncated)
419 break;
420 }
421 if (s == dest)
422 goto null_terminate;
423 break;
424 case FORMAT_SUBST_ROOT:
425 strpcpy_full(&s, l, "/dev", &truncated);
426 break;
427 case FORMAT_SUBST_SYS:
428 strpcpy_full(&s, l, "/sys", &truncated);
429 break;
430 case FORMAT_SUBST_ENV:
431 if (isempty(attr))
432 return -EINVAL;
433 r = sd_device_get_property_value(dev, attr, &val);
434 if (r == -ENOENT)
435 goto null_terminate;
436 if (r < 0)
437 return r;
438 strpcpy_full(&s, l, val, &truncated);
439 break;
440 default:
441 assert_not_reached();
442 }
443
444 if (ret_truncated)
445 *ret_truncated = truncated;
446
447 return s - dest;
448
449 null_terminate:
450 if (ret_truncated)
451 *ret_truncated = truncated;
452
453 *s = '\0';
454 return 0;
455 }
456
457 size_t udev_event_apply_format(
458 UdevEvent *event,
459 const char *src,
460 char *dest,
461 size_t size,
462 bool replace_whitespace,
463 bool *ret_truncated) {
464
465 bool truncated = false;
466 const char *s = ASSERT_PTR(src);
467 int r;
468
469 assert(event);
470 assert(event->dev);
471 assert(dest);
472 assert(size > 0);
473
474 while (*s) {
475 FormatSubstitutionType type;
476 char attr[UDEV_PATH_SIZE];
477 ssize_t subst_len;
478 bool t;
479
480 r = get_subst_type(&s, false, &type, attr);
481 if (r < 0) {
482 log_device_warning_errno(event->dev, r, "Invalid format string, ignoring: %s", src);
483 break;
484 } else if (r == 0) {
485 if (size < 2) {
486 /* need space for this char and the terminating NUL */
487 truncated = true;
488 break;
489 }
490 *dest++ = *s++;
491 size--;
492 continue;
493 }
494
495 subst_len = udev_event_subst_format(event, type, attr, dest, size, &t);
496 if (subst_len < 0) {
497 log_device_warning_errno(event->dev, subst_len,
498 "Failed to substitute variable '$%s' or apply format '%%%c', ignoring: %m",
499 format_type_to_string(type), format_type_to_char(type));
500 break;
501 }
502
503 truncated = truncated || t;
504
505 /* FORMAT_SUBST_RESULT handles spaces itself */
506 if (replace_whitespace && type != FORMAT_SUBST_RESULT)
507 /* udev_replace_whitespace can replace in-place,
508 * and does nothing if subst_len == 0 */
509 subst_len = udev_replace_whitespace(dest, dest, subst_len);
510
511 dest += subst_len;
512 size -= subst_len;
513 }
514
515 assert(size >= 1);
516
517 if (ret_truncated)
518 *ret_truncated = truncated;
519
520 *dest = '\0';
521 return size;
522 }
523
524 int udev_check_format(const char *value, size_t *offset, const char **hint) {
525 FormatSubstitutionType type;
526 const char *s = value;
527 char attr[UDEV_PATH_SIZE];
528 int r;
529
530 while (*s) {
531 r = get_subst_type(&s, true, &type, attr);
532 if (r < 0) {
533 if (offset)
534 *offset = s - value;
535 if (hint)
536 *hint = "invalid substitution type";
537 return r;
538 } else if (r == 0) {
539 s++;
540 continue;
541 }
542
543 if (IN_SET(type, FORMAT_SUBST_ATTR, FORMAT_SUBST_ENV) && isempty(attr)) {
544 if (offset)
545 *offset = s - value;
546 if (hint)
547 *hint = "attribute value missing";
548 return -EINVAL;
549 }
550
551 if (type == FORMAT_SUBST_RESULT && !isempty(attr)) {
552 unsigned i;
553
554 r = safe_atou_optional_plus(attr, &i);
555 if (r < 0) {
556 if (offset)
557 *offset = s - value;
558 if (hint)
559 *hint = "attribute value not a valid number";
560 return r;
561 }
562 }
563 }
564
565 return 0;
566 }
567
568 static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
569 Spawn *spawn = ASSERT_PTR(userdata);
570 char buf[4096], *p;
571 size_t size;
572 ssize_t l;
573 int r;
574
575 assert(fd == spawn->fd_stdout || fd == spawn->fd_stderr);
576 assert(!spawn->result || spawn->result_len < spawn->result_size);
577
578 if (fd == spawn->fd_stdout && spawn->result) {
579 p = spawn->result + spawn->result_len;
580 size = spawn->result_size - spawn->result_len;
581 } else {
582 p = buf;
583 size = sizeof(buf);
584 }
585
586 l = read(fd, p, size - (p == buf));
587 if (l < 0) {
588 if (errno == EAGAIN)
589 goto reenable;
590
591 log_device_error_errno(spawn->device, errno,
592 "Failed to read stdout of '%s': %m", spawn->cmd);
593
594 return 0;
595 }
596
597 if ((size_t) l == size) {
598 log_device_warning(spawn->device, "Truncating stdout of '%s' up to %zu byte.",
599 spawn->cmd, spawn->result_size);
600 l--;
601 spawn->truncated = true;
602 }
603
604 p[l] = '\0';
605 if (fd == spawn->fd_stdout && spawn->result)
606 spawn->result_len += l;
607
608 /* Log output only if we watch stderr. */
609 if (l > 0 && spawn->fd_stderr >= 0) {
610 _cleanup_strv_free_ char **v = NULL;
611
612 r = strv_split_newlines_full(&v, p, EXTRACT_RETAIN_ESCAPE);
613 if (r < 0)
614 log_device_debug(spawn->device,
615 "Failed to split output from '%s'(%s), ignoring: %m",
616 spawn->cmd, fd == spawn->fd_stdout ? "out" : "err");
617
618 STRV_FOREACH(q, v)
619 log_device_debug(spawn->device, "'%s'(%s) '%s'", spawn->cmd,
620 fd == spawn->fd_stdout ? "out" : "err", *q);
621 }
622
623 if (l == 0 || spawn->truncated)
624 return 0;
625
626 reenable:
627 /* Re-enable the event source if we did not encounter EOF */
628
629 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
630 if (r < 0)
631 log_device_error_errno(spawn->device, r,
632 "Failed to reactivate IO source of '%s'", spawn->cmd);
633 return 0;
634 }
635
636 static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
637 Spawn *spawn = ASSERT_PTR(userdata);
638
639 DEVICE_TRACE_POINT(spawn_timeout, spawn->device, spawn->cmd);
640
641 kill_and_sigcont(spawn->pid, spawn->timeout_signal);
642
643 log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing",
644 spawn->cmd, spawn->pid,
645 FORMAT_TIMESPAN(spawn->timeout_usec, USEC_PER_SEC));
646
647 return 1;
648 }
649
650 static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
651 Spawn *spawn = ASSERT_PTR(userdata);
652
653 log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete",
654 spawn->cmd, spawn->pid,
655 FORMAT_TIMESPAN(spawn->timeout_warn_usec, USEC_PER_SEC));
656
657 return 1;
658 }
659
660 static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
661 Spawn *spawn = ASSERT_PTR(userdata);
662 int ret = -EIO;
663
664 switch (si->si_code) {
665 case CLD_EXITED:
666 if (si->si_status == 0)
667 log_device_debug(spawn->device, "Process '%s' succeeded.", spawn->cmd);
668 else
669 log_device_full(spawn->device, spawn->accept_failure ? LOG_DEBUG : LOG_WARNING,
670 "Process '%s' failed with exit code %i.", spawn->cmd, si->si_status);
671 ret = si->si_status;
672 break;
673 case CLD_KILLED:
674 case CLD_DUMPED:
675 log_device_error(spawn->device, "Process '%s' terminated by signal %s.", spawn->cmd, signal_to_string(si->si_status));
676 break;
677 default:
678 log_device_error(spawn->device, "Process '%s' failed due to unknown reason.", spawn->cmd);
679 }
680
681 DEVICE_TRACE_POINT(spawn_exit, spawn->device, spawn->cmd);
682
683 sd_event_exit(sd_event_source_get_event(s), ret);
684 return 1;
685 }
686
687 static int spawn_wait(Spawn *spawn) {
688 _cleanup_(sd_event_unrefp) sd_event *e = NULL;
689 _cleanup_(sd_event_source_disable_unrefp) sd_event_source *sigchld_source = NULL;
690 _cleanup_(sd_event_source_disable_unrefp) sd_event_source *stdout_source = NULL;
691 _cleanup_(sd_event_source_disable_unrefp) sd_event_source *stderr_source = NULL;
692 int r;
693
694 assert(spawn);
695
696 r = sd_event_new(&e);
697 if (r < 0)
698 return log_device_debug_errno(spawn->device, r, "Failed to allocate sd-event object: %m");
699
700 if (spawn->timeout_usec > 0) {
701 usec_t usec, age_usec;
702
703 usec = now(CLOCK_MONOTONIC);
704 age_usec = usec - spawn->event_birth_usec;
705 if (age_usec < spawn->timeout_usec) {
706 if (spawn->timeout_warn_usec > 0 &&
707 spawn->timeout_warn_usec < spawn->timeout_usec &&
708 spawn->timeout_warn_usec > age_usec) {
709 spawn->timeout_warn_usec -= age_usec;
710
711 r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
712 usec + spawn->timeout_warn_usec, USEC_PER_SEC,
713 on_spawn_timeout_warning, spawn);
714 if (r < 0)
715 return log_device_debug_errno(spawn->device, r, "Failed to create timeout warning event source: %m");
716 }
717
718 spawn->timeout_usec -= age_usec;
719
720 r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
721 usec + spawn->timeout_usec, USEC_PER_SEC, on_spawn_timeout, spawn);
722 if (r < 0)
723 return log_device_debug_errno(spawn->device, r, "Failed to create timeout event source: %m");
724 }
725 }
726
727 if (spawn->fd_stdout >= 0) {
728 r = sd_event_add_io(e, &stdout_source, spawn->fd_stdout, EPOLLIN, on_spawn_io, spawn);
729 if (r < 0)
730 return log_device_debug_errno(spawn->device, r, "Failed to create stdio event source: %m");
731 r = sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT);
732 if (r < 0)
733 return log_device_debug_errno(spawn->device, r, "Failed to enable stdio event source: %m");
734 }
735
736 if (spawn->fd_stderr >= 0) {
737 r = sd_event_add_io(e, &stderr_source, spawn->fd_stderr, EPOLLIN, on_spawn_io, spawn);
738 if (r < 0)
739 return log_device_debug_errno(spawn->device, r, "Failed to create stderr event source: %m");
740 r = sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT);
741 if (r < 0)
742 return log_device_debug_errno(spawn->device, r, "Failed to enable stderr event source: %m");
743 }
744
745 r = sd_event_add_child(e, &sigchld_source, spawn->pid, WEXITED, on_spawn_sigchld, spawn);
746 if (r < 0)
747 return log_device_debug_errno(spawn->device, r, "Failed to create sigchild event source: %m");
748 /* SIGCHLD should be processed after IO is complete */
749 r = sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1);
750 if (r < 0)
751 return log_device_debug_errno(spawn->device, r, "Failed to set priority to sigchild event source: %m");
752
753 return sd_event_loop(e);
754 }
755
756 int udev_event_spawn(
757 UdevEvent *event,
758 usec_t timeout_usec,
759 int timeout_signal,
760 bool accept_failure,
761 const char *cmd,
762 char *result,
763 size_t ressize,
764 bool *ret_truncated) {
765
766 _cleanup_close_pair_ int outpipe[2] = PIPE_EBADF, errpipe[2] = PIPE_EBADF;
767 _cleanup_strv_free_ char **argv = NULL;
768 char **envp = NULL;
769 Spawn spawn;
770 pid_t pid;
771 int r;
772
773 assert(event);
774 assert(event->dev);
775 assert(result || ressize == 0);
776
777 /* pipes from child to parent */
778 if (result || log_get_max_level() >= LOG_INFO)
779 if (pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) != 0)
780 return log_device_error_errno(event->dev, errno,
781 "Failed to create pipe for command '%s': %m", cmd);
782
783 if (log_get_max_level() >= LOG_INFO)
784 if (pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) != 0)
785 return log_device_error_errno(event->dev, errno,
786 "Failed to create pipe for command '%s': %m", cmd);
787
788 r = strv_split_full(&argv, cmd, NULL, EXTRACT_UNQUOTE | EXTRACT_RELAX | EXTRACT_RETAIN_ESCAPE);
789 if (r < 0)
790 return log_device_error_errno(event->dev, r, "Failed to split command: %m");
791
792 if (isempty(argv[0]))
793 return log_device_error_errno(event->dev, SYNTHETIC_ERRNO(EINVAL),
794 "Invalid command '%s'", cmd);
795
796 /* allow programs in /usr/lib/udev/ to be called without the path */
797 if (!path_is_absolute(argv[0])) {
798 char *program;
799
800 program = path_join(UDEVLIBEXECDIR, argv[0]);
801 if (!program)
802 return log_oom();
803
804 free_and_replace(argv[0], program);
805 }
806
807 r = device_get_properties_strv(event->dev, &envp);
808 if (r < 0)
809 return log_device_error_errno(event->dev, r, "Failed to get device properties");
810
811 log_device_debug(event->dev, "Starting '%s'", cmd);
812
813 r = safe_fork("(spawn)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
814 if (r < 0)
815 return log_device_error_errno(event->dev, r,
816 "Failed to fork() to execute command '%s': %m", cmd);
817 if (r == 0) {
818 if (rearrange_stdio(-1, TAKE_FD(outpipe[WRITE_END]), TAKE_FD(errpipe[WRITE_END])) < 0)
819 _exit(EXIT_FAILURE);
820
821 (void) close_all_fds(NULL, 0);
822 (void) rlimit_nofile_safe();
823
824 DEVICE_TRACE_POINT(spawn_exec, event->dev, cmd);
825
826 execve(argv[0], argv, envp);
827 _exit(EXIT_FAILURE);
828 }
829
830 /* parent closed child's ends of pipes */
831 outpipe[WRITE_END] = safe_close(outpipe[WRITE_END]);
832 errpipe[WRITE_END] = safe_close(errpipe[WRITE_END]);
833
834 spawn = (Spawn) {
835 .device = event->dev,
836 .cmd = cmd,
837 .pid = pid,
838 .accept_failure = accept_failure,
839 .timeout_warn_usec = udev_warn_timeout(timeout_usec),
840 .timeout_usec = timeout_usec,
841 .timeout_signal = timeout_signal,
842 .event_birth_usec = event->birth_usec,
843 .fd_stdout = outpipe[READ_END],
844 .fd_stderr = errpipe[READ_END],
845 .result = result,
846 .result_size = ressize,
847 };
848 r = spawn_wait(&spawn);
849 if (r < 0)
850 return log_device_error_errno(event->dev, r,
851 "Failed to wait for spawned command '%s': %m", cmd);
852
853 if (result)
854 result[spawn.result_len] = '\0';
855
856 if (ret_truncated)
857 *ret_truncated = spawn.truncated;
858
859 return r; /* 0 for success, and positive if the program failed */
860 }
861
862 static int rename_netif(UdevEvent *event) {
863 const char *oldname;
864 sd_device *dev;
865 int ifindex, r;
866
867 assert(event);
868
869 if (!event->name)
870 return 0; /* No new name is requested. */
871
872 dev = ASSERT_PTR(event->dev);
873
874 /* Read sysname from cloned sd-device object, otherwise use-after-free is triggered, as the
875 * main object will be renamed and dev->sysname will be freed in device_rename(). */
876 r = sd_device_get_sysname(event->dev_db_clone, &oldname);
877 if (r < 0)
878 return log_device_error_errno(dev, r, "Failed to get sysname: %m");
879
880 if (streq(event->name, oldname))
881 return 0; /* The interface name is already requested name. */
882
883 if (!device_for_action(dev, SD_DEVICE_ADD))
884 return 0; /* Rename the interface only when it is added. */
885
886 r = sd_device_get_ifindex(dev, &ifindex);
887 if (r == -ENOENT)
888 return 0; /* Device is not a network interface. */
889 if (r < 0)
890 return log_device_error_errno(dev, r, "Failed to get ifindex: %m");
891
892 if (naming_scheme_has(NAMING_REPLACE_STRICTLY) &&
893 !ifname_valid(event->name)) {
894 log_device_warning(dev, "Invalid network interface name, ignoring: %s", event->name);
895 return 0;
896 }
897
898 /* Set ID_RENAMING boolean property here. It will be dropped when the corresponding move uevent is processed. */
899 r = device_add_property(dev, "ID_RENAMING", "1");
900 if (r < 0)
901 return log_device_warning_errno(dev, r, "Failed to add 'ID_RENAMING' property: %m");
902
903 r = device_rename(dev, event->name);
904 if (r < 0)
905 return log_device_warning_errno(dev, r, "Failed to update properties with new name '%s': %m", event->name);
906
907 /* Also set ID_RENAMING boolean property to cloned sd_device object and save it to database
908 * before calling rtnl_set_link_name(). Otherwise, clients (e.g., systemd-networkd) may receive
909 * RTM_NEWLINK netlink message before the database is updated. */
910 r = device_add_property(event->dev_db_clone, "ID_RENAMING", "1");
911 if (r < 0)
912 return log_device_warning_errno(event->dev_db_clone, r, "Failed to add 'ID_RENAMING' property: %m");
913
914 r = device_update_db(event->dev_db_clone);
915 if (r < 0)
916 return log_device_debug_errno(event->dev_db_clone, r, "Failed to update database under /run/udev/data/: %m");
917
918 r = rtnl_set_link_name(&event->rtnl, ifindex, event->name);
919 if (r == -EBUSY) {
920 log_device_info(dev, "Network interface '%s' is already up, cannot rename to '%s'.",
921 oldname, event->name);
922 return 0;
923 }
924 if (r < 0)
925 return log_device_error_errno(dev, r, "Failed to rename network interface %i from '%s' to '%s': %m",
926 ifindex, oldname, event->name);
927
928 log_device_debug(dev, "Network interface %i is renamed from '%s' to '%s'", ifindex, oldname, event->name);
929
930 return 1;
931 }
932
933 static int update_devnode(UdevEvent *event) {
934 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
935 int r;
936
937 r = sd_device_get_devnum(dev, NULL);
938 if (r == -ENOENT)
939 return 0;
940 if (r < 0)
941 return log_device_error_errno(dev, r, "Failed to get devnum: %m");
942
943 if (!uid_is_valid(event->uid)) {
944 r = device_get_devnode_uid(dev, &event->uid);
945 if (r < 0 && r != -ENOENT)
946 return log_device_error_errno(dev, r, "Failed to get devnode UID: %m");
947 }
948
949 if (!gid_is_valid(event->gid)) {
950 r = device_get_devnode_gid(dev, &event->gid);
951 if (r < 0 && r != -ENOENT)
952 return log_device_error_errno(dev, r, "Failed to get devnode GID: %m");
953 }
954
955 if (event->mode == MODE_INVALID) {
956 r = device_get_devnode_mode(dev, &event->mode);
957 if (r < 0 && r != -ENOENT)
958 return log_device_error_errno(dev, r, "Failed to get devnode mode: %m");
959 }
960
961 bool apply_mac = device_for_action(dev, SD_DEVICE_ADD);
962
963 r = udev_node_apply_permissions(dev, apply_mac, event->mode, event->uid, event->gid, event->seclabel_list);
964 if (r < 0)
965 return log_device_error_errno(dev, r, "Failed to apply devnode permissions: %m");
966
967 return udev_node_update(dev, event->dev_db_clone);
968 }
969
970 static int event_execute_rules_on_remove(
971 UdevEvent *event,
972 int inotify_fd,
973 usec_t timeout_usec,
974 int timeout_signal,
975 Hashmap *properties_list,
976 UdevRules *rules) {
977
978 sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
979 int r;
980
981 r = device_read_db_internal(dev, true);
982 if (r < 0)
983 log_device_debug_errno(dev, r, "Failed to read database under /run/udev/data/: %m");
984
985 r = device_tag_index(dev, NULL, false);
986 if (r < 0)
987 log_device_debug_errno(dev, r, "Failed to remove corresponding tag files under /run/udev/tag/, ignoring: %m");
988
989 r = device_delete_db(dev);
990 if (r < 0)
991 log_device_debug_errno(dev, r, "Failed to delete database under /run/udev/data/, ignoring: %m");
992
993 r = udev_watch_end(inotify_fd, dev);
994 if (r < 0)
995 log_device_warning_errno(dev, r, "Failed to remove inotify watch, ignoring: %m");
996
997 r = udev_rules_apply_to_event(rules, event, timeout_usec, timeout_signal, properties_list);
998
999 if (sd_device_get_devnum(dev, NULL) >= 0)
1000 (void) udev_node_remove(dev);
1001
1002 return r;
1003 }
1004
1005 static int copy_all_tags(sd_device *d, sd_device *s) {
1006 const char *tag;
1007 int r;
1008
1009 assert(d);
1010
1011 if (!s)
1012 return 0;
1013
1014 FOREACH_DEVICE_TAG(s, tag) {
1015 r = device_add_tag(d, tag, false);
1016 if (r < 0)
1017 return r;
1018 }
1019
1020 return 0;
1021 }
1022
1023 int udev_event_execute_rules(
1024 UdevEvent *event,
1025 int inotify_fd, /* This may be negative */
1026 usec_t timeout_usec,
1027 int timeout_signal,
1028 Hashmap *properties_list,
1029 UdevRules *rules) {
1030
1031 sd_device_action_t action;
1032 sd_device *dev;
1033 int r;
1034
1035 dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
1036 assert(rules);
1037
1038 r = sd_device_get_action(dev, &action);
1039 if (r < 0)
1040 return log_device_error_errno(dev, r, "Failed to get ACTION: %m");
1041
1042 if (action == SD_DEVICE_REMOVE)
1043 return event_execute_rules_on_remove(event, inotify_fd, timeout_usec, timeout_signal, properties_list, rules);
1044
1045 /* Disable watch during event processing. */
1046 r = udev_watch_end(inotify_fd, dev);
1047 if (r < 0)
1048 log_device_warning_errno(dev, r, "Failed to remove inotify watch, ignoring: %m");
1049
1050 r = device_clone_with_db(dev, &event->dev_db_clone);
1051 if (r < 0)
1052 return log_device_debug_errno(dev, r, "Failed to clone sd_device object: %m");
1053
1054 r = copy_all_tags(dev, event->dev_db_clone);
1055 if (r < 0)
1056 log_device_warning_errno(dev, r, "Failed to copy all tags from old database entry, ignoring: %m");
1057
1058 /* Drop previously added property for safety to make IMPORT{db}="ID_RENAMING" not work. This is
1059 * mostly for 'move' uevent, but let's do unconditionally. Why? If a network interface is renamed in
1060 * initrd, then udevd may lose the 'move' uevent during switching root. Usually, we do not set the
1061 * persistent flag for network interfaces, but user may set it. Just for safety. */
1062 r = device_add_property(event->dev_db_clone, "ID_RENAMING", NULL);
1063 if (r < 0)
1064 return log_device_debug_errno(dev, r, "Failed to remove 'ID_RENAMING' property: %m");
1065
1066 DEVICE_TRACE_POINT(rules_start, dev);
1067
1068 r = udev_rules_apply_to_event(rules, event, timeout_usec, timeout_signal, properties_list);
1069 if (r < 0)
1070 return log_device_debug_errno(dev, r, "Failed to apply udev rules: %m");
1071
1072 DEVICE_TRACE_POINT(rules_finished, dev);
1073
1074 r = rename_netif(event);
1075 if (r < 0)
1076 return r;
1077
1078 r = update_devnode(event);
1079 if (r < 0)
1080 return r;
1081
1082 /* preserve old, or get new initialization timestamp */
1083 r = device_ensure_usec_initialized(dev, event->dev_db_clone);
1084 if (r < 0)
1085 return log_device_debug_errno(dev, r, "Failed to set initialization timestamp: %m");
1086
1087 /* (re)write database file */
1088 r = device_tag_index(dev, event->dev_db_clone, true);
1089 if (r < 0)
1090 return log_device_debug_errno(dev, r, "Failed to update tags under /run/udev/tag/: %m");
1091
1092 r = device_update_db(dev);
1093 if (r < 0)
1094 return log_device_debug_errno(dev, r, "Failed to update database under /run/udev/data/: %m");
1095
1096 device_set_is_initialized(dev);
1097
1098 return 0;
1099 }
1100
1101 void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal) {
1102 const char *command;
1103 void *val;
1104 int r;
1105
1106 ORDERED_HASHMAP_FOREACH_KEY(val, command, event->run_list) {
1107 UdevBuiltinCommand builtin_cmd = PTR_TO_UDEV_BUILTIN_CMD(val);
1108
1109 if (builtin_cmd != _UDEV_BUILTIN_INVALID) {
1110 log_device_debug(event->dev, "Running built-in command \"%s\"", command);
1111 r = udev_builtin_run(event->dev, &event->rtnl, builtin_cmd, command, false);
1112 if (r < 0)
1113 log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command);
1114 } else {
1115 if (event->exec_delay_usec > 0) {
1116 log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.",
1117 command, FORMAT_TIMESPAN(event->exec_delay_usec, USEC_PER_SEC));
1118 (void) usleep(event->exec_delay_usec);
1119 }
1120
1121 log_device_debug(event->dev, "Running command \"%s\"", command);
1122
1123 r = udev_event_spawn(event, timeout_usec, timeout_signal, false, command, NULL, 0, NULL);
1124 if (r < 0)
1125 log_device_warning_errno(event->dev, r, "Failed to execute '%s', ignoring: %m", command);
1126 else if (r > 0) /* returned value is positive when program fails */
1127 log_device_debug(event->dev, "Command \"%s\" returned %d (error), ignoring.", command, r);
1128 }
1129 }
1130 }