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