]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/udev/udev-event.c
udev: rename enum subst_type -> FormatSubstitutionType
[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"
feaa6db7 23#include "path-util.h"
8128f229 24#include "process-util.h"
595225af 25#include "rlimit-util.h"
24882e06 26#include "signal-util.h"
4cade7a1 27#include "stdio-util.h"
07630cea 28#include "string-util.h"
5ea78a39
YW
29#include "strv.h"
30#include "strxcpyx.h"
07a26e42 31#include "udev-builtin.h"
25de7aa7 32#include "udev-event.h"
a2554ace 33#include "udev-node.h"
d4d690fa 34#include "udev-util.h"
70068602 35#include "udev-watch.h"
25de7aa7 36#include "user-util.h"
8128f229
TG
37
38typedef struct Spawn {
39 const char *cmd;
40 pid_t pid;
e81c3a4c
YW
41 usec_t timeout_warn_usec;
42 usec_t timeout_usec;
43 usec_t event_birth_usec;
53318514 44 bool accept_failure;
e81c3a4c
YW
45 int fd_stdout;
46 int fd_stderr;
47 char *result;
48 size_t result_size;
49 size_t result_len;
8128f229 50} Spawn;
d46f37fd 51
2e088715
ZJS
52UdevEvent *udev_event_new(sd_device *dev, usec_t exec_delay_usec, sd_netlink *rtnl) {
53 UdevEvent *event;
912541b0 54
89665d09
YW
55 assert(dev);
56
2e088715 57 event = new(UdevEvent, 1);
89665d09 58 if (!event)
912541b0 59 return NULL;
89665d09 60
2e088715 61 *event = (UdevEvent) {
cf28ad46 62 .dev = sd_device_ref(dev),
89665d09 63 .birth_usec = now(CLOCK_MONOTONIC),
6b92f429 64 .exec_delay_usec = exec_delay_usec,
e0bb2ff9 65 .rtnl = sd_netlink_ref(rtnl),
25de7aa7
YW
66 .uid = UID_INVALID,
67 .gid = GID_INVALID,
68 .mode = MODE_INVALID,
89665d09
YW
69 };
70
912541b0 71 return event;
aa8734ff
KS
72}
73
2e088715 74UdevEvent *udev_event_free(UdevEvent *event) {
c1118ceb
YW
75 if (!event)
76 return NULL;
77
cf28ad46 78 sd_device_unref(event->dev);
480ecb7d 79 sd_device_unref(event->dev_db_clone);
1c4baffc 80 sd_netlink_unref(event->rtnl);
39a15c8a
YW
81 ordered_hashmap_free_free_key(event->run_list);
82 ordered_hashmap_free_free_free(event->seclabel_list);
912541b0
KS
83 free(event->program_result);
84 free(event->name);
c1118ceb
YW
85
86 return mfree(event);
aa8734ff
KS
87}
88
7e9c23dd
YW
89typedef 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;
0d53705b 109
9204d802
YW
110struct subst_map_entry {
111 const char *name;
112 const char fmt;
7e9c23dd 113 FormatSubstitutionType type;
9204d802
YW
114};
115
116static const struct subst_map_entry map[] = {
7e9c23dd
YW
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 },
9204d802
YW
135};
136
2e088715 137static ssize_t subst_format_var(UdevEvent *event,
4cade7a1
YW
138 const struct subst_map_entry *entry, char *attr,
139 char *dest, size_t l) {
cf28ad46 140 sd_device *parent, *dev = event->dev;
4cade7a1 141 const char *val = NULL;
be452683 142 char *s = dest;
4cade7a1
YW
143 dev_t devnum;
144 int r;
0d53705b 145
9204d802
YW
146 assert(entry);
147
148 switch (entry->type) {
7e9c23dd 149 case FORMAT_SUBST_DEVPATH:
4cade7a1
YW
150 r = sd_device_get_devpath(dev, &val);
151 if (r < 0)
152 return r;
153 l = strpcpy(&s, l, val);
0d53705b 154 break;
7e9c23dd 155 case FORMAT_SUBST_KERNEL:
4cade7a1
YW
156 r = sd_device_get_sysname(dev, &val);
157 if (r < 0)
158 return r;
159 l = strpcpy(&s, l, val);
0d53705b 160 break;
7e9c23dd 161 case FORMAT_SUBST_KERNEL_NUMBER:
4cade7a1 162 r = sd_device_get_sysnum(dev, &val);
380d1901
YW
163 if (r == -ENOENT)
164 goto null_terminate;
4cade7a1 165 if (r < 0)
380d1901 166 return r;
4cade7a1 167 l = strpcpy(&s, l, val);
0d53705b 168 break;
7e9c23dd 169 case FORMAT_SUBST_ID:
4cade7a1 170 if (!event->dev_parent)
380d1901 171 goto null_terminate;
f3d241fe 172 r = sd_device_get_sysname(event->dev_parent, &val);
4cade7a1
YW
173 if (r < 0)
174 return r;
175 l = strpcpy(&s, l, val);
0d53705b 176 break;
7e9c23dd 177 case FORMAT_SUBST_DRIVER:
4cade7a1 178 if (!event->dev_parent)
380d1901 179 goto null_terminate;
f3d241fe 180 r = sd_device_get_driver(event->dev_parent, &val);
380d1901
YW
181 if (r == -ENOENT)
182 goto null_terminate;
4cade7a1 183 if (r < 0)
380d1901 184 return r;
4cade7a1 185 l = strpcpy(&s, l, val);
0d53705b 186 break;
7e9c23dd
YW
187 case FORMAT_SUBST_MAJOR:
188 case FORMAT_SUBST_MINOR: {
4cade7a1 189 char buf[DECIMAL_STR_MAX(unsigned)];
0d53705b 190
4cade7a1
YW
191 r = sd_device_get_devnum(dev, &devnum);
192 if (r < 0 && r != -ENOENT)
193 return r;
7e9c23dd 194 xsprintf(buf, "%u", r < 0 ? 0 : entry->type == FORMAT_SUBST_MAJOR ? major(devnum) : minor(devnum));
4cade7a1 195 l = strpcpy(&s, l, buf);
0d53705b
DS
196 break;
197 }
7e9c23dd 198 case FORMAT_SUBST_RESULT: {
0d53705b
DS
199 char *rest;
200 int i;
201
4cade7a1 202 if (!event->program_result)
380d1901 203 goto null_terminate;
4cade7a1 204
0d53705b
DS
205 /* get part of the result string */
206 i = 0;
4cade7a1 207 if (attr)
0d53705b
DS
208 i = strtoul(attr, &rest, 10);
209 if (i > 0) {
4cade7a1 210 char result[UTIL_PATH_SIZE], tmp[UTIL_PATH_SIZE], *cpos;
0d53705b
DS
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);
4cade7a1 234 } else
0d53705b 235 l = strpcpy(&s, l, event->program_result);
0d53705b
DS
236 break;
237 }
7e9c23dd 238 case FORMAT_SUBST_ATTR: {
0d53705b
DS
239 char vbuf[UTIL_NAME_SIZE];
240 size_t len;
241 int count;
242
4cade7a1
YW
243 if (!attr)
244 return -EINVAL;
0d53705b
DS
245
246 /* try to read the value specified by "[dmi/id]product_name" */
3839535a 247 if (util_resolve_subsys_kernel(attr, vbuf, sizeof(vbuf), true) == 0)
4cade7a1 248 val = vbuf;
0d53705b
DS
249
250 /* try to read the attribute the device */
4cade7a1
YW
251 if (!val)
252 (void) sd_device_get_sysattr_value(dev, attr, &val);
0d53705b
DS
253
254 /* try to read the attribute of the parent device, other matches have selected */
f3d241fe
YW
255 if (!val && event->dev_parent && event->dev_parent != dev)
256 (void) sd_device_get_sysattr_value(event->dev_parent, attr, &val);
0d53705b 257
4cade7a1 258 if (!val)
380d1901 259 goto null_terminate;
0d53705b
DS
260
261 /* strip trailing whitespace, and replace unwanted characters */
4cade7a1
YW
262 if (val != vbuf)
263 strscpy(vbuf, sizeof(vbuf), val);
0d53705b
DS
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)
4cade7a1 269 log_device_debug(dev, "%i character(s) replaced", count);
0d53705b
DS
270 l = strpcpy(&s, l, vbuf);
271 break;
272 }
7e9c23dd 273 case FORMAT_SUBST_PARENT:
4cade7a1 274 r = sd_device_get_parent(dev, &parent);
380d1901
YW
275 if (r == -ENODEV)
276 goto null_terminate;
4cade7a1 277 if (r < 0)
380d1901 278 return r;
4cade7a1 279 r = sd_device_get_devname(parent, &val);
380d1901
YW
280 if (r == -ENOENT)
281 goto null_terminate;
4cade7a1 282 if (r < 0)
380d1901 283 return r;
4cade7a1 284 l = strpcpy(&s, l, val + STRLEN("/dev/"));
0d53705b 285 break;
7e9c23dd 286 case FORMAT_SUBST_DEVNODE:
4cade7a1 287 r = sd_device_get_devname(dev, &val);
380d1901
YW
288 if (r == -ENOENT)
289 goto null_terminate;
4cade7a1 290 if (r < 0)
380d1901 291 return r;
4cade7a1 292 l = strpcpy(&s, l, val);
0d53705b 293 break;
7e9c23dd 294 case FORMAT_SUBST_NAME:
4cade7a1 295 if (event->name)
0d53705b 296 l = strpcpy(&s, l, event->name);
4cade7a1
YW
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 }
0d53705b 305 break;
7e9c23dd 306 case FORMAT_SUBST_LINKS:
4cade7a1
YW
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);
380d1901
YW
312 if (s == dest)
313 goto null_terminate;
0d53705b 314 break;
7e9c23dd 315 case FORMAT_SUBST_ROOT:
0d53705b
DS
316 l = strpcpy(&s, l, "/dev");
317 break;
7e9c23dd 318 case FORMAT_SUBST_SYS:
0d53705b
DS
319 l = strpcpy(&s, l, "/sys");
320 break;
7e9c23dd 321 case FORMAT_SUBST_ENV:
4cade7a1 322 if (!attr)
380d1901 323 goto null_terminate;
4cade7a1 324 r = sd_device_get_property_value(dev, attr, &val);
380d1901
YW
325 if (r == -ENOENT)
326 goto null_terminate;
4cade7a1 327 if (r < 0)
380d1901 328 return r;
4cade7a1
YW
329 l = strpcpy(&s, l, val);
330 break;
0d53705b 331 default:
9204d802 332 assert_not_reached("Unknown format substitution type");
0d53705b
DS
333 }
334
be452683 335 return s - dest;
380d1901
YW
336
337null_terminate:
338 *s = '\0';
339 return 0;
0d53705b
DS
340}
341
2e088715 342ssize_t udev_event_apply_format(UdevEvent *event,
4cade7a1
YW
343 const char *src, char *dest, size_t size,
344 bool replace_whitespace) {
912541b0
KS
345 const char *from;
346 char *s;
347 size_t l;
348
a368732b
YW
349 assert(event);
350 assert(event->dev);
351 assert(src);
352 assert(dest);
353 assert(size > 0);
3b64e4d4 354
912541b0
KS
355 from = src;
356 s = dest;
357 l = size;
358
359 for (;;) {
9204d802 360 const struct subst_map_entry *entry = NULL;
4cade7a1
YW
361 char attrbuf[UTIL_PATH_SIZE], *attr;
362 bool format_dollar = false;
363 ssize_t subst_len;
912541b0
KS
364
365 while (from[0] != '\0') {
366 if (from[0] == '$') {
367 /* substitute named variable */
14cb109d 368 unsigned i;
912541b0
KS
369
370 if (from[1] == '$') {
371 from++;
372 goto copy;
373 }
374
8fef0ff2 375 for (i = 0; i < ELEMENTSOF(map); i++) {
33502ffe 376 if (startswith(&from[1], map[i].name)) {
9204d802 377 entry = &map[i];
912541b0 378 from += strlen(map[i].name)+1;
4cade7a1 379 format_dollar = true;
912541b0
KS
380 goto subst;
381 }
382 }
383 } else if (from[0] == '%') {
384 /* substitute format char */
14cb109d 385 unsigned i;
912541b0
KS
386
387 if (from[1] == '%') {
388 from++;
389 goto copy;
390 }
391
8fef0ff2 392 for (i = 0; i < ELEMENTSOF(map); i++) {
912541b0 393 if (from[1] == map[i].fmt) {
9204d802 394 entry = &map[i];
912541b0 395 from += 2;
912541b0
KS
396 goto subst;
397 }
398 }
399 }
065db052 400copy:
912541b0 401 /* copy char */
79a695f2 402 if (l < 2) /* need space for this char and the terminating NUL */
912541b0
KS
403 goto out;
404 s[0] = from[0];
405 from++;
406 s++;
407 l--;
408 }
409
410 goto out;
065db052 411subst:
912541b0
KS
412 /* extract possible $format{attr} */
413 if (from[0] == '{') {
14cb109d 414 unsigned i;
912541b0
KS
415
416 from++;
79a695f2 417 for (i = 0; from[i] != '}'; i++)
912541b0 418 if (from[i] == '\0') {
9f6445e3 419 log_error("missing closing brace for format '%s'", src);
912541b0
KS
420 goto out;
421 }
79a695f2 422
912541b0
KS
423 if (i >= sizeof(attrbuf))
424 goto out;
425 memcpy(attrbuf, from, i);
426 attrbuf[i] = '\0';
427 from += i+1;
428 attr = attrbuf;
4cade7a1 429 } else
912541b0 430 attr = NULL;
912541b0 431
9204d802 432 subst_len = subst_format_var(event, entry, attr, s, l);
4cade7a1
YW
433 if (subst_len < 0) {
434 if (format_dollar)
cf28ad46 435 log_device_warning_errno(event->dev, subst_len, "Failed to substitute variable '$%s', ignoring: %m", entry->name);
4cade7a1 436 else
cf28ad46 437 log_device_warning_errno(event->dev, subst_len, "Failed to apply format '%%%c', ignoring: %m", entry->fmt);
4cade7a1
YW
438
439 continue;
440 }
e20a9171 441
7e9c23dd
YW
442 /* FORMAT_SUBST_RESULT handles spaces itself */
443 if (replace_whitespace && entry->type != FORMAT_SUBST_RESULT)
be452683
DS
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);
e20a9171 448
be452683
DS
449 s += subst_len;
450 l -= subst_len;
912541b0 451 }
065db052
KS
452
453out:
79a695f2 454 assert(l >= 1);
912541b0 455 s[0] = '\0';
912541b0 456 return l;
f1128767
KS
457}
458
e81c3a4c
YW
459static 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;
912541b0 464
e81c3a4c
YW
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);
912541b0
KS
475 }
476
e81c3a4c
YW
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);
912541b0 481
e81c3a4c 482 return 0;
912541b0
KS
483 }
484
e81c3a4c
YW
485 p[l] = '\0';
486 if (fd == spawn->fd_stdout && spawn->result)
487 spawn->result_len += l;
912541b0 488
e81c3a4c
YW
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;
912541b0 493
e81c3a4c
YW
494 v = strv_split_newlines(p);
495 if (!v)
496 return 0;
912541b0 497
e81c3a4c
YW
498 STRV_FOREACH(q, v)
499 log_debug("'%s'(%s) '%s'", spawn->cmd,
500 fd == spawn->fd_stdout ? "out" : "err", *q);
912541b0
KS
501 }
502
e81c3a4c 503 return 0;
2181d30a
KS
504}
505
8128f229
TG
506static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
507 Spawn *spawn = userdata;
4375dab5 508 char timeout[FORMAT_TIMESPAN_MAX];
912541b0 509
8128f229 510 assert(spawn);
912541b0 511
8128f229 512 kill_and_sigcont(spawn->pid, SIGKILL);
912541b0 513
5ca3dbc9 514 log_error("Spawned process '%s' ["PID_FMT"] timed out after %s, killing", spawn->cmd, spawn->pid,
4375dab5 515 format_timespan(timeout, sizeof(timeout), spawn->timeout_usec, USEC_PER_SEC));
912541b0 516
8128f229
TG
517 return 1;
518}
67117413 519
8128f229
TG
520static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
521 Spawn *spawn = userdata;
4375dab5 522 char timeout[FORMAT_TIMESPAN_MAX];
912541b0 523
8128f229 524 assert(spawn);
67117413 525
5ca3dbc9 526 log_warning("Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete", spawn->cmd, spawn->pid,
4375dab5 527 format_timespan(timeout, sizeof(timeout), spawn->timeout_warn_usec, USEC_PER_SEC));
8128f229
TG
528
529 return 1;
530}
531
532static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
533 Spawn *spawn = userdata;
a7521142 534 int ret = -EIO;
8128f229
TG
535
536 assert(spawn);
537
538 switch (si->si_code) {
539 case CLD_EXITED:
a7521142 540 if (si->si_status == 0)
53318514 541 log_debug("Process '%s' succeeded.", spawn->cmd);
a7521142
ZJS
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;
8128f229
TG
546 break;
547 case CLD_KILLED:
548 case CLD_DUMPED:
a7521142 549 log_error("Process '%s' terminated by signal %s.", spawn->cmd, signal_to_string(si->si_status));
8128f229
TG
550 break;
551 default:
53318514 552 log_error("Process '%s' failed due to unknown reason.", spawn->cmd);
8128f229 553 }
912541b0 554
a7521142 555 sd_event_exit(sd_event_source_get_event(s), ret);
8128f229
TG
556 return 1;
557}
558
e81c3a4c 559static int spawn_wait(Spawn *spawn) {
4afd3348 560 _cleanup_(sd_event_unrefp) sd_event *e = NULL;
a7521142 561 int r;
8128f229 562
e81c3a4c
YW
563 assert(spawn);
564
8128f229
TG
565 r = sd_event_new(&e);
566 if (r < 0)
567 return r;
568
e81c3a4c 569 if (spawn->timeout_usec > 0) {
8128f229
TG
570 usec_t usec, age_usec;
571
3285baa8 572 usec = now(CLOCK_MONOTONIC);
e81c3a4c
YW
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;
8128f229 579
3285baa8 580 r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
e81c3a4c
YW
581 usec + spawn->timeout_warn_usec, USEC_PER_SEC,
582 on_spawn_timeout_warning, spawn);
8128f229
TG
583 if (r < 0)
584 return r;
912541b0 585 }
8128f229 586
e81c3a4c 587 spawn->timeout_usec -= age_usec;
8128f229 588
3285baa8 589 r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
e81c3a4c 590 usec + spawn->timeout_usec, USEC_PER_SEC, on_spawn_timeout, spawn);
8128f229
TG
591 if (r < 0)
592 return r;
912541b0
KS
593 }
594 }
8128f229 595
adeb26c1
YW
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 }
e81c3a4c 601
adeb26c1
YW
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 }
e81c3a4c
YW
607
608 r = sd_event_add_child(e, NULL, spawn->pid, WEXITED, on_spawn_sigchld, spawn);
8128f229
TG
609 if (r < 0)
610 return r;
611
a7521142 612 return sd_event_loop(e);
2181d30a
KS
613}
614
2e088715 615int udev_event_spawn(UdevEvent *event,
dd5eddd2 616 usec_t timeout_usec,
53318514 617 bool accept_failure,
bbf35206 618 const char *cmd,
dd5eddd2 619 char *result, size_t ressize) {
feaa6db7
YW
620 _cleanup_close_pair_ int outpipe[2] = {-1, -1}, errpipe[2] = {-1, -1};
621 _cleanup_strv_free_ char **argv = NULL;
947ce772 622 char **envp = NULL;
e81c3a4c 623 Spawn spawn;
912541b0 624 pid_t pid;
feaa6db7 625 int r;
912541b0 626
dc8aec36
YW
627 assert(event);
628 assert(event->dev);
e81c3a4c
YW
629 assert(result || ressize == 0);
630
912541b0 631 /* pipes from child to parent */
2e48548f 632 if (result || log_get_max_level() >= LOG_INFO)
f71e8ec1 633 if (pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) != 0)
feaa6db7 634 return log_error_errno(errno, "Failed to create pipe for command '%s': %m", cmd);
912541b0 635
feaa6db7 636 if (log_get_max_level() >= LOG_INFO)
f71e8ec1 637 if (pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) != 0)
feaa6db7
YW
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
baaa35ad
ZJS
644 if (isempty(argv[0]))
645 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
646 "Invalid command '%s'", cmd);
dc8aec36 647
feaa6db7
YW
648 /* allow programs in /usr/lib/udev/ to be called without the path */
649 if (!path_is_absolute(argv[0])) {
650 char *program;
651
62a85ee0 652 program = path_join(UDEVLIBEXECDIR, argv[0]);
feaa6db7
YW
653 if (!program)
654 return log_oom();
bbf35206 655
feaa6db7
YW
656 free_and_replace(argv[0], program);
657 }
658
cf28ad46 659 r = device_get_properties_strv(event->dev, &envp);
947ce772 660 if (r < 0)
cf28ad46 661 return log_device_error_errno(event->dev, r, "Failed to get device properties");
947ce772 662
3ad4d482
YW
663 log_debug("Starting '%s'", cmd);
664
6ce075a2 665 r = safe_fork("(spawn)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
feaa6db7
YW
666 if (r < 0)
667 return log_error_errno(r, "Failed to fork() to execute command '%s': %m", cmd);
668 if (r == 0) {
84b1ccb9
YW
669 if (rearrange_stdio(-1, outpipe[WRITE_END], errpipe[WRITE_END]) < 0)
670 _exit(EXIT_FAILURE);
912541b0 671
84b1ccb9 672 (void) close_all_fds(NULL, 0);
595225af 673 (void) rlimit_nofile_safe();
912541b0 674
947ce772 675 execve(argv[0], argv, envp);
84b1ccb9 676 _exit(EXIT_FAILURE);
bbf35206 677 }
912541b0 678
4c253ed1
LP
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]);
912541b0 682
e81c3a4c
YW
683 spawn = (Spawn) {
684 .cmd = cmd,
685 .pid = pid,
686 .accept_failure = accept_failure,
66f737b4 687 .timeout_warn_usec = udev_warn_timeout(timeout_usec),
e81c3a4c
YW
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);
feaa6db7 696 if (r < 0)
a7521142 697 return log_error_errno(r, "Failed to wait for spawned command '%s': %m", cmd);
2181d30a 698
e81c3a4c
YW
699 if (result)
700 result[spawn.result_len] = '\0';
701
a7521142 702 return r; /* 0 for success, and positive if the program failed */
2181d30a
KS
703}
704
2e088715 705static int rename_netif(UdevEvent *event) {
cf28ad46 706 sd_device *dev = event->dev;
d4d690fa 707 const char *oldname;
2740750d
YW
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
d4d690fa 720 if (!device_for_action(dev, DEVICE_ACTION_ADD))
2740750d 721 return 0; /* Rename the interface only when it is added. */
16d26d55 722
2740750d
YW
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");
912541b0 728
589384be 729 r = rtnl_set_link_name(&event->rtnl, ifindex, event->name);
2740750d 730 if (r < 0)
589384be
YW
731 return log_device_error_errno(dev, r, "Failed to rename network interface %i from '%s' to '%s': %m",
732 ifindex, oldname, event->name);
912541b0 733
a4055a60
YW
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");
912541b0 738
2740750d 739 r = device_rename(dev, event->name);
f647962d 740 if (r < 0)
a4055a60 741 log_device_warning_errno(dev, r, "Failed to update properties with new name '%s': %m", event->name);
16d26d55 742
589384be 743 log_device_debug(dev, "Network interface %i is renamed from '%s' to '%s'", ifindex, oldname, event->name);
16d26d55 744
2740750d 745 return 1;
d46f37fd
KS
746}
747
2e088715 748static int update_devnode(UdevEvent *event) {
cf28ad46 749 sd_device *dev = event->dev;
e52eaf56
YW
750 bool apply;
751 int r;
752
7af1c780 753 r = sd_device_get_devnum(dev, NULL);
e52eaf56
YW
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 */
480ecb7d
YW
760 if (event->dev_db_clone)
761 (void) udev_node_update_old_links(dev, event->dev_db_clone);
e52eaf56 762
25de7aa7 763 if (!uid_is_valid(event->uid)) {
e52eaf56 764 r = device_get_devnode_uid(dev, &event->uid);
25de7aa7
YW
765 if (r == -ENOENT)
766 event->uid = 0;
767 else if (r < 0)
e52eaf56
YW
768 return log_device_error_errno(dev, r, "Failed to get devnode UID: %m");
769 }
770
25de7aa7 771 if (!gid_is_valid(event->gid)) {
e52eaf56 772 r = device_get_devnode_gid(dev, &event->gid);
25de7aa7
YW
773 if (r == -ENOENT)
774 event->gid = 0;
775 else if (r < 0)
e52eaf56
YW
776 return log_device_error_errno(dev, r, "Failed to get devnode GID: %m");
777 }
778
25de7aa7 779 if (event->mode == MODE_INVALID) {
e52eaf56
YW
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
25de7aa7
YW
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;
e52eaf56
YW
797 return udev_node_add(dev, apply, event->mode, event->uid, event->gid, event->seclabel_list);
798}
799
eb1f9e30 800static void event_execute_rules_on_remove(
2e088715 801 UdevEvent *event,
66f737b4 802 usec_t timeout_usec,
eb1f9e30 803 Hashmap *properties_list,
9a07157d 804 UdevRules *rules) {
912541b0 805
cf28ad46 806 sd_device *dev = event->dev;
eb1f9e30 807 int r;
912541b0 808
ebcc52fa 809 r = device_read_db_internal(dev, true);
eb1f9e30
YW
810 if (r < 0)
811 log_device_debug_errno(dev, r, "Failed to read database under /run/udev/data/: %m");
107f2e25 812
eb1f9e30
YW
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");
912541b0 816
eb1f9e30
YW
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");
912541b0 820
d4a95a95 821 if (sd_device_get_devnum(dev, NULL) >= 0)
eb1f9e30
YW
822 (void) udev_watch_end(dev);
823
66f737b4 824 (void) udev_rules_apply_to_event(rules, event, timeout_usec, properties_list);
eb1f9e30 825
d4a95a95 826 if (sd_device_get_devnum(dev, NULL) >= 0)
eb1f9e30
YW
827 (void) udev_node_remove(dev);
828}
829
a4055a60
YW
830static 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
2e088715 849int udev_event_execute_rules(UdevEvent *event,
66f737b4 850 usec_t timeout_usec,
eb1f9e30 851 Hashmap *properties_list,
9a07157d 852 UdevRules *rules) {
d4d690fa
YW
853 const char *subsystem;
854 DeviceAction action;
6d0fdf45 855 sd_device *dev;
eb1f9e30
YW
856 int r;
857
858 assert(event);
859 assert(rules);
860
6d0fdf45
YW
861 dev = event->dev;
862
eb1f9e30
YW
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
d4d690fa 867 r = device_get_action(dev, &action);
eb1f9e30 868 if (r < 0)
d4d690fa 869 return log_device_error_errno(dev, r, "Failed to get ACTION: %m");
b081b27e 870
d4d690fa 871 if (action == DEVICE_ACTION_REMOVE) {
66f737b4 872 event_execute_rules_on_remove(event, timeout_usec, properties_list, rules);
eb1f9e30
YW
873 return 0;
874 }
912541b0 875
480ecb7d 876 r = device_clone_with_db(dev, &event->dev_db_clone);
eb1f9e30
YW
877 if (r < 0)
878 log_device_debug_errno(dev, r, "Failed to clone sd_device object, ignoring: %m");
912541b0 879
a4055a60
YW
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);
912541b0 883
d4d690fa 884 if (action == DEVICE_ACTION_MOVE)
a4055a60 885 (void) udev_event_on_move(event);
eb1f9e30 886
66f737b4 887 (void) udev_rules_apply_to_event(rules, event, timeout_usec, properties_list);
eb1f9e30
YW
888
889 (void) rename_netif(event);
890 (void) update_devnode(event);
891
892 /* preserve old, or get new initialization timestamp */
480ecb7d 893 r = device_ensure_usec_initialized(dev, event->dev_db_clone);
eb1f9e30
YW
894 if (r < 0)
895 log_device_debug_errno(dev, r, "Failed to set initialization timestamp, ignoring: %m");
896
897 /* (re)write database file */
480ecb7d 898 r = device_tag_index(dev, event->dev_db_clone, true);
eb1f9e30
YW
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
480ecb7d 908 event->dev_db_clone = sd_device_unref(event->dev_db_clone);
eb1f9e30
YW
909
910 return 0;
d46f37fd 911}
2d73813e 912
2e088715 913void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec) {
29448498
YW
914 const char *cmd;
915 void *val;
916 Iterator i;
25de7aa7 917 int r;
912541b0 918
39a15c8a 919 ORDERED_HASHMAP_FOREACH_KEY(val, cmd, event->run_list, i) {
25de7aa7 920 UdevBuiltinCommand builtin_cmd = PTR_TO_UDEV_BUILTIN_CMD(val);
bbf35206 921 char command[UTIL_PATH_SIZE];
83cd6b75 922
25de7aa7 923 (void) udev_event_apply_format(event, cmd, command, sizeof(command), false);
912541b0 924
25de7aa7
YW
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 {
6b92f429 931 if (event->exec_delay_usec > 0) {
25de7aa7
YW
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));
6b92f429 936 (void) usleep(event->exec_delay_usec);
912541b0
KS
937 }
938
25de7aa7
YW
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);
912541b0
KS
943 }
944 }
2d73813e 945}