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