]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/udev/udev-event.c
Merge pull request #14085 from poettering/ask-password-api
[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 <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 "libudev-util.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 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_device_error_errno(spawn->device, errno,
554 "Failed to read stdout of '%s': %m", spawn->cmd);
555
556 return 0;
557 }
558
559 p[l] = '\0';
560 if (fd == spawn->fd_stdout && spawn->result)
561 spawn->result_len += l;
562
563 /* Log output only if we watch stderr. */
564 if (l > 0 && spawn->fd_stderr >= 0) {
565 _cleanup_strv_free_ char **v = NULL;
566 char **q;
567
568 v = strv_split_newlines(p);
569 if (!v)
570 return 0;
571
572 STRV_FOREACH(q, v)
573 log_device_debug(spawn->device, "'%s'(%s) '%s'", spawn->cmd,
574 fd == spawn->fd_stdout ? "out" : "err", *q);
575 }
576
577 return 0;
578 }
579
580 static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
581 Spawn *spawn = userdata;
582 char timeout[FORMAT_TIMESPAN_MAX];
583
584 assert(spawn);
585
586 kill_and_sigcont(spawn->pid, SIGKILL);
587
588 log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing",
589 spawn->cmd, spawn->pid,
590 format_timespan(timeout, sizeof(timeout), spawn->timeout_usec, USEC_PER_SEC));
591
592 return 1;
593 }
594
595 static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
596 Spawn *spawn = userdata;
597 char timeout[FORMAT_TIMESPAN_MAX];
598
599 assert(spawn);
600
601 log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete",
602 spawn->cmd, spawn->pid,
603 format_timespan(timeout, sizeof(timeout), spawn->timeout_warn_usec, USEC_PER_SEC));
604
605 return 1;
606 }
607
608 static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
609 Spawn *spawn = userdata;
610 int ret = -EIO;
611
612 assert(spawn);
613
614 switch (si->si_code) {
615 case CLD_EXITED:
616 if (si->si_status == 0)
617 log_device_debug(spawn->device, "Process '%s' succeeded.", spawn->cmd);
618 else
619 log_device_full(spawn->device, spawn->accept_failure ? LOG_DEBUG : LOG_WARNING, 0,
620 "Process '%s' failed with exit code %i.", spawn->cmd, si->si_status);
621 ret = si->si_status;
622 break;
623 case CLD_KILLED:
624 case CLD_DUMPED:
625 log_device_error(spawn->device, "Process '%s' terminated by signal %s.", spawn->cmd, signal_to_string(si->si_status));
626 break;
627 default:
628 log_device_error(spawn->device, "Process '%s' failed due to unknown reason.", spawn->cmd);
629 }
630
631 sd_event_exit(sd_event_source_get_event(s), ret);
632 return 1;
633 }
634
635 static int spawn_wait(Spawn *spawn) {
636 _cleanup_(sd_event_unrefp) sd_event *e = NULL;
637 int r;
638
639 assert(spawn);
640
641 r = sd_event_new(&e);
642 if (r < 0)
643 return r;
644
645 if (spawn->timeout_usec > 0) {
646 usec_t usec, age_usec;
647
648 usec = now(CLOCK_MONOTONIC);
649 age_usec = usec - spawn->event_birth_usec;
650 if (age_usec < spawn->timeout_usec) {
651 if (spawn->timeout_warn_usec > 0 &&
652 spawn->timeout_warn_usec < spawn->timeout_usec &&
653 spawn->timeout_warn_usec > age_usec) {
654 spawn->timeout_warn_usec -= age_usec;
655
656 r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
657 usec + spawn->timeout_warn_usec, USEC_PER_SEC,
658 on_spawn_timeout_warning, spawn);
659 if (r < 0)
660 return r;
661 }
662
663 spawn->timeout_usec -= age_usec;
664
665 r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
666 usec + spawn->timeout_usec, USEC_PER_SEC, on_spawn_timeout, spawn);
667 if (r < 0)
668 return r;
669 }
670 }
671
672 if (spawn->fd_stdout >= 0) {
673 r = sd_event_add_io(e, NULL, spawn->fd_stdout, EPOLLIN, on_spawn_io, spawn);
674 if (r < 0)
675 return r;
676 }
677
678 if (spawn->fd_stderr >= 0) {
679 r = sd_event_add_io(e, NULL, spawn->fd_stderr, EPOLLIN, on_spawn_io, spawn);
680 if (r < 0)
681 return r;
682 }
683
684 r = sd_event_add_child(e, NULL, spawn->pid, WEXITED, on_spawn_sigchld, spawn);
685 if (r < 0)
686 return r;
687
688 return sd_event_loop(e);
689 }
690
691 int udev_event_spawn(UdevEvent *event,
692 usec_t timeout_usec,
693 bool accept_failure,
694 const char *cmd,
695 char *result, size_t ressize) {
696 _cleanup_close_pair_ int outpipe[2] = {-1, -1}, errpipe[2] = {-1, -1};
697 _cleanup_strv_free_ char **argv = NULL;
698 char **envp = NULL;
699 Spawn spawn;
700 pid_t pid;
701 int r;
702
703 assert(event);
704 assert(event->dev);
705 assert(result || ressize == 0);
706
707 /* pipes from child to parent */
708 if (result || log_get_max_level() >= LOG_INFO)
709 if (pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) != 0)
710 return log_device_error_errno(event->dev, errno,
711 "Failed to create pipe for command '%s': %m", cmd);
712
713 if (log_get_max_level() >= LOG_INFO)
714 if (pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) != 0)
715 return log_device_error_errno(event->dev, errno,
716 "Failed to create pipe for command '%s': %m", cmd);
717
718 argv = strv_split_full(cmd, NULL, SPLIT_QUOTES|SPLIT_RELAX);
719 if (!argv)
720 return log_oom();
721
722 if (isempty(argv[0]))
723 return log_device_error_errno(event->dev, SYNTHETIC_ERRNO(EINVAL),
724 "Invalid command '%s'", cmd);
725
726 /* allow programs in /usr/lib/udev/ to be called without the path */
727 if (!path_is_absolute(argv[0])) {
728 char *program;
729
730 program = path_join(UDEVLIBEXECDIR, argv[0]);
731 if (!program)
732 return log_oom();
733
734 free_and_replace(argv[0], program);
735 }
736
737 r = device_get_properties_strv(event->dev, &envp);
738 if (r < 0)
739 return log_device_error_errno(event->dev, r, "Failed to get device properties");
740
741 log_device_debug(event->dev, "Starting '%s'", cmd);
742
743 r = safe_fork("(spawn)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
744 if (r < 0)
745 return log_device_error_errno(event->dev, r,
746 "Failed to fork() to execute command '%s': %m", cmd);
747 if (r == 0) {
748 if (rearrange_stdio(-1, outpipe[WRITE_END], errpipe[WRITE_END]) < 0)
749 _exit(EXIT_FAILURE);
750
751 (void) close_all_fds(NULL, 0);
752 (void) rlimit_nofile_safe();
753
754 execve(argv[0], argv, envp);
755 _exit(EXIT_FAILURE);
756 }
757
758 /* parent closed child's ends of pipes */
759 outpipe[WRITE_END] = safe_close(outpipe[WRITE_END]);
760 errpipe[WRITE_END] = safe_close(errpipe[WRITE_END]);
761
762 spawn = (Spawn) {
763 .device = event->dev,
764 .cmd = cmd,
765 .pid = pid,
766 .accept_failure = accept_failure,
767 .timeout_warn_usec = udev_warn_timeout(timeout_usec),
768 .timeout_usec = timeout_usec,
769 .event_birth_usec = event->birth_usec,
770 .fd_stdout = outpipe[READ_END],
771 .fd_stderr = errpipe[READ_END],
772 .result = result,
773 .result_size = ressize,
774 };
775 r = spawn_wait(&spawn);
776 if (r < 0)
777 return log_device_error_errno(event->dev, r,
778 "Failed to wait for spawned command '%s': %m", cmd);
779
780 if (result)
781 result[spawn.result_len] = '\0';
782
783 return r; /* 0 for success, and positive if the program failed */
784 }
785
786 static int rename_netif(UdevEvent *event) {
787 sd_device *dev = event->dev;
788 const char *oldname;
789 int ifindex, r;
790
791 if (!event->name)
792 return 0; /* No new name is requested. */
793
794 r = sd_device_get_sysname(dev, &oldname);
795 if (r < 0)
796 return log_device_error_errno(dev, r, "Failed to get sysname: %m");
797
798 if (streq(event->name, oldname))
799 return 0; /* The interface name is already requested name. */
800
801 if (!device_for_action(dev, DEVICE_ACTION_ADD))
802 return 0; /* Rename the interface only when it is added. */
803
804 r = sd_device_get_ifindex(dev, &ifindex);
805 if (r == -ENOENT)
806 return 0; /* Device is not a network interface. */
807 if (r < 0)
808 return log_device_error_errno(dev, r, "Failed to get ifindex: %m");
809
810 r = rtnl_set_link_name(&event->rtnl, ifindex, event->name);
811 if (r < 0)
812 return log_device_error_errno(dev, r, "Failed to rename network interface %i from '%s' to '%s': %m",
813 ifindex, oldname, event->name);
814
815 /* Set ID_RENAMING boolean property here, and drop it in the corresponding move uevent later. */
816 r = device_add_property(dev, "ID_RENAMING", "1");
817 if (r < 0)
818 return log_device_warning_errno(dev, r, "Failed to add 'ID_RENAMING' property: %m");
819
820 r = device_rename(dev, event->name);
821 if (r < 0)
822 return log_device_warning_errno(dev, r, "Failed to update properties with new name '%s': %m", event->name);
823
824 log_device_debug(dev, "Network interface %i is renamed from '%s' to '%s'", ifindex, oldname, event->name);
825
826 return 1;
827 }
828
829 static int update_devnode(UdevEvent *event) {
830 sd_device *dev = event->dev;
831 int r;
832
833 r = sd_device_get_devnum(dev, NULL);
834 if (r == -ENOENT)
835 return 0;
836 if (r < 0)
837 return log_device_error_errno(dev, r, "Failed to get devnum: %m");
838
839 /* remove/update possible left-over symlinks from old database entry */
840 if (event->dev_db_clone)
841 (void) udev_node_update_old_links(dev, event->dev_db_clone);
842
843 if (!uid_is_valid(event->uid)) {
844 r = device_get_devnode_uid(dev, &event->uid);
845 if (r < 0 && r != -ENOENT)
846 return log_device_error_errno(dev, r, "Failed to get devnode UID: %m");
847 }
848
849 if (!gid_is_valid(event->gid)) {
850 r = device_get_devnode_gid(dev, &event->gid);
851 if (r < 0 && r != -ENOENT)
852 return log_device_error_errno(dev, r, "Failed to get devnode GID: %m");
853 }
854
855 if (event->mode == MODE_INVALID) {
856 r = device_get_devnode_mode(dev, &event->mode);
857 if (r < 0 && r != -ENOENT)
858 return log_device_error_errno(dev, r, "Failed to get devnode mode: %m");
859 }
860 if (event->mode == MODE_INVALID && gid_is_valid(event->gid) && event->gid > 0)
861 /* If group is set, but mode is not set, "upgrade" mode for the group. */
862 event->mode = 0660;
863
864 bool apply_mac = device_for_action(dev, DEVICE_ACTION_ADD);
865
866 return udev_node_add(dev, apply_mac, event->mode, event->uid, event->gid, event->seclabel_list);
867 }
868
869 static void event_execute_rules_on_remove(
870 UdevEvent *event,
871 usec_t timeout_usec,
872 Hashmap *properties_list,
873 UdevRules *rules) {
874
875 sd_device *dev = event->dev;
876 int r;
877
878 r = device_read_db_internal(dev, true);
879 if (r < 0)
880 log_device_debug_errno(dev, r, "Failed to read database under /run/udev/data/: %m");
881
882 r = device_tag_index(dev, NULL, false);
883 if (r < 0)
884 log_device_debug_errno(dev, r, "Failed to remove corresponding tag files under /run/udev/tag/, ignoring: %m");
885
886 r = device_delete_db(dev);
887 if (r < 0)
888 log_device_debug_errno(dev, r, "Failed to delete database under /run/udev/data/, ignoring: %m");
889
890 if (sd_device_get_devnum(dev, NULL) >= 0)
891 (void) udev_watch_end(dev);
892
893 (void) udev_rules_apply_to_event(rules, event, timeout_usec, properties_list);
894
895 if (sd_device_get_devnum(dev, NULL) >= 0)
896 (void) udev_node_remove(dev);
897 }
898
899 static int udev_event_on_move(UdevEvent *event) {
900 sd_device *dev = event->dev;
901 int r;
902
903 if (event->dev_db_clone &&
904 sd_device_get_devnum(dev, NULL) < 0) {
905 r = device_copy_properties(dev, event->dev_db_clone);
906 if (r < 0)
907 log_device_debug_errno(dev, r, "Failed to copy properties from cloned sd_device object, ignoring: %m");
908 }
909
910 /* Drop previously added property */
911 r = device_add_property(dev, "ID_RENAMING", NULL);
912 if (r < 0)
913 return log_device_debug_errno(dev, r, "Failed to remove 'ID_RENAMING' property: %m");
914
915 return 0;
916 }
917
918 int udev_event_execute_rules(UdevEvent *event,
919 usec_t timeout_usec,
920 Hashmap *properties_list,
921 UdevRules *rules) {
922 const char *subsystem;
923 DeviceAction action;
924 sd_device *dev;
925 int r;
926
927 assert(event);
928 assert(rules);
929
930 dev = event->dev;
931
932 r = sd_device_get_subsystem(dev, &subsystem);
933 if (r < 0)
934 return log_device_error_errno(dev, r, "Failed to get subsystem: %m");
935
936 r = device_get_action(dev, &action);
937 if (r < 0)
938 return log_device_error_errno(dev, r, "Failed to get ACTION: %m");
939
940 if (action == DEVICE_ACTION_REMOVE) {
941 event_execute_rules_on_remove(event, timeout_usec, properties_list, rules);
942 return 0;
943 }
944
945 r = device_clone_with_db(dev, &event->dev_db_clone);
946 if (r < 0)
947 return log_device_debug_errno(dev, r, "Failed to clone sd_device object: %m");
948
949 if (event->dev_db_clone && sd_device_get_devnum(dev, NULL) >= 0)
950 /* Disable watch during event processing. */
951 (void) udev_watch_end(event->dev_db_clone);
952
953 if (action == DEVICE_ACTION_MOVE) {
954 r = udev_event_on_move(event);
955 if (r < 0)
956 return r;
957 }
958
959 r = udev_rules_apply_to_event(rules, event, timeout_usec, properties_list);
960 if (r < 0)
961 return log_device_debug_errno(dev, r, "Failed to apply udev rules: %m");
962
963 r = rename_netif(event);
964 if (r < 0)
965 return r;
966
967 r = update_devnode(event);
968 if (r < 0)
969 return r;
970
971 /* preserve old, or get new initialization timestamp */
972 r = device_ensure_usec_initialized(dev, event->dev_db_clone);
973 if (r < 0)
974 return log_device_debug_errno(dev, r, "Failed to set initialization timestamp: %m");
975
976 /* (re)write database file */
977 r = device_tag_index(dev, event->dev_db_clone, true);
978 if (r < 0)
979 return log_device_debug_errno(dev, r, "Failed to update tags under /run/udev/tag/: %m");
980
981 r = device_update_db(dev);
982 if (r < 0)
983 return log_device_debug_errno(dev, r, "Failed to update database under /run/udev/data/: %m");
984
985 device_set_is_initialized(dev);
986
987 event->dev_db_clone = sd_device_unref(event->dev_db_clone);
988
989 return 0;
990 }
991
992 void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec) {
993 const char *command;
994 void *val;
995 Iterator i;
996 int r;
997
998 ORDERED_HASHMAP_FOREACH_KEY(val, command, event->run_list, i) {
999 UdevBuiltinCommand builtin_cmd = PTR_TO_UDEV_BUILTIN_CMD(val);
1000
1001 if (builtin_cmd != _UDEV_BUILTIN_INVALID) {
1002 log_device_debug(event->dev, "Running built-in command \"%s\"", command);
1003 r = udev_builtin_run(event->dev, builtin_cmd, command, false);
1004 if (r < 0)
1005 log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command);
1006 } else {
1007 if (event->exec_delay_usec > 0) {
1008 char buf[FORMAT_TIMESPAN_MAX];
1009
1010 log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.",
1011 command, format_timespan(buf, sizeof(buf), event->exec_delay_usec, USEC_PER_SEC));
1012 (void) usleep(event->exec_delay_usec);
1013 }
1014
1015 log_device_debug(event->dev, "Running command \"%s\"", command);
1016 r = udev_event_spawn(event, timeout_usec, false, command, NULL, 0);
1017 if (r < 0)
1018 log_device_warning_errno(event->dev, r, "Failed to execute '%s', ignoring: %m", command);
1019 else if (r > 0) /* returned value is positive when program fails */
1020 log_device_debug(event->dev, "Command \"%s\" returned %d (error), ignoring.", command, r);
1021 }
1022 }
1023 }