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