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