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