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