1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <net/if.h>
7 #include <stddef.h>
8 #include <stdlib.h>
9 #include <sys/wait.h>
10 #include <unistd.h>
11 
12 #include "sd-event.h"
13 
14 #include "alloc-util.h"
15 #include "device-private.h"
16 #include "device-util.h"
17 #include "fd-util.h"
18 #include "fs-util.h"
19 #include "format-util.h"
20 #include "netif-naming-scheme.h"
21 #include "netlink-util.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
25 #include "rlimit-util.h"
26 #include "signal-util.h"
27 #include "stdio-util.h"
28 #include "string-util.h"
29 #include "strv.h"
30 #include "strxcpyx.h"
31 #include "udev-builtin.h"
32 #include "udev-event.h"
33 #include "udev-netlink.h"
34 #include "udev-node.h"
35 #include "udev-util.h"
36 #include "udev-watch.h"
37 #include "user-util.h"
38 
39 typedef struct Spawn {
40         sd_device *device;
41         const char *cmd;
42         pid_t pid;
43         usec_t timeout_warn_usec;
44         usec_t timeout_usec;
45         int timeout_signal;
46         usec_t event_birth_usec;
47         bool accept_failure;
48         int fd_stdout;
49         int fd_stderr;
50         char *result;
51         size_t result_size;
52         size_t result_len;
53         bool truncated;
54 } Spawn;
55 
udev_event_new(sd_device * dev,usec_t exec_delay_usec,sd_netlink * rtnl,int log_level)56 UdevEvent *udev_event_new(sd_device *dev, usec_t exec_delay_usec, sd_netlink *rtnl, int log_level) {
57         UdevEvent *event;
58 
59         assert(dev);
60 
61         event = new(UdevEvent, 1);
62         if (!event)
63                 return NULL;
64 
65         *event = (UdevEvent) {
66                 .dev = sd_device_ref(dev),
67                 .birth_usec = now(CLOCK_MONOTONIC),
68                 .exec_delay_usec = exec_delay_usec,
69                 .rtnl = sd_netlink_ref(rtnl),
70                 .uid = UID_INVALID,
71                 .gid = GID_INVALID,
72                 .mode = MODE_INVALID,
73                 .log_level_was_debug = log_level == LOG_DEBUG,
74                 .default_log_level = log_level,
75         };
76 
77         return event;
78 }
79 
udev_event_free(UdevEvent * event)80 UdevEvent *udev_event_free(UdevEvent *event) {
81         if (!event)
82                 return NULL;
83 
84         sd_device_unref(event->dev);
85         sd_device_unref(event->dev_db_clone);
86         sd_netlink_unref(event->rtnl);
87         ordered_hashmap_free_free_key(event->run_list);
88         ordered_hashmap_free_free_free(event->seclabel_list);
89         free(event->program_result);
90         free(event->name);
91 
92         return mfree(event);
93 }
94 
95 typedef enum {
96         FORMAT_SUBST_DEVNODE,
97         FORMAT_SUBST_ATTR,
98         FORMAT_SUBST_ENV,
99         FORMAT_SUBST_KERNEL,
100         FORMAT_SUBST_KERNEL_NUMBER,
101         FORMAT_SUBST_DRIVER,
102         FORMAT_SUBST_DEVPATH,
103         FORMAT_SUBST_ID,
104         FORMAT_SUBST_MAJOR,
105         FORMAT_SUBST_MINOR,
106         FORMAT_SUBST_RESULT,
107         FORMAT_SUBST_PARENT,
108         FORMAT_SUBST_NAME,
109         FORMAT_SUBST_LINKS,
110         FORMAT_SUBST_ROOT,
111         FORMAT_SUBST_SYS,
112         _FORMAT_SUBST_TYPE_MAX,
113         _FORMAT_SUBST_TYPE_INVALID = -EINVAL,
114 } FormatSubstitutionType;
115 
116 struct subst_map_entry {
117         const char *name;
118         const char fmt;
119         FormatSubstitutionType type;
120 };
121 
122 static const struct subst_map_entry map[] = {
123            { .name = "devnode",  .fmt = 'N', .type = FORMAT_SUBST_DEVNODE },
124            { .name = "tempnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE }, /* deprecated */
125            { .name = "attr",     .fmt = 's', .type = FORMAT_SUBST_ATTR },
126            { .name = "sysfs",    .fmt = 's', .type = FORMAT_SUBST_ATTR }, /* deprecated */
127            { .name = "env",      .fmt = 'E', .type = FORMAT_SUBST_ENV },
128            { .name = "kernel",   .fmt = 'k', .type = FORMAT_SUBST_KERNEL },
129            { .name = "number",   .fmt = 'n', .type = FORMAT_SUBST_KERNEL_NUMBER },
130            { .name = "driver",   .fmt = 'd', .type = FORMAT_SUBST_DRIVER },
131            { .name = "devpath",  .fmt = 'p', .type = FORMAT_SUBST_DEVPATH },
132            { .name = "id",       .fmt = 'b', .type = FORMAT_SUBST_ID },
133            { .name = "major",    .fmt = 'M', .type = FORMAT_SUBST_MAJOR },
134            { .name = "minor",    .fmt = 'm', .type = FORMAT_SUBST_MINOR },
135            { .name = "result",   .fmt = 'c', .type = FORMAT_SUBST_RESULT },
136            { .name = "parent",   .fmt = 'P', .type = FORMAT_SUBST_PARENT },
137            { .name = "name",     .fmt = 'D', .type = FORMAT_SUBST_NAME },
138            { .name = "links",    .fmt = 'L', .type = FORMAT_SUBST_LINKS },
139            { .name = "root",     .fmt = 'r', .type = FORMAT_SUBST_ROOT },
140            { .name = "sys",      .fmt = 'S', .type = FORMAT_SUBST_SYS },
141 };
142 
format_type_to_string(FormatSubstitutionType t)143 static const char *format_type_to_string(FormatSubstitutionType t) {
144         for (size_t i = 0; i < ELEMENTSOF(map); i++)
145                 if (map[i].type == t)
146                         return map[i].name;
147         return NULL;
148 }
149 
format_type_to_char(FormatSubstitutionType t)150 static char format_type_to_char(FormatSubstitutionType t) {
151         for (size_t i = 0; i < ELEMENTSOF(map); i++)
152                 if (map[i].type == t)
153                         return map[i].fmt;
154         return '\0';
155 }
156 
get_subst_type(const char ** str,bool strict,FormatSubstitutionType * ret_type,char ret_attr[static UDEV_PATH_SIZE])157 static int get_subst_type(const char **str, bool strict, FormatSubstitutionType *ret_type, char ret_attr[static UDEV_PATH_SIZE]) {
158         const char *p = *str, *q = NULL;
159         size_t i;
160 
161         assert(str);
162         assert(*str);
163         assert(ret_type);
164         assert(ret_attr);
165 
166         if (*p == '$') {
167                 p++;
168                 if (*p == '$') {
169                         *str = p;
170                         return 0;
171                 }
172                 for (i = 0; i < ELEMENTSOF(map); i++)
173                         if ((q = startswith(p, map[i].name)))
174                                 break;
175         } else if (*p == '%') {
176                 p++;
177                 if (*p == '%') {
178                         *str = p;
179                         return 0;
180                 }
181 
182                 for (i = 0; i < ELEMENTSOF(map); i++)
183                         if (*p == map[i].fmt) {
184                                 q = p + 1;
185                                 break;
186                         }
187         } else
188                 return 0;
189         if (!q)
190                 /* When 'strict' flag is set, then '$' and '%' must be escaped. */
191                 return strict ? -EINVAL : 0;
192 
193         if (*q == '{') {
194                 const char *start, *end;
195                 size_t len;
196 
197                 start = q + 1;
198                 end = strchr(start, '}');
199                 if (!end)
200                         return -EINVAL;
201 
202                 len = end - start;
203                 if (len == 0 || len >= UDEV_PATH_SIZE)
204                         return -EINVAL;
205 
206                 strnscpy(ret_attr, UDEV_PATH_SIZE, start, len);
207                 q = end + 1;
208         } else
209                 *ret_attr = '\0';
210 
211         *str = q;
212         *ret_type = map[i].type;
213         return 1;
214 }
215 
safe_atou_optional_plus(const char * s,unsigned * ret)216 static int safe_atou_optional_plus(const char *s, unsigned *ret) {
217         const char *p;
218         int r;
219 
220         assert(s);
221         assert(ret);
222 
223         /* Returns 1 if plus, 0 if no plus, negative on error */
224 
225         p = endswith(s, "+");
226         if (p)
227                 s = strndupa_safe(s, p - s);
228 
229         r = safe_atou(s, ret);
230         if (r < 0)
231                 return r;
232 
233         return !!p;
234 }
235 
udev_event_subst_format(UdevEvent * event,FormatSubstitutionType type,const char * attr,char * dest,size_t l,bool * ret_truncated)236 static ssize_t udev_event_subst_format(
237                 UdevEvent *event,
238                 FormatSubstitutionType type,
239                 const char *attr,
240                 char *dest,
241                 size_t l,
242                 bool *ret_truncated) {
243 
244         sd_device *parent, *dev = event->dev;
245         const char *val = NULL;
246         bool truncated = false;
247         char *s = dest;
248         int r;
249 
250         switch (type) {
251         case FORMAT_SUBST_DEVPATH:
252                 r = sd_device_get_devpath(dev, &val);
253                 if (r < 0)
254                         return r;
255                 strpcpy_full(&s, l, val, &truncated);
256                 break;
257         case FORMAT_SUBST_KERNEL:
258                 r = sd_device_get_sysname(dev, &val);
259                 if (r < 0)
260                         return r;
261                 strpcpy_full(&s, l, val, &truncated);
262                 break;
263         case FORMAT_SUBST_KERNEL_NUMBER:
264                 r = sd_device_get_sysnum(dev, &val);
265                 if (r == -ENOENT)
266                         goto null_terminate;
267                 if (r < 0)
268                         return r;
269                 strpcpy_full(&s, l, val, &truncated);
270                 break;
271         case FORMAT_SUBST_ID:
272                 if (!event->dev_parent)
273                         goto null_terminate;
274                 r = sd_device_get_sysname(event->dev_parent, &val);
275                 if (r < 0)
276                         return r;
277                 strpcpy_full(&s, l, val, &truncated);
278                 break;
279         case FORMAT_SUBST_DRIVER:
280                 if (!event->dev_parent)
281                         goto null_terminate;
282                 r = sd_device_get_driver(event->dev_parent, &val);
283                 if (r == -ENOENT)
284                         goto null_terminate;
285                 if (r < 0)
286                         return r;
287                 strpcpy_full(&s, l, val, &truncated);
288                 break;
289         case FORMAT_SUBST_MAJOR:
290         case FORMAT_SUBST_MINOR: {
291                 dev_t devnum;
292 
293                 r = sd_device_get_devnum(dev, &devnum);
294                 if (r < 0 && r != -ENOENT)
295                         return r;
296                 strpcpyf_full(&s, l, &truncated, "%u", r < 0 ? 0 : type == FORMAT_SUBST_MAJOR ? major(devnum) : minor(devnum));
297                 break;
298         }
299         case FORMAT_SUBST_RESULT: {
300                 unsigned index = 0; /* 0 means whole string */
301                 bool has_plus;
302 
303                 if (!event->program_result)
304                         goto null_terminate;
305 
306                 if (!isempty(attr)) {
307                         r = safe_atou_optional_plus(attr, &index);
308                         if (r < 0)
309                                 return r;
310 
311                         has_plus = r;
312                 }
313 
314                 if (index == 0)
315                         strpcpy_full(&s, l, event->program_result, &truncated);
316                 else {
317                         const char *start, *p;
318                         unsigned i;
319 
320                         p = skip_leading_chars(event->program_result, NULL);
321 
322                         for (i = 1; i < index; i++) {
323                                 while (*p && !strchr(WHITESPACE, *p))
324                                         p++;
325                                 p = skip_leading_chars(p, NULL);
326                                 if (*p == '\0')
327                                         break;
328                         }
329                         if (i != index) {
330                                 log_device_debug(dev, "requested part of result string not found");
331                                 goto null_terminate;
332                         }
333 
334                         start = p;
335                         /* %c{2+} copies the whole string from the second part on */
336                         if (has_plus)
337                                 strpcpy_full(&s, l, start, &truncated);
338                         else {
339                                 while (*p && !strchr(WHITESPACE, *p))
340                                         p++;
341                                 strnpcpy_full(&s, l, start, p - start, &truncated);
342                         }
343                 }
344                 break;
345         }
346         case FORMAT_SUBST_ATTR: {
347                 char vbuf[UDEV_NAME_SIZE];
348                 int count;
349                 bool t;
350 
351                 if (isempty(attr))
352                         return -EINVAL;
353 
354                 /* try to read the value specified by "[dmi/id]product_name" */
355                 if (udev_resolve_subsys_kernel(attr, vbuf, sizeof(vbuf), true) == 0)
356                         val = vbuf;
357 
358                 /* try to read the attribute the device */
359                 if (!val)
360                         (void) device_get_sysattr_value_maybe_from_netlink(dev, &event->rtnl, attr, &val);
361 
362                 /* try to read the attribute of the parent device, other matches have selected */
363                 if (!val && event->dev_parent && event->dev_parent != dev)
364                         (void) device_get_sysattr_value_maybe_from_netlink(event->dev_parent, &event->rtnl, attr, &val);
365 
366                 if (!val)
367                         goto null_terminate;
368 
369                 /* strip trailing whitespace, and replace unwanted characters */
370                 if (val != vbuf)
371                         strscpy_full(vbuf, sizeof(vbuf), val, &truncated);
372                 delete_trailing_chars(vbuf, NULL);
373                 count = udev_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
374                 if (count > 0)
375                         log_device_debug(dev, "%i character(s) replaced", count);
376                 strpcpy_full(&s, l, vbuf, &t);
377                 truncated = truncated || t;
378                 break;
379         }
380         case FORMAT_SUBST_PARENT:
381                 r = sd_device_get_parent(dev, &parent);
382                 if (r == -ENOENT)
383                         goto null_terminate;
384                 if (r < 0)
385                         return r;
386                 r = sd_device_get_devname(parent, &val);
387                 if (r == -ENOENT)
388                         goto null_terminate;
389                 if (r < 0)
390                         return r;
391                 strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
392                 break;
393         case FORMAT_SUBST_DEVNODE:
394                 r = sd_device_get_devname(dev, &val);
395                 if (r == -ENOENT)
396                         goto null_terminate;
397                 if (r < 0)
398                         return r;
399                 strpcpy_full(&s, l, val, &truncated);
400                 break;
401         case FORMAT_SUBST_NAME:
402                 if (event->name)
403                         strpcpy_full(&s, l, event->name, &truncated);
404                 else if (sd_device_get_devname(dev, &val) >= 0)
405                         strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
406                 else {
407                         r = sd_device_get_sysname(dev, &val);
408                         if (r < 0)
409                                 return r;
410                         strpcpy_full(&s, l, val, &truncated);
411                 }
412                 break;
413         case FORMAT_SUBST_LINKS:
414                 FOREACH_DEVICE_DEVLINK(dev, val) {
415                         if (s == dest)
416                                 strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
417                         else
418                                 strpcpyl_full(&s, l, &truncated, " ", val + STRLEN("/dev/"), NULL);
419                         if (truncated)
420                                 break;
421                 }
422                 if (s == dest)
423                         goto null_terminate;
424                 break;
425         case FORMAT_SUBST_ROOT:
426                 strpcpy_full(&s, l, "/dev", &truncated);
427                 break;
428         case FORMAT_SUBST_SYS:
429                 strpcpy_full(&s, l, "/sys", &truncated);
430                 break;
431         case FORMAT_SUBST_ENV:
432                 if (isempty(attr))
433                         return -EINVAL;
434                 r = sd_device_get_property_value(dev, attr, &val);
435                 if (r == -ENOENT)
436                         goto null_terminate;
437                 if (r < 0)
438                         return r;
439                 strpcpy_full(&s, l, val, &truncated);
440                 break;
441         default:
442                 assert_not_reached();
443         }
444 
445         if (ret_truncated)
446                 *ret_truncated = truncated;
447 
448         return s - dest;
449 
450 null_terminate:
451         if (ret_truncated)
452                 *ret_truncated = truncated;
453 
454         *s = '\0';
455         return 0;
456 }
457 
udev_event_apply_format(UdevEvent * event,const char * src,char * dest,size_t size,bool replace_whitespace,bool * ret_truncated)458 size_t udev_event_apply_format(
459                 UdevEvent *event,
460                 const char *src,
461                 char *dest,
462                 size_t size,
463                 bool replace_whitespace,
464                 bool *ret_truncated) {
465 
466         bool truncated = false;
467         const char *s = src;
468         int r;
469 
470         assert(event);
471         assert(event->dev);
472         assert(src);
473         assert(dest);
474         assert(size > 0);
475 
476         while (*s) {
477                 FormatSubstitutionType type;
478                 char attr[UDEV_PATH_SIZE];
479                 ssize_t subst_len;
480                 bool t;
481 
482                 r = get_subst_type(&s, false, &type, attr);
483                 if (r < 0) {
484                         log_device_warning_errno(event->dev, r, "Invalid format string, ignoring: %s", src);
485                         break;
486                 } else if (r == 0) {
487                         if (size < 2) {
488                                 /* need space for this char and the terminating NUL */
489                                 truncated = true;
490                                 break;
491                         }
492                         *dest++ = *s++;
493                         size--;
494                         continue;
495                 }
496 
497                 subst_len = udev_event_subst_format(event, type, attr, dest, size, &t);
498                 if (subst_len < 0) {
499                         log_device_warning_errno(event->dev, subst_len,
500                                                  "Failed to substitute variable '$%s' or apply format '%%%c', ignoring: %m",
501                                                  format_type_to_string(type), format_type_to_char(type));
502                         break;
503                 }
504 
505                 truncated = truncated || t;
506 
507                 /* FORMAT_SUBST_RESULT handles spaces itself */
508                 if (replace_whitespace && type != FORMAT_SUBST_RESULT)
509                         /* udev_replace_whitespace can replace in-place,
510                          * and does nothing if subst_len == 0 */
511                         subst_len = udev_replace_whitespace(dest, dest, subst_len);
512 
513                 dest += subst_len;
514                 size -= subst_len;
515         }
516 
517         assert(size >= 1);
518 
519         if (ret_truncated)
520                 *ret_truncated = truncated;
521 
522         *dest = '\0';
523         return size;
524 }
525 
udev_check_format(const char * value,size_t * offset,const char ** hint)526 int udev_check_format(const char *value, size_t *offset, const char **hint) {
527         FormatSubstitutionType type;
528         const char *s = value;
529         char attr[UDEV_PATH_SIZE];
530         int r;
531 
532         while (*s) {
533                 r = get_subst_type(&s, true, &type, attr);
534                 if (r < 0) {
535                         if (offset)
536                                 *offset = s - value;
537                         if (hint)
538                                 *hint = "invalid substitution type";
539                         return r;
540                 } else if (r == 0) {
541                         s++;
542                         continue;
543                 }
544 
545                 if (IN_SET(type, FORMAT_SUBST_ATTR, FORMAT_SUBST_ENV) && isempty(attr)) {
546                         if (offset)
547                                 *offset = s - value;
548                         if (hint)
549                                 *hint = "attribute value missing";
550                         return -EINVAL;
551                 }
552 
553                 if (type == FORMAT_SUBST_RESULT && !isempty(attr)) {
554                         unsigned i;
555 
556                         r = safe_atou_optional_plus(attr, &i);
557                         if (r < 0) {
558                                 if (offset)
559                                         *offset = s - value;
560                                 if (hint)
561                                         *hint = "attribute value not a valid number";
562                                 return r;
563                         }
564                 }
565         }
566 
567         return 0;
568 }
569 
on_spawn_io(sd_event_source * s,int fd,uint32_t revents,void * userdata)570 static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
571         Spawn *spawn = userdata;
572         char buf[4096], *p;
573         size_t size;
574         ssize_t l;
575         int r;
576 
577         assert(spawn);
578         assert(fd == spawn->fd_stdout || fd == spawn->fd_stderr);
579         assert(!spawn->result || spawn->result_len < spawn->result_size);
580 
581         if (fd == spawn->fd_stdout && spawn->result) {
582                 p = spawn->result + spawn->result_len;
583                 size = spawn->result_size - spawn->result_len;
584         } else {
585                 p = buf;
586                 size = sizeof(buf);
587         }
588 
589         l = read(fd, p, size - (p == buf));
590         if (l < 0) {
591                 if (errno == EAGAIN)
592                         goto reenable;
593 
594                 log_device_error_errno(spawn->device, errno,
595                                        "Failed to read stdout of '%s': %m", spawn->cmd);
596 
597                 return 0;
598         }
599 
600         if ((size_t) l == size) {
601                 log_device_warning(spawn->device, "Truncating stdout of '%s' up to %zu byte.",
602                                    spawn->cmd, spawn->result_size);
603                 l--;
604                 spawn->truncated = true;
605         }
606 
607         p[l] = '\0';
608         if (fd == spawn->fd_stdout && spawn->result)
609                 spawn->result_len += l;
610 
611         /* Log output only if we watch stderr. */
612         if (l > 0 && spawn->fd_stderr >= 0) {
613                 _cleanup_strv_free_ char **v = NULL;
614 
615                 r = strv_split_newlines_full(&v, p, EXTRACT_RETAIN_ESCAPE);
616                 if (r < 0)
617                         log_device_debug(spawn->device,
618                                          "Failed to split output from '%s'(%s), ignoring: %m",
619                                          spawn->cmd, fd == spawn->fd_stdout ? "out" : "err");
620 
621                 STRV_FOREACH(q, v)
622                         log_device_debug(spawn->device, "'%s'(%s) '%s'", spawn->cmd,
623                                          fd == spawn->fd_stdout ? "out" : "err", *q);
624         }
625 
626         if (l == 0 || spawn->truncated)
627                 return 0;
628 
629 reenable:
630         /* Re-enable the event source if we did not encounter EOF */
631 
632         r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
633         if (r < 0)
634                 log_device_error_errno(spawn->device, r,
635                                        "Failed to reactivate IO source of '%s'", spawn->cmd);
636         return 0;
637 }
638 
on_spawn_timeout(sd_event_source * s,uint64_t usec,void * userdata)639 static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
640         Spawn *spawn = userdata;
641 
642         assert(spawn);
643 
644         DEVICE_TRACE_POINT(spawn_timeout, spawn->device, spawn->cmd);
645 
646         kill_and_sigcont(spawn->pid, spawn->timeout_signal);
647 
648         log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing",
649                          spawn->cmd, spawn->pid,
650                          FORMAT_TIMESPAN(spawn->timeout_usec, USEC_PER_SEC));
651 
652         return 1;
653 }
654 
on_spawn_timeout_warning(sd_event_source * s,uint64_t usec,void * userdata)655 static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
656         Spawn *spawn = userdata;
657 
658         assert(spawn);
659 
660         log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete",
661                            spawn->cmd, spawn->pid,
662                            FORMAT_TIMESPAN(spawn->timeout_warn_usec, USEC_PER_SEC));
663 
664         return 1;
665 }
666 
on_spawn_sigchld(sd_event_source * s,const siginfo_t * si,void * userdata)667 static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
668         Spawn *spawn = userdata;
669         int ret = -EIO;
670 
671         assert(spawn);
672 
673         switch (si->si_code) {
674         case CLD_EXITED:
675                 if (si->si_status == 0)
676                         log_device_debug(spawn->device, "Process '%s' succeeded.", spawn->cmd);
677                 else
678                         log_device_full(spawn->device, spawn->accept_failure ? LOG_DEBUG : LOG_WARNING,
679                                         "Process '%s' failed with exit code %i.", spawn->cmd, si->si_status);
680                 ret = si->si_status;
681                 break;
682         case CLD_KILLED:
683         case CLD_DUMPED:
684                 log_device_error(spawn->device, "Process '%s' terminated by signal %s.", spawn->cmd, signal_to_string(si->si_status));
685                 break;
686         default:
687                 log_device_error(spawn->device, "Process '%s' failed due to unknown reason.", spawn->cmd);
688         }
689 
690         DEVICE_TRACE_POINT(spawn_exit, spawn->device, spawn->cmd);
691 
692         sd_event_exit(sd_event_source_get_event(s), ret);
693         return 1;
694 }
695 
spawn_wait(Spawn * spawn)696 static int spawn_wait(Spawn *spawn) {
697         _cleanup_(sd_event_unrefp) sd_event *e = NULL;
698         _cleanup_(sd_event_source_disable_unrefp) sd_event_source *sigchld_source = NULL;
699         _cleanup_(sd_event_source_disable_unrefp) sd_event_source *stdout_source = NULL;
700         _cleanup_(sd_event_source_disable_unrefp) sd_event_source *stderr_source = NULL;
701         int r;
702 
703         assert(spawn);
704 
705         r = sd_event_new(&e);
706         if (r < 0)
707                 return log_device_debug_errno(spawn->device, r, "Failed to allocate sd-event object: %m");
708 
709         if (spawn->timeout_usec > 0) {
710                 usec_t usec, age_usec;
711 
712                 usec = now(CLOCK_MONOTONIC);
713                 age_usec = usec - spawn->event_birth_usec;
714                 if (age_usec < spawn->timeout_usec) {
715                         if (spawn->timeout_warn_usec > 0 &&
716                             spawn->timeout_warn_usec < spawn->timeout_usec &&
717                             spawn->timeout_warn_usec > age_usec) {
718                                 spawn->timeout_warn_usec -= age_usec;
719 
720                                 r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
721                                                       usec + spawn->timeout_warn_usec, USEC_PER_SEC,
722                                                       on_spawn_timeout_warning, spawn);
723                                 if (r < 0)
724                                         return log_device_debug_errno(spawn->device, r, "Failed to create timeout warning event source: %m");
725                         }
726 
727                         spawn->timeout_usec -= age_usec;
728 
729                         r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
730                                               usec + spawn->timeout_usec, USEC_PER_SEC, on_spawn_timeout, spawn);
731                         if (r < 0)
732                                 return log_device_debug_errno(spawn->device, r, "Failed to create timeout event source: %m");
733                 }
734         }
735 
736         if (spawn->fd_stdout >= 0) {
737                 r = sd_event_add_io(e, &stdout_source, spawn->fd_stdout, EPOLLIN, on_spawn_io, spawn);
738                 if (r < 0)
739                         return log_device_debug_errno(spawn->device, r, "Failed to create stdio event source: %m");
740                 r = sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT);
741                 if (r < 0)
742                         return log_device_debug_errno(spawn->device, r, "Failed to enable stdio event source: %m");
743         }
744 
745         if (spawn->fd_stderr >= 0) {
746                 r = sd_event_add_io(e, &stderr_source, spawn->fd_stderr, EPOLLIN, on_spawn_io, spawn);
747                 if (r < 0)
748                         return log_device_debug_errno(spawn->device, r, "Failed to create stderr event source: %m");
749                 r = sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT);
750                 if (r < 0)
751                         return log_device_debug_errno(spawn->device, r, "Failed to enable stderr event source: %m");
752         }
753 
754         r = sd_event_add_child(e, &sigchld_source, spawn->pid, WEXITED, on_spawn_sigchld, spawn);
755         if (r < 0)
756                 return log_device_debug_errno(spawn->device, r, "Failed to create sigchild event source: %m");
757         /* SIGCHLD should be processed after IO is complete */
758         r = sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1);
759         if (r < 0)
760                 return log_device_debug_errno(spawn->device, r, "Failed to set priority to sigchild event source: %m");
761 
762         return sd_event_loop(e);
763 }
764 
udev_event_spawn(UdevEvent * event,usec_t timeout_usec,int timeout_signal,bool accept_failure,const char * cmd,char * result,size_t ressize,bool * ret_truncated)765 int udev_event_spawn(
766                 UdevEvent *event,
767                 usec_t timeout_usec,
768                 int timeout_signal,
769                 bool accept_failure,
770                 const char *cmd,
771                 char *result,
772                 size_t ressize,
773                 bool *ret_truncated) {
774 
775         _cleanup_close_pair_ int outpipe[2] = {-1, -1}, errpipe[2] = {-1, -1};
776         _cleanup_strv_free_ char **argv = NULL;
777         char **envp = NULL;
778         Spawn spawn;
779         pid_t pid;
780         int r;
781 
782         assert(event);
783         assert(event->dev);
784         assert(result || ressize == 0);
785 
786         /* pipes from child to parent */
787         if (result || log_get_max_level() >= LOG_INFO)
788                 if (pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) != 0)
789                         return log_device_error_errno(event->dev, errno,
790                                                       "Failed to create pipe for command '%s': %m", cmd);
791 
792         if (log_get_max_level() >= LOG_INFO)
793                 if (pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) != 0)
794                         return log_device_error_errno(event->dev, errno,
795                                                       "Failed to create pipe for command '%s': %m", cmd);
796 
797         r = strv_split_full(&argv, cmd, NULL, EXTRACT_UNQUOTE | EXTRACT_RELAX | EXTRACT_RETAIN_ESCAPE);
798         if (r < 0)
799                 return log_device_error_errno(event->dev, r, "Failed to split command: %m");
800 
801         if (isempty(argv[0]))
802                 return log_device_error_errno(event->dev, SYNTHETIC_ERRNO(EINVAL),
803                                               "Invalid command '%s'", cmd);
804 
805         /* allow programs in /usr/lib/udev/ to be called without the path */
806         if (!path_is_absolute(argv[0])) {
807                 char *program;
808 
809                 program = path_join(UDEVLIBEXECDIR, argv[0]);
810                 if (!program)
811                         return log_oom();
812 
813                 free_and_replace(argv[0], program);
814         }
815 
816         r = device_get_properties_strv(event->dev, &envp);
817         if (r < 0)
818                 return log_device_error_errno(event->dev, r, "Failed to get device properties");
819 
820         log_device_debug(event->dev, "Starting '%s'", cmd);
821 
822         r = safe_fork("(spawn)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &pid);
823         if (r < 0)
824                 return log_device_error_errno(event->dev, r,
825                                               "Failed to fork() to execute command '%s': %m", cmd);
826         if (r == 0) {
827                 if (rearrange_stdio(-1, TAKE_FD(outpipe[WRITE_END]), TAKE_FD(errpipe[WRITE_END])) < 0)
828                         _exit(EXIT_FAILURE);
829 
830                 (void) close_all_fds(NULL, 0);
831                 (void) rlimit_nofile_safe();
832 
833                 DEVICE_TRACE_POINT(spawn_exec, event->dev, cmd);
834 
835                 execve(argv[0], argv, envp);
836                 _exit(EXIT_FAILURE);
837         }
838 
839         /* parent closed child's ends of pipes */
840         outpipe[WRITE_END] = safe_close(outpipe[WRITE_END]);
841         errpipe[WRITE_END] = safe_close(errpipe[WRITE_END]);
842 
843         spawn = (Spawn) {
844                 .device = event->dev,
845                 .cmd = cmd,
846                 .pid = pid,
847                 .accept_failure = accept_failure,
848                 .timeout_warn_usec = udev_warn_timeout(timeout_usec),
849                 .timeout_usec = timeout_usec,
850                 .timeout_signal = timeout_signal,
851                 .event_birth_usec = event->birth_usec,
852                 .fd_stdout = outpipe[READ_END],
853                 .fd_stderr = errpipe[READ_END],
854                 .result = result,
855                 .result_size = ressize,
856         };
857         r = spawn_wait(&spawn);
858         if (r < 0)
859                 return log_device_error_errno(event->dev, r,
860                                               "Failed to wait for spawned command '%s': %m", cmd);
861 
862         if (result)
863                 result[spawn.result_len] = '\0';
864 
865         if (ret_truncated)
866                 *ret_truncated = spawn.truncated;
867 
868         return r; /* 0 for success, and positive if the program failed */
869 }
870 
rename_netif(UdevEvent * event)871 static int rename_netif(UdevEvent *event) {
872         const char *oldname;
873         sd_device *dev;
874         unsigned flags;
875         int ifindex, r;
876 
877         assert(event);
878 
879         if (!event->name)
880                 return 0; /* No new name is requested. */
881 
882         dev = ASSERT_PTR(event->dev);
883 
884         /* Read sysname from cloned sd-device object, otherwise use-after-free is triggered, as the
885          * main object will be renamed and dev->sysname will be freed in device_rename(). */
886         r = sd_device_get_sysname(event->dev_db_clone, &oldname);
887         if (r < 0)
888                 return log_device_error_errno(dev, r, "Failed to get sysname: %m");
889 
890         if (streq(event->name, oldname))
891                 return 0; /* The interface name is already requested name. */
892 
893         if (!device_for_action(dev, SD_DEVICE_ADD))
894                 return 0; /* Rename the interface only when it is added. */
895 
896         r = sd_device_get_ifindex(dev, &ifindex);
897         if (r == -ENOENT)
898                 return 0; /* Device is not a network interface. */
899         if (r < 0)
900                 return log_device_error_errno(dev, r, "Failed to get ifindex: %m");
901 
902         if (naming_scheme_has(NAMING_REPLACE_STRICTLY) &&
903             !ifname_valid(event->name)) {
904                 log_device_warning(dev, "Invalid network interface name, ignoring: %s", event->name);
905                 return 0;
906         }
907 
908         r = rtnl_get_link_info(&event->rtnl, ifindex, NULL, &flags, NULL, NULL, NULL);
909         if (r < 0)
910                 return log_device_warning_errno(dev, r, "Failed to get link flags: %m");
911 
912         if (FLAGS_SET(flags, IFF_UP)) {
913                 log_device_info(dev, "Network interface '%s' is already up, refusing to rename to '%s'.",
914                                 oldname, event->name);
915                 return 0;
916         }
917 
918         /* Set ID_RENAMING boolean property here, and drop it in the corresponding move uevent later. */
919         r = device_add_property(dev, "ID_RENAMING", "1");
920         if (r < 0)
921                 return log_device_warning_errno(dev, r, "Failed to add 'ID_RENAMING' property: %m");
922 
923         r = device_rename(dev, event->name);
924         if (r < 0)
925                 return log_device_warning_errno(dev, r, "Failed to update properties with new name '%s': %m", event->name);
926 
927         /* Also set ID_RENAMING boolean property to cloned sd_device object and save it to database
928          * before calling rtnl_set_link_name(). Otherwise, clients (e.g., systemd-networkd) may receive
929          * RTM_NEWLINK netlink message before the database is updated. */
930         r = device_add_property(event->dev_db_clone, "ID_RENAMING", "1");
931         if (r < 0)
932                 return log_device_warning_errno(event->dev_db_clone, r, "Failed to add 'ID_RENAMING' property: %m");
933 
934         r = device_update_db(event->dev_db_clone);
935         if (r < 0)
936                 return log_device_debug_errno(event->dev_db_clone, r, "Failed to update database under /run/udev/data/: %m");
937 
938         r = rtnl_set_link_name(&event->rtnl, ifindex, event->name);
939         if (r < 0)
940                 return log_device_error_errno(dev, r, "Failed to rename network interface %i from '%s' to '%s': %m",
941                                               ifindex, oldname, event->name);
942 
943         log_device_debug(dev, "Network interface %i is renamed from '%s' to '%s'", ifindex, oldname, event->name);
944 
945         return 1;
946 }
947 
update_devnode(UdevEvent * event)948 static int update_devnode(UdevEvent *event) {
949         sd_device *dev = event->dev;
950         int r;
951 
952         r = sd_device_get_devnum(dev, NULL);
953         if (r == -ENOENT)
954                 return 0;
955         if (r < 0)
956                 return log_device_error_errno(dev, r, "Failed to get devnum: %m");
957 
958         if (!uid_is_valid(event->uid)) {
959                 r = device_get_devnode_uid(dev, &event->uid);
960                 if (r < 0 && r != -ENOENT)
961                         return log_device_error_errno(dev, r, "Failed to get devnode UID: %m");
962         }
963 
964         if (!gid_is_valid(event->gid)) {
965                 r = device_get_devnode_gid(dev, &event->gid);
966                 if (r < 0 && r != -ENOENT)
967                         return log_device_error_errno(dev, r, "Failed to get devnode GID: %m");
968         }
969 
970         if (event->mode == MODE_INVALID) {
971                 r = device_get_devnode_mode(dev, &event->mode);
972                 if (r < 0 && r != -ENOENT)
973                         return log_device_error_errno(dev, r, "Failed to get devnode mode: %m");
974         }
975 
976         bool apply_mac = device_for_action(dev, SD_DEVICE_ADD);
977 
978         r = udev_node_apply_permissions(dev, apply_mac, event->mode, event->uid, event->gid, event->seclabel_list);
979         if (r < 0)
980                 return log_device_error_errno(dev, r, "Failed to apply devnode permissions: %m");
981 
982         return udev_node_update(dev, event->dev_db_clone);
983 }
984 
event_execute_rules_on_remove(UdevEvent * event,int inotify_fd,usec_t timeout_usec,int timeout_signal,Hashmap * properties_list,UdevRules * rules)985 static int event_execute_rules_on_remove(
986                 UdevEvent *event,
987                 int inotify_fd,
988                 usec_t timeout_usec,
989                 int timeout_signal,
990                 Hashmap *properties_list,
991                 UdevRules *rules) {
992 
993         sd_device *dev = event->dev;
994         int r;
995 
996         r = device_read_db_internal(dev, true);
997         if (r < 0)
998                 log_device_debug_errno(dev, r, "Failed to read database under /run/udev/data/: %m");
999 
1000         r = device_tag_index(dev, NULL, false);
1001         if (r < 0)
1002                 log_device_debug_errno(dev, r, "Failed to remove corresponding tag files under /run/udev/tag/, ignoring: %m");
1003 
1004         r = device_delete_db(dev);
1005         if (r < 0)
1006                 log_device_debug_errno(dev, r, "Failed to delete database under /run/udev/data/, ignoring: %m");
1007 
1008         (void) udev_watch_end(inotify_fd, dev);
1009 
1010         r = udev_rules_apply_to_event(rules, event, timeout_usec, timeout_signal, properties_list);
1011 
1012         if (sd_device_get_devnum(dev, NULL) >= 0)
1013                 (void) udev_node_remove(dev);
1014 
1015         return r;
1016 }
1017 
udev_event_on_move(sd_device * dev)1018 static int udev_event_on_move(sd_device *dev) {
1019         int r;
1020 
1021         /* Drop previously added property */
1022         r = device_add_property(dev, "ID_RENAMING", NULL);
1023         if (r < 0)
1024                 return log_device_debug_errno(dev, r, "Failed to remove 'ID_RENAMING' property: %m");
1025 
1026         return 0;
1027 }
1028 
copy_all_tags(sd_device * d,sd_device * s)1029 static int copy_all_tags(sd_device *d, sd_device *s) {
1030         const char *tag;
1031         int r;
1032 
1033         assert(d);
1034 
1035         if (!s)
1036                 return 0;
1037 
1038         FOREACH_DEVICE_TAG(s, tag) {
1039                 r = device_add_tag(d, tag, false);
1040                 if (r < 0)
1041                         return r;
1042         }
1043 
1044         return 0;
1045 }
1046 
udev_event_execute_rules(UdevEvent * event,int inotify_fd,usec_t timeout_usec,int timeout_signal,Hashmap * properties_list,UdevRules * rules)1047 int udev_event_execute_rules(
1048                 UdevEvent *event,
1049                 int inotify_fd, /* This may be negative */
1050                 usec_t timeout_usec,
1051                 int timeout_signal,
1052                 Hashmap *properties_list,
1053                 UdevRules *rules) {
1054 
1055         sd_device_action_t action;
1056         sd_device *dev;
1057         int r;
1058 
1059         assert(event);
1060         assert(rules);
1061 
1062         dev = event->dev;
1063 
1064         r = sd_device_get_action(dev, &action);
1065         if (r < 0)
1066                 return log_device_error_errno(dev, r, "Failed to get ACTION: %m");
1067 
1068         if (action == SD_DEVICE_REMOVE)
1069                 return event_execute_rules_on_remove(event, inotify_fd, timeout_usec, timeout_signal, properties_list, rules);
1070 
1071         /* Disable watch during event processing. */
1072         (void) udev_watch_end(inotify_fd, event->dev);
1073 
1074         r = device_clone_with_db(dev, &event->dev_db_clone);
1075         if (r < 0)
1076                 return log_device_debug_errno(dev, r, "Failed to clone sd_device object: %m");
1077 
1078         r = copy_all_tags(dev, event->dev_db_clone);
1079         if (r < 0)
1080                 log_device_warning_errno(dev, r, "Failed to copy all tags from old database entry, ignoring: %m");
1081 
1082         if (action == SD_DEVICE_MOVE) {
1083                 r = udev_event_on_move(event->dev);
1084                 if (r < 0)
1085                         return r;
1086         }
1087 
1088         DEVICE_TRACE_POINT(rules_start, dev);
1089 
1090         r = udev_rules_apply_to_event(rules, event, timeout_usec, timeout_signal, properties_list);
1091         if (r < 0)
1092                 return log_device_debug_errno(dev, r, "Failed to apply udev rules: %m");
1093 
1094         DEVICE_TRACE_POINT(rules_finished, dev);
1095 
1096         r = rename_netif(event);
1097         if (r < 0)
1098                 return r;
1099 
1100         r = update_devnode(event);
1101         if (r < 0)
1102                 return r;
1103 
1104         /* preserve old, or get new initialization timestamp */
1105         r = device_ensure_usec_initialized(dev, event->dev_db_clone);
1106         if (r < 0)
1107                 return log_device_debug_errno(dev, r, "Failed to set initialization timestamp: %m");
1108 
1109         /* (re)write database file */
1110         r = device_tag_index(dev, event->dev_db_clone, true);
1111         if (r < 0)
1112                 return log_device_debug_errno(dev, r, "Failed to update tags under /run/udev/tag/: %m");
1113 
1114         r = device_update_db(dev);
1115         if (r < 0)
1116                 return log_device_debug_errno(dev, r, "Failed to update database under /run/udev/data/: %m");
1117 
1118         device_set_is_initialized(dev);
1119 
1120         return 0;
1121 }
1122 
udev_event_execute_run(UdevEvent * event,usec_t timeout_usec,int timeout_signal)1123 void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal) {
1124         const char *command;
1125         void *val;
1126         int r;
1127 
1128         ORDERED_HASHMAP_FOREACH_KEY(val, command, event->run_list) {
1129                 UdevBuiltinCommand builtin_cmd = PTR_TO_UDEV_BUILTIN_CMD(val);
1130 
1131                 if (builtin_cmd != _UDEV_BUILTIN_INVALID) {
1132                         log_device_debug(event->dev, "Running built-in command \"%s\"", command);
1133                         r = udev_builtin_run(event->dev, &event->rtnl, builtin_cmd, command, false);
1134                         if (r < 0)
1135                                 log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command);
1136                 } else {
1137                         if (event->exec_delay_usec > 0) {
1138                                 log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.",
1139                                                  command, FORMAT_TIMESPAN(event->exec_delay_usec, USEC_PER_SEC));
1140                                 (void) usleep(event->exec_delay_usec);
1141                         }
1142 
1143                         log_device_debug(event->dev, "Running command \"%s\"", command);
1144 
1145                         r = udev_event_spawn(event, timeout_usec, timeout_signal, false, command, NULL, 0, NULL);
1146                         if (r < 0)
1147                                 log_device_warning_errno(event->dev, r, "Failed to execute '%s', ignoring: %m", command);
1148                         else if (r > 0) /* returned value is positive when program fails */
1149                                 log_device_debug(event->dev, "Command \"%s\" returned %d (error), ignoring.", command, r);
1150                 }
1151         }
1152 }
1153 
udev_event_process_inotify_watch(UdevEvent * event,int inotify_fd)1154 int udev_event_process_inotify_watch(UdevEvent *event, int inotify_fd) {
1155         sd_device *dev;
1156 
1157         assert(event);
1158         assert(inotify_fd >= 0);
1159 
1160         dev = event->dev;
1161 
1162         assert(dev);
1163 
1164         if (device_for_action(dev, SD_DEVICE_REMOVE))
1165                 return 0;
1166 
1167         if (event->inotify_watch)
1168                 (void) udev_watch_begin(inotify_fd, dev);
1169         else
1170                 (void) udev_watch_end(inotify_fd, dev);
1171 
1172         return 0;
1173 }
1174