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