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