]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
udev: split-out formatter and spawning commands from udev-event.c
authorYu Watanabe <watanabe.yu+github@gmail.com>
Tue, 18 Jul 2023 14:10:41 +0000 (23:10 +0900)
committerYu Watanabe <watanabe.yu+github@gmail.com>
Mon, 31 Jul 2023 14:23:00 +0000 (23:23 +0900)
No functional changes, just refactoring.

12 files changed:
src/test/udev-rule-runner.c
src/udev/meson.build
src/udev/test-udev-event.c
src/udev/udev-event.c
src/udev/udev-event.h
src/udev/udev-format.c [new file with mode: 0644]
src/udev/udev-format.h [new file with mode: 0644]
src/udev/udev-rules.c
src/udev/udev-spawn.c [new file with mode: 0644]
src/udev/udev-spawn.h [new file with mode: 0644]
src/udev/udevadm-test.c
src/udev/udevd.c

index fe854a3d2e6d46c11c03bd0b37ebe7ce9f11ea04..72296b3f0e69cbf0fc3b4edeabbe49cfbff53af9 100644 (file)
@@ -24,6 +24,7 @@
 #include "string-util.h"
 #include "tests.h"
 #include "udev-event.h"
+#include "udev-spawn.h"
 #include "version.h"
 
 static int device_new_from_synthetic_event(sd_device **ret, const char *syspath, const char *action) {
index 2e14867ba7a0318efea18b03a31c45bd767dc1f0..3dbda3cc2f3ac27d80095b38daa96398bf68e2f3 100644 (file)
@@ -21,8 +21,10 @@ libudevd_core_sources = files(
         'net/link-config.c',
         'udev-ctrl.c',
         'udev-event.c',
+        'udev-format.c',
         'udev-node.c',
         'udev-rules.c',
+        'udev-spawn.c',
         'udev-watch.c',
         'udev-builtin-btrfs.c',
         'udev-builtin-hwdb.c',
index 42f435916bd64916db656ddc76d2fc9a6dee3130..4f43facd8054b0c9a7d5e4f742c0707ee446795a 100644 (file)
@@ -5,6 +5,7 @@
 #include "strv.h"
 #include "tests.h"
 #include "udev-event.h"
+#include "udev-spawn.h"
 
 #define BUF_SIZE 1024
 
index 745f29a88f3443e96115a0338f9ac5e830913b2a..0876e478d818e250ef9aee92367d894b74490d10 100644 (file)
@@ -1,58 +1,21 @@
 /* SPDX-License-Identifier: GPL-2.0-or-later */
 
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <net/if.h>
-#include <stddef.h>
-#include <stdlib.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#include "sd-event.h"
-
 #include "alloc-util.h"
 #include "device-internal.h"
 #include "device-private.h"
 #include "device-util.h"
-#include "fd-util.h"
 #include "fs-util.h"
-#include "format-util.h"
 #include "netif-naming-scheme.h"
 #include "netlink-util.h"
-#include "parse-util.h"
 #include "path-util.h"
-#include "process-util.h"
-#include "signal-util.h"
-#include "stdio-util.h"
 #include "string-util.h"
 #include "strv.h"
-#include "strxcpyx.h"
-#include "udev-builtin.h"
 #include "udev-event.h"
 #include "udev-node.h"
 #include "udev-trace.h"
-#include "udev-util.h"
 #include "udev-watch.h"
 #include "user-util.h"
 
-typedef struct Spawn {
-        sd_device *device;
-        const char *cmd;
-        pid_t pid;
-        usec_t timeout_warn_usec;
-        usec_t timeout_usec;
-        int timeout_signal;
-        usec_t event_birth_usec;
-        bool accept_failure;
-        int fd_stdout;
-        int fd_stderr;
-        char *result;
-        size_t result_size;
-        size_t result_len;
-        bool truncated;
-} Spawn;
-
 UdevEvent *udev_event_new(sd_device *dev, usec_t exec_delay_usec, sd_netlink *rtnl, int log_level) {
         UdevEvent *event;
 
@@ -93,771 +56,6 @@ UdevEvent *udev_event_free(UdevEvent *event) {
         return mfree(event);
 }
 
-typedef enum {
-        FORMAT_SUBST_DEVNODE,
-        FORMAT_SUBST_ATTR,
-        FORMAT_SUBST_ENV,
-        FORMAT_SUBST_KERNEL,
-        FORMAT_SUBST_KERNEL_NUMBER,
-        FORMAT_SUBST_DRIVER,
-        FORMAT_SUBST_DEVPATH,
-        FORMAT_SUBST_ID,
-        FORMAT_SUBST_MAJOR,
-        FORMAT_SUBST_MINOR,
-        FORMAT_SUBST_RESULT,
-        FORMAT_SUBST_PARENT,
-        FORMAT_SUBST_NAME,
-        FORMAT_SUBST_LINKS,
-        FORMAT_SUBST_ROOT,
-        FORMAT_SUBST_SYS,
-        _FORMAT_SUBST_TYPE_MAX,
-        _FORMAT_SUBST_TYPE_INVALID = -EINVAL,
-} FormatSubstitutionType;
-
-struct subst_map_entry {
-        const char *name;
-        const char fmt;
-        FormatSubstitutionType type;
-};
-
-static const struct subst_map_entry map[] = {
-           { .name = "devnode",  .fmt = 'N', .type = FORMAT_SUBST_DEVNODE       },
-           { .name = "tempnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE       }, /* deprecated */
-           { .name = "attr",     .fmt = 's', .type = FORMAT_SUBST_ATTR          },
-           { .name = "sysfs",    .fmt = 's', .type = FORMAT_SUBST_ATTR          }, /* deprecated */
-           { .name = "env",      .fmt = 'E', .type = FORMAT_SUBST_ENV           },
-           { .name = "kernel",   .fmt = 'k', .type = FORMAT_SUBST_KERNEL        },
-           { .name = "number",   .fmt = 'n', .type = FORMAT_SUBST_KERNEL_NUMBER },
-           { .name = "driver",   .fmt = 'd', .type = FORMAT_SUBST_DRIVER        },
-           { .name = "devpath",  .fmt = 'p', .type = FORMAT_SUBST_DEVPATH       },
-           { .name = "id",       .fmt = 'b', .type = FORMAT_SUBST_ID            },
-           { .name = "major",    .fmt = 'M', .type = FORMAT_SUBST_MAJOR         },
-           { .name = "minor",    .fmt = 'm', .type = FORMAT_SUBST_MINOR         },
-           { .name = "result",   .fmt = 'c', .type = FORMAT_SUBST_RESULT        },
-           { .name = "parent",   .fmt = 'P', .type = FORMAT_SUBST_PARENT        },
-           { .name = "name",     .fmt = 'D', .type = FORMAT_SUBST_NAME          },
-           { .name = "links",    .fmt = 'L', .type = FORMAT_SUBST_LINKS         },
-           { .name = "root",     .fmt = 'r', .type = FORMAT_SUBST_ROOT          },
-           { .name = "sys",      .fmt = 'S', .type = FORMAT_SUBST_SYS           },
-};
-
-static const char *format_type_to_string(FormatSubstitutionType t) {
-        for (size_t i = 0; i < ELEMENTSOF(map); i++)
-                if (map[i].type == t)
-                        return map[i].name;
-        return NULL;
-}
-
-static char format_type_to_char(FormatSubstitutionType t) {
-        for (size_t i = 0; i < ELEMENTSOF(map); i++)
-                if (map[i].type == t)
-                        return map[i].fmt;
-        return '\0';
-}
-
-static int get_subst_type(const char **str, bool strict, FormatSubstitutionType *ret_type, char ret_attr[static UDEV_PATH_SIZE]) {
-        const char *p = *str, *q = NULL;
-        size_t i;
-
-        assert(str);
-        assert(*str);
-        assert(ret_type);
-        assert(ret_attr);
-
-        if (*p == '$') {
-                p++;
-                if (*p == '$') {
-                        *str = p;
-                        return 0;
-                }
-                for (i = 0; i < ELEMENTSOF(map); i++)
-                        if ((q = startswith(p, map[i].name)))
-                                break;
-        } else if (*p == '%') {
-                p++;
-                if (*p == '%') {
-                        *str = p;
-                        return 0;
-                }
-
-                for (i = 0; i < ELEMENTSOF(map); i++)
-                        if (*p == map[i].fmt) {
-                                q = p + 1;
-                                break;
-                        }
-        } else
-                return 0;
-        if (!q)
-                /* When 'strict' flag is set, then '$' and '%' must be escaped. */
-                return strict ? -EINVAL : 0;
-
-        if (*q == '{') {
-                const char *start, *end;
-                size_t len;
-
-                start = q + 1;
-                end = strchr(start, '}');
-                if (!end)
-                        return -EINVAL;
-
-                len = end - start;
-                if (len == 0 || len >= UDEV_PATH_SIZE)
-                        return -EINVAL;
-
-                strnscpy(ret_attr, UDEV_PATH_SIZE, start, len);
-                q = end + 1;
-        } else
-                *ret_attr = '\0';
-
-        *str = q;
-        *ret_type = map[i].type;
-        return 1;
-}
-
-static int safe_atou_optional_plus(const char *s, unsigned *ret) {
-        const char *p;
-        int r;
-
-        assert(s);
-        assert(ret);
-
-        /* Returns 1 if plus, 0 if no plus, negative on error */
-
-        p = endswith(s, "+");
-        if (p)
-                s = strndupa_safe(s, p - s);
-
-        r = safe_atou(s, ret);
-        if (r < 0)
-                return r;
-
-        return !!p;
-}
-
-static ssize_t udev_event_subst_format(
-                UdevEvent *event,
-                FormatSubstitutionType type,
-                const char *attr,
-                char *dest,
-                size_t l,
-                bool *ret_truncated) {
-
-        sd_device *parent, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
-        const char *val = NULL;
-        bool truncated = false;
-        char *s = dest;
-        int r;
-
-        switch (type) {
-        case FORMAT_SUBST_DEVPATH:
-                r = sd_device_get_devpath(dev, &val);
-                if (r < 0)
-                        return r;
-                strpcpy_full(&s, l, val, &truncated);
-                break;
-        case FORMAT_SUBST_KERNEL:
-                r = sd_device_get_sysname(dev, &val);
-                if (r < 0)
-                        return r;
-                strpcpy_full(&s, l, val, &truncated);
-                break;
-        case FORMAT_SUBST_KERNEL_NUMBER:
-                r = sd_device_get_sysnum(dev, &val);
-                if (r == -ENOENT)
-                        goto null_terminate;
-                if (r < 0)
-                        return r;
-                strpcpy_full(&s, l, val, &truncated);
-                break;
-        case FORMAT_SUBST_ID:
-                if (!event->dev_parent)
-                        goto null_terminate;
-                r = sd_device_get_sysname(event->dev_parent, &val);
-                if (r < 0)
-                        return r;
-                strpcpy_full(&s, l, val, &truncated);
-                break;
-        case FORMAT_SUBST_DRIVER:
-                if (!event->dev_parent)
-                        goto null_terminate;
-                r = sd_device_get_driver(event->dev_parent, &val);
-                if (r == -ENOENT)
-                        goto null_terminate;
-                if (r < 0)
-                        return r;
-                strpcpy_full(&s, l, val, &truncated);
-                break;
-        case FORMAT_SUBST_MAJOR:
-        case FORMAT_SUBST_MINOR: {
-                dev_t devnum;
-
-                r = sd_device_get_devnum(dev, &devnum);
-                if (r < 0 && r != -ENOENT)
-                        return r;
-                strpcpyf_full(&s, l, &truncated, "%u", r < 0 ? 0 : type == FORMAT_SUBST_MAJOR ? major(devnum) : minor(devnum));
-                break;
-        }
-        case FORMAT_SUBST_RESULT: {
-                unsigned index = 0; /* 0 means whole string */
-                bool has_plus;
-
-                if (!event->program_result)
-                        goto null_terminate;
-
-                if (!isempty(attr)) {
-                        r = safe_atou_optional_plus(attr, &index);
-                        if (r < 0)
-                                return r;
-
-                        has_plus = r;
-                }
-
-                if (index == 0)
-                        strpcpy_full(&s, l, event->program_result, &truncated);
-                else {
-                        const char *start, *p;
-                        unsigned i;
-
-                        p = skip_leading_chars(event->program_result, NULL);
-
-                        for (i = 1; i < index; i++) {
-                                while (*p && !strchr(WHITESPACE, *p))
-                                        p++;
-                                p = skip_leading_chars(p, NULL);
-                                if (*p == '\0')
-                                        break;
-                        }
-                        if (i != index) {
-                                log_device_debug(dev, "requested part of result string not found");
-                                goto null_terminate;
-                        }
-
-                        start = p;
-                        /* %c{2+} copies the whole string from the second part on */
-                        if (has_plus)
-                                strpcpy_full(&s, l, start, &truncated);
-                        else {
-                                while (*p && !strchr(WHITESPACE, *p))
-                                        p++;
-                                strnpcpy_full(&s, l, start, p - start, &truncated);
-                        }
-                }
-                break;
-        }
-        case FORMAT_SUBST_ATTR: {
-                char vbuf[UDEV_NAME_SIZE];
-                int count;
-                bool t;
-
-                if (isempty(attr))
-                        return -EINVAL;
-
-                /* try to read the value specified by "[dmi/id]product_name" */
-                if (udev_resolve_subsys_kernel(attr, vbuf, sizeof(vbuf), true) == 0)
-                        val = vbuf;
-
-                /* try to read the attribute the device */
-                if (!val)
-                        (void) sd_device_get_sysattr_value(dev, attr, &val);
-
-                /* try to read the attribute of the parent device, other matches have selected */
-                if (!val && event->dev_parent && event->dev_parent != dev)
-                        (void) sd_device_get_sysattr_value(event->dev_parent, attr, &val);
-
-                if (!val)
-                        goto null_terminate;
-
-                /* strip trailing whitespace, and replace unwanted characters */
-                if (val != vbuf)
-                        strscpy_full(vbuf, sizeof(vbuf), val, &truncated);
-                delete_trailing_chars(vbuf, NULL);
-                count = udev_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
-                if (count > 0)
-                        log_device_debug(dev, "%i character(s) replaced", count);
-                strpcpy_full(&s, l, vbuf, &t);
-                truncated = truncated || t;
-                break;
-        }
-        case FORMAT_SUBST_PARENT:
-                r = sd_device_get_parent(dev, &parent);
-                if (r == -ENOENT)
-                        goto null_terminate;
-                if (r < 0)
-                        return r;
-                r = sd_device_get_devname(parent, &val);
-                if (r == -ENOENT)
-                        goto null_terminate;
-                if (r < 0)
-                        return r;
-                strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
-                break;
-        case FORMAT_SUBST_DEVNODE:
-                r = sd_device_get_devname(dev, &val);
-                if (r == -ENOENT)
-                        goto null_terminate;
-                if (r < 0)
-                        return r;
-                strpcpy_full(&s, l, val, &truncated);
-                break;
-        case FORMAT_SUBST_NAME:
-                if (event->name)
-                        strpcpy_full(&s, l, event->name, &truncated);
-                else if (sd_device_get_devname(dev, &val) >= 0)
-                        strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
-                else {
-                        r = sd_device_get_sysname(dev, &val);
-                        if (r < 0)
-                                return r;
-                        strpcpy_full(&s, l, val, &truncated);
-                }
-                break;
-        case FORMAT_SUBST_LINKS:
-                FOREACH_DEVICE_DEVLINK(dev, link) {
-                        if (s == dest)
-                                strpcpy_full(&s, l, link + STRLEN("/dev/"), &truncated);
-                        else
-                                strpcpyl_full(&s, l, &truncated, " ", link + STRLEN("/dev/"), NULL);
-                        if (truncated)
-                                break;
-                }
-                if (s == dest)
-                        goto null_terminate;
-                break;
-        case FORMAT_SUBST_ROOT:
-                strpcpy_full(&s, l, "/dev", &truncated);
-                break;
-        case FORMAT_SUBST_SYS:
-                strpcpy_full(&s, l, "/sys", &truncated);
-                break;
-        case FORMAT_SUBST_ENV:
-                if (isempty(attr))
-                        return -EINVAL;
-                r = sd_device_get_property_value(dev, attr, &val);
-                if (r == -ENOENT)
-                        goto null_terminate;
-                if (r < 0)
-                        return r;
-                strpcpy_full(&s, l, val, &truncated);
-                break;
-        default:
-                assert_not_reached();
-        }
-
-        if (ret_truncated)
-                *ret_truncated = truncated;
-
-        return s - dest;
-
-null_terminate:
-        if (ret_truncated)
-                *ret_truncated = truncated;
-
-        *s = '\0';
-        return 0;
-}
-
-size_t udev_event_apply_format(
-                UdevEvent *event,
-                const char *src,
-                char *dest,
-                size_t size,
-                bool replace_whitespace,
-                bool *ret_truncated) {
-
-        bool truncated = false;
-        const char *s = ASSERT_PTR(src);
-        int r;
-
-        assert(event);
-        assert(event->dev);
-        assert(dest);
-        assert(size > 0);
-
-        while (*s) {
-                FormatSubstitutionType type;
-                char attr[UDEV_PATH_SIZE];
-                ssize_t subst_len;
-                bool t;
-
-                r = get_subst_type(&s, false, &type, attr);
-                if (r < 0) {
-                        log_device_warning_errno(event->dev, r, "Invalid format string, ignoring: %s", src);
-                        break;
-                } else if (r == 0) {
-                        if (size < 2) {
-                                /* need space for this char and the terminating NUL */
-                                truncated = true;
-                                break;
-                        }
-                        *dest++ = *s++;
-                        size--;
-                        continue;
-                }
-
-                subst_len = udev_event_subst_format(event, type, attr, dest, size, &t);
-                if (subst_len < 0) {
-                        log_device_warning_errno(event->dev, subst_len,
-                                                 "Failed to substitute variable '$%s' or apply format '%%%c', ignoring: %m",
-                                                 format_type_to_string(type), format_type_to_char(type));
-                        break;
-                }
-
-                truncated = truncated || t;
-
-                /* FORMAT_SUBST_RESULT handles spaces itself */
-                if (replace_whitespace && type != FORMAT_SUBST_RESULT)
-                        /* udev_replace_whitespace can replace in-place,
-                         * and does nothing if subst_len == 0 */
-                        subst_len = udev_replace_whitespace(dest, dest, subst_len);
-
-                dest += subst_len;
-                size -= subst_len;
-        }
-
-        assert(size >= 1);
-
-        if (ret_truncated)
-                *ret_truncated = truncated;
-
-        *dest = '\0';
-        return size;
-}
-
-int udev_check_format(const char *value, size_t *offset, const char **hint) {
-        FormatSubstitutionType type;
-        const char *s = value;
-        char attr[UDEV_PATH_SIZE];
-        int r;
-
-        while (*s) {
-                r = get_subst_type(&s, true, &type, attr);
-                if (r < 0) {
-                        if (offset)
-                                *offset = s - value;
-                        if (hint)
-                                *hint = "invalid substitution type";
-                        return r;
-                } else if (r == 0) {
-                        s++;
-                        continue;
-                }
-
-                if (IN_SET(type, FORMAT_SUBST_ATTR, FORMAT_SUBST_ENV) && isempty(attr)) {
-                        if (offset)
-                                *offset = s - value;
-                        if (hint)
-                                *hint = "attribute value missing";
-                        return -EINVAL;
-                }
-
-                if (type == FORMAT_SUBST_RESULT && !isempty(attr)) {
-                        unsigned i;
-
-                        r = safe_atou_optional_plus(attr, &i);
-                        if (r < 0) {
-                                if (offset)
-                                        *offset = s - value;
-                                if (hint)
-                                        *hint = "attribute value not a valid number";
-                                return r;
-                        }
-                }
-        }
-
-        return 0;
-}
-
-static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
-        Spawn *spawn = ASSERT_PTR(userdata);
-        char buf[4096], *p;
-        size_t size;
-        ssize_t l;
-        int r;
-
-        assert(fd == spawn->fd_stdout || fd == spawn->fd_stderr);
-        assert(!spawn->result || spawn->result_len < spawn->result_size);
-
-        if (fd == spawn->fd_stdout && spawn->result) {
-                p = spawn->result + spawn->result_len;
-                size = spawn->result_size - spawn->result_len;
-        } else {
-                p = buf;
-                size = sizeof(buf);
-        }
-
-        l = read(fd, p, size - (p == buf));
-        if (l < 0) {
-                if (errno == EAGAIN)
-                        goto reenable;
-
-                log_device_error_errno(spawn->device, errno,
-                                       "Failed to read stdout of '%s': %m", spawn->cmd);
-
-                return 0;
-        }
-
-        if ((size_t) l == size) {
-                log_device_warning(spawn->device, "Truncating stdout of '%s' up to %zu byte.",
-                                   spawn->cmd, spawn->result_size);
-                l--;
-                spawn->truncated = true;
-        }
-
-        p[l] = '\0';
-        if (fd == spawn->fd_stdout && spawn->result)
-                spawn->result_len += l;
-
-        /* Log output only if we watch stderr. */
-        if (l > 0 && spawn->fd_stderr >= 0) {
-                _cleanup_strv_free_ char **v = NULL;
-
-                r = strv_split_newlines_full(&v, p, EXTRACT_RETAIN_ESCAPE);
-                if (r < 0)
-                        log_device_debug(spawn->device,
-                                         "Failed to split output from '%s'(%s), ignoring: %m",
-                                         spawn->cmd, fd == spawn->fd_stdout ? "out" : "err");
-
-                STRV_FOREACH(q, v)
-                        log_device_debug(spawn->device, "'%s'(%s) '%s'", spawn->cmd,
-                                         fd == spawn->fd_stdout ? "out" : "err", *q);
-        }
-
-        if (l == 0 || spawn->truncated)
-                return 0;
-
-reenable:
-        /* Re-enable the event source if we did not encounter EOF */
-
-        r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
-        if (r < 0)
-                log_device_error_errno(spawn->device, r,
-                                       "Failed to reactivate IO source of '%s'", spawn->cmd);
-        return 0;
-}
-
-static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
-        Spawn *spawn = ASSERT_PTR(userdata);
-
-        DEVICE_TRACE_POINT(spawn_timeout, spawn->device, spawn->cmd);
-
-        kill_and_sigcont(spawn->pid, spawn->timeout_signal);
-
-        log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing",
-                         spawn->cmd, spawn->pid,
-                         FORMAT_TIMESPAN(spawn->timeout_usec, USEC_PER_SEC));
-
-        return 1;
-}
-
-static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
-        Spawn *spawn = ASSERT_PTR(userdata);
-
-        log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete",
-                           spawn->cmd, spawn->pid,
-                           FORMAT_TIMESPAN(spawn->timeout_warn_usec, USEC_PER_SEC));
-
-        return 1;
-}
-
-static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
-        Spawn *spawn = ASSERT_PTR(userdata);
-        int ret = -EIO;
-
-        switch (si->si_code) {
-        case CLD_EXITED:
-                if (si->si_status == 0)
-                        log_device_debug(spawn->device, "Process '%s' succeeded.", spawn->cmd);
-                else
-                        log_device_full(spawn->device, spawn->accept_failure ? LOG_DEBUG : LOG_WARNING,
-                                        "Process '%s' failed with exit code %i.", spawn->cmd, si->si_status);
-                ret = si->si_status;
-                break;
-        case CLD_KILLED:
-        case CLD_DUMPED:
-                log_device_error(spawn->device, "Process '%s' terminated by signal %s.", spawn->cmd, signal_to_string(si->si_status));
-                break;
-        default:
-                log_device_error(spawn->device, "Process '%s' failed due to unknown reason.", spawn->cmd);
-        }
-
-        DEVICE_TRACE_POINT(spawn_exit, spawn->device, spawn->cmd);
-
-        sd_event_exit(sd_event_source_get_event(s), ret);
-        return 1;
-}
-
-static int spawn_wait(Spawn *spawn) {
-        _cleanup_(sd_event_unrefp) sd_event *e = NULL;
-        _cleanup_(sd_event_source_disable_unrefp) sd_event_source *sigchld_source = NULL;
-        _cleanup_(sd_event_source_disable_unrefp) sd_event_source *stdout_source = NULL;
-        _cleanup_(sd_event_source_disable_unrefp) sd_event_source *stderr_source = NULL;
-        int r;
-
-        assert(spawn);
-
-        r = sd_event_new(&e);
-        if (r < 0)
-                return log_device_debug_errno(spawn->device, r, "Failed to allocate sd-event object: %m");
-
-        if (spawn->timeout_usec > 0) {
-                usec_t usec, age_usec;
-
-                usec = now(CLOCK_MONOTONIC);
-                age_usec = usec - spawn->event_birth_usec;
-                if (age_usec < spawn->timeout_usec) {
-                        if (spawn->timeout_warn_usec > 0 &&
-                            spawn->timeout_warn_usec < spawn->timeout_usec &&
-                            spawn->timeout_warn_usec > age_usec) {
-                                spawn->timeout_warn_usec -= age_usec;
-
-                                r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
-                                                      usec + spawn->timeout_warn_usec, USEC_PER_SEC,
-                                                      on_spawn_timeout_warning, spawn);
-                                if (r < 0)
-                                        return log_device_debug_errno(spawn->device, r, "Failed to create timeout warning event source: %m");
-                        }
-
-                        spawn->timeout_usec -= age_usec;
-
-                        r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
-                                              usec + spawn->timeout_usec, USEC_PER_SEC, on_spawn_timeout, spawn);
-                        if (r < 0)
-                                return log_device_debug_errno(spawn->device, r, "Failed to create timeout event source: %m");
-                }
-        }
-
-        if (spawn->fd_stdout >= 0) {
-                r = sd_event_add_io(e, &stdout_source, spawn->fd_stdout, EPOLLIN, on_spawn_io, spawn);
-                if (r < 0)
-                        return log_device_debug_errno(spawn->device, r, "Failed to create stdio event source: %m");
-                r = sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT);
-                if (r < 0)
-                        return log_device_debug_errno(spawn->device, r, "Failed to enable stdio event source: %m");
-        }
-
-        if (spawn->fd_stderr >= 0) {
-                r = sd_event_add_io(e, &stderr_source, spawn->fd_stderr, EPOLLIN, on_spawn_io, spawn);
-                if (r < 0)
-                        return log_device_debug_errno(spawn->device, r, "Failed to create stderr event source: %m");
-                r = sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT);
-                if (r < 0)
-                        return log_device_debug_errno(spawn->device, r, "Failed to enable stderr event source: %m");
-        }
-
-        r = sd_event_add_child(e, &sigchld_source, spawn->pid, WEXITED, on_spawn_sigchld, spawn);
-        if (r < 0)
-                return log_device_debug_errno(spawn->device, r, "Failed to create sigchild event source: %m");
-        /* SIGCHLD should be processed after IO is complete */
-        r = sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1);
-        if (r < 0)
-                return log_device_debug_errno(spawn->device, r, "Failed to set priority to sigchild event source: %m");
-
-        return sd_event_loop(e);
-}
-
-int 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) {
-
-        _cleanup_close_pair_ int outpipe[2] = PIPE_EBADF, errpipe[2] = PIPE_EBADF;
-        _cleanup_strv_free_ char **argv = NULL;
-        char **envp = NULL;
-        Spawn spawn;
-        pid_t pid;
-        int r;
-
-        assert(event);
-        assert(event->dev);
-        assert(result || ressize == 0);
-
-        /* pipes from child to parent */
-        if (result || log_get_max_level() >= LOG_INFO)
-                if (pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) != 0)
-                        return log_device_error_errno(event->dev, errno,
-                                                      "Failed to create pipe for command '%s': %m", cmd);
-
-        if (log_get_max_level() >= LOG_INFO)
-                if (pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) != 0)
-                        return log_device_error_errno(event->dev, errno,
-                                                      "Failed to create pipe for command '%s': %m", cmd);
-
-        r = strv_split_full(&argv, cmd, NULL, EXTRACT_UNQUOTE | EXTRACT_RELAX | EXTRACT_RETAIN_ESCAPE);
-        if (r < 0)
-                return log_device_error_errno(event->dev, r, "Failed to split command: %m");
-
-        if (isempty(argv[0]))
-                return log_device_error_errno(event->dev, SYNTHETIC_ERRNO(EINVAL),
-                                              "Invalid command '%s'", cmd);
-
-        /* allow programs in /usr/lib/udev/ to be called without the path */
-        if (!path_is_absolute(argv[0])) {
-                char *program;
-
-                program = path_join(UDEVLIBEXECDIR, argv[0]);
-                if (!program)
-                        return log_oom();
-
-                free_and_replace(argv[0], program);
-        }
-
-        r = device_get_properties_strv(event->dev, &envp);
-        if (r < 0)
-                return log_device_error_errno(event->dev, r, "Failed to get device properties");
-
-        log_device_debug(event->dev, "Starting '%s'", cmd);
-
-        r = safe_fork_full("(spawn)",
-                           (int[]) { -EBADF, outpipe[WRITE_END], errpipe[WRITE_END] },
-                           NULL, 0,
-                           FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_REARRANGE_STDIO|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE,
-                           &pid);
-        if (r < 0)
-                return log_device_error_errno(event->dev, r,
-                                              "Failed to fork() to execute command '%s': %m", cmd);
-        if (r == 0) {
-                DEVICE_TRACE_POINT(spawn_exec, event->dev, cmd);
-                execve(argv[0], argv, envp);
-                _exit(EXIT_FAILURE);
-        }
-
-        /* parent closed child's ends of pipes */
-        outpipe[WRITE_END] = safe_close(outpipe[WRITE_END]);
-        errpipe[WRITE_END] = safe_close(errpipe[WRITE_END]);
-
-        spawn = (Spawn) {
-                .device = event->dev,
-                .cmd = cmd,
-                .pid = pid,
-                .accept_failure = accept_failure,
-                .timeout_warn_usec = udev_warn_timeout(timeout_usec),
-                .timeout_usec = timeout_usec,
-                .timeout_signal = timeout_signal,
-                .event_birth_usec = event->birth_usec,
-                .fd_stdout = outpipe[READ_END],
-                .fd_stderr = errpipe[READ_END],
-                .result = result,
-                .result_size = ressize,
-        };
-        r = spawn_wait(&spawn);
-        if (r < 0)
-                return log_device_error_errno(event->dev, r,
-                                              "Failed to wait for spawned command '%s': %m", cmd);
-
-        if (result)
-                result[spawn.result_len] = '\0';
-
-        if (ret_truncated)
-                *ret_truncated = spawn.truncated;
-
-        return r; /* 0 for success, and positive if the program failed */
-}
-
 static int device_rename(sd_device *device, const char *name) {
         _cleanup_free_ char *new_syspath = NULL;
         const char *s;
@@ -1205,34 +403,3 @@ int udev_event_execute_rules(
 
         return 0;
 }
-
-void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal) {
-        const char *command;
-        void *val;
-        int r;
-
-        ORDERED_HASHMAP_FOREACH_KEY(val, command, event->run_list) {
-                UdevBuiltinCommand builtin_cmd = PTR_TO_UDEV_BUILTIN_CMD(val);
-
-                if (builtin_cmd != _UDEV_BUILTIN_INVALID) {
-                        log_device_debug(event->dev, "Running built-in command \"%s\"", command);
-                        r = udev_builtin_run(event, builtin_cmd, command, false);
-                        if (r < 0)
-                                log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command);
-                } else {
-                        if (event->exec_delay_usec > 0) {
-                                log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.",
-                                                 command, FORMAT_TIMESPAN(event->exec_delay_usec, USEC_PER_SEC));
-                                (void) usleep_safe(event->exec_delay_usec);
-                        }
-
-                        log_device_debug(event->dev, "Running command \"%s\"", command);
-
-                        r = udev_event_spawn(event, timeout_usec, timeout_signal, false, command, NULL, 0, NULL);
-                        if (r < 0)
-                                log_device_warning_errno(event->dev, r, "Failed to execute '%s', ignoring: %m", command);
-                        else if (r > 0) /* returned value is positive when program fails */
-                                log_device_debug(event->dev, "Command \"%s\" returned %d (error), ignoring.", command, r);
-                }
-        }
-}
index b99559ca2ee1a76e92b33de283c4aa3037ab1cde..6b94fd08aba29af39908da1fc4492074c7d0ded5 100644 (file)
@@ -5,17 +5,17 @@
  * Copyright Â© 2003 Greg Kroah-Hartman <greg@kroah.com>
  */
 
+#include <stdbool.h>
+#include <stddef.h>
+
 #include "sd-device.h"
 #include "sd-netlink.h"
 
 #include "hashmap.h"
 #include "macro.h"
+#include "time-util.h"
 #include "udev-rules.h"
-#include "udev-util.h"
-
-#define READ_END  0
-#define WRITE_END 1
-#define UDEV_ALLOWED_CHARS_INPUT        "/ $%?,"
+#include "user-util.h"
 
 typedef struct UdevEvent {
         sd_device *dev;
@@ -51,23 +51,6 @@ UdevEvent *udev_event_new(sd_device *dev, usec_t exec_delay_usec, sd_netlink *rt
 UdevEvent *udev_event_free(UdevEvent *event);
 DEFINE_TRIVIAL_CLEANUP_FUNC(UdevEvent*, udev_event_free);
 
-size_t udev_event_apply_format(
-                UdevEvent *event,
-                const char *src,
-                char *dest,
-                size_t size,
-                bool replace_whitespace,
-                bool *ret_truncated);
-int udev_check_format(const char *value, size_t *offset, const char **hint);
-int 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);
 int udev_event_execute_rules(
                 UdevEvent *event,
                 int inotify_fd,
@@ -75,8 +58,3 @@ int udev_event_execute_rules(
                 int timeout_signal,
                 Hashmap *properties_list,
                 UdevRules *rules);
-void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal);
-
-static inline usec_t udev_warn_timeout(usec_t timeout_usec) {
-        return DIV_ROUND_UP(timeout_usec, 3);
-}
diff --git a/src/udev/udev-format.c b/src/udev/udev-format.c
new file mode 100644 (file)
index 0000000..b33d864
--- /dev/null
@@ -0,0 +1,483 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include "device-util.h"
+#include "parse-util.h"
+#include "string-util.h"
+#include "strxcpyx.h"
+#include "udev-event.h"
+#include "udev-format.h"
+#include "udev-util.h"
+
+typedef enum {
+        FORMAT_SUBST_DEVNODE,
+        FORMAT_SUBST_ATTR,
+        FORMAT_SUBST_ENV,
+        FORMAT_SUBST_KERNEL,
+        FORMAT_SUBST_KERNEL_NUMBER,
+        FORMAT_SUBST_DRIVER,
+        FORMAT_SUBST_DEVPATH,
+        FORMAT_SUBST_ID,
+        FORMAT_SUBST_MAJOR,
+        FORMAT_SUBST_MINOR,
+        FORMAT_SUBST_RESULT,
+        FORMAT_SUBST_PARENT,
+        FORMAT_SUBST_NAME,
+        FORMAT_SUBST_LINKS,
+        FORMAT_SUBST_ROOT,
+        FORMAT_SUBST_SYS,
+        _FORMAT_SUBST_TYPE_MAX,
+        _FORMAT_SUBST_TYPE_INVALID = -EINVAL,
+} FormatSubstitutionType;
+
+struct subst_map_entry {
+        const char *name;
+        const char fmt;
+        FormatSubstitutionType type;
+};
+
+static const struct subst_map_entry map[] = {
+           { .name = "devnode",  .fmt = 'N', .type = FORMAT_SUBST_DEVNODE       },
+           { .name = "tempnode", .fmt = 'N', .type = FORMAT_SUBST_DEVNODE       }, /* deprecated */
+           { .name = "attr",     .fmt = 's', .type = FORMAT_SUBST_ATTR          },
+           { .name = "sysfs",    .fmt = 's', .type = FORMAT_SUBST_ATTR          }, /* deprecated */
+           { .name = "env",      .fmt = 'E', .type = FORMAT_SUBST_ENV           },
+           { .name = "kernel",   .fmt = 'k', .type = FORMAT_SUBST_KERNEL        },
+           { .name = "number",   .fmt = 'n', .type = FORMAT_SUBST_KERNEL_NUMBER },
+           { .name = "driver",   .fmt = 'd', .type = FORMAT_SUBST_DRIVER        },
+           { .name = "devpath",  .fmt = 'p', .type = FORMAT_SUBST_DEVPATH       },
+           { .name = "id",       .fmt = 'b', .type = FORMAT_SUBST_ID            },
+           { .name = "major",    .fmt = 'M', .type = FORMAT_SUBST_MAJOR         },
+           { .name = "minor",    .fmt = 'm', .type = FORMAT_SUBST_MINOR         },
+           { .name = "result",   .fmt = 'c', .type = FORMAT_SUBST_RESULT        },
+           { .name = "parent",   .fmt = 'P', .type = FORMAT_SUBST_PARENT        },
+           { .name = "name",     .fmt = 'D', .type = FORMAT_SUBST_NAME          },
+           { .name = "links",    .fmt = 'L', .type = FORMAT_SUBST_LINKS         },
+           { .name = "root",     .fmt = 'r', .type = FORMAT_SUBST_ROOT          },
+           { .name = "sys",      .fmt = 'S', .type = FORMAT_SUBST_SYS           },
+};
+
+static const char *format_type_to_string(FormatSubstitutionType t) {
+        for (size_t i = 0; i < ELEMENTSOF(map); i++)
+                if (map[i].type == t)
+                        return map[i].name;
+        return NULL;
+}
+
+static char format_type_to_char(FormatSubstitutionType t) {
+        for (size_t i = 0; i < ELEMENTSOF(map); i++)
+                if (map[i].type == t)
+                        return map[i].fmt;
+        return '\0';
+}
+
+static int get_subst_type(const char **str, bool strict, FormatSubstitutionType *ret_type, char ret_attr[static UDEV_PATH_SIZE]) {
+        const char *p = *str, *q = NULL;
+        size_t i;
+
+        assert(str);
+        assert(*str);
+        assert(ret_type);
+        assert(ret_attr);
+
+        if (*p == '$') {
+                p++;
+                if (*p == '$') {
+                        *str = p;
+                        return 0;
+                }
+                for (i = 0; i < ELEMENTSOF(map); i++)
+                        if ((q = startswith(p, map[i].name)))
+                                break;
+        } else if (*p == '%') {
+                p++;
+                if (*p == '%') {
+                        *str = p;
+                        return 0;
+                }
+
+                for (i = 0; i < ELEMENTSOF(map); i++)
+                        if (*p == map[i].fmt) {
+                                q = p + 1;
+                                break;
+                        }
+        } else
+                return 0;
+        if (!q)
+                /* When 'strict' flag is set, then '$' and '%' must be escaped. */
+                return strict ? -EINVAL : 0;
+
+        if (*q == '{') {
+                const char *start, *end;
+                size_t len;
+
+                start = q + 1;
+                end = strchr(start, '}');
+                if (!end)
+                        return -EINVAL;
+
+                len = end - start;
+                if (len == 0 || len >= UDEV_PATH_SIZE)
+                        return -EINVAL;
+
+                strnscpy(ret_attr, UDEV_PATH_SIZE, start, len);
+                q = end + 1;
+        } else
+                *ret_attr = '\0';
+
+        *str = q;
+        *ret_type = map[i].type;
+        return 1;
+}
+
+static int safe_atou_optional_plus(const char *s, unsigned *ret) {
+        const char *p;
+        int r;
+
+        assert(s);
+        assert(ret);
+
+        /* Returns 1 if plus, 0 if no plus, negative on error */
+
+        p = endswith(s, "+");
+        if (p)
+                s = strndupa_safe(s, p - s);
+
+        r = safe_atou(s, ret);
+        if (r < 0)
+                return r;
+
+        return !!p;
+}
+
+static ssize_t udev_event_subst_format(
+                UdevEvent *event,
+                FormatSubstitutionType type,
+                const char *attr,
+                char *dest,
+                size_t l,
+                bool *ret_truncated) {
+
+        sd_device *parent, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev);
+        const char *val = NULL;
+        bool truncated = false;
+        char *s = dest;
+        int r;
+
+        switch (type) {
+        case FORMAT_SUBST_DEVPATH:
+                r = sd_device_get_devpath(dev, &val);
+                if (r < 0)
+                        return r;
+                strpcpy_full(&s, l, val, &truncated);
+                break;
+        case FORMAT_SUBST_KERNEL:
+                r = sd_device_get_sysname(dev, &val);
+                if (r < 0)
+                        return r;
+                strpcpy_full(&s, l, val, &truncated);
+                break;
+        case FORMAT_SUBST_KERNEL_NUMBER:
+                r = sd_device_get_sysnum(dev, &val);
+                if (r == -ENOENT)
+                        goto null_terminate;
+                if (r < 0)
+                        return r;
+                strpcpy_full(&s, l, val, &truncated);
+                break;
+        case FORMAT_SUBST_ID:
+                if (!event->dev_parent)
+                        goto null_terminate;
+                r = sd_device_get_sysname(event->dev_parent, &val);
+                if (r < 0)
+                        return r;
+                strpcpy_full(&s, l, val, &truncated);
+                break;
+        case FORMAT_SUBST_DRIVER:
+                if (!event->dev_parent)
+                        goto null_terminate;
+                r = sd_device_get_driver(event->dev_parent, &val);
+                if (r == -ENOENT)
+                        goto null_terminate;
+                if (r < 0)
+                        return r;
+                strpcpy_full(&s, l, val, &truncated);
+                break;
+        case FORMAT_SUBST_MAJOR:
+        case FORMAT_SUBST_MINOR: {
+                dev_t devnum;
+
+                r = sd_device_get_devnum(dev, &devnum);
+                if (r < 0 && r != -ENOENT)
+                        return r;
+                strpcpyf_full(&s, l, &truncated, "%u", r < 0 ? 0 : type == FORMAT_SUBST_MAJOR ? major(devnum) : minor(devnum));
+                break;
+        }
+        case FORMAT_SUBST_RESULT: {
+                unsigned index = 0; /* 0 means whole string */
+                bool has_plus;
+
+                if (!event->program_result)
+                        goto null_terminate;
+
+                if (!isempty(attr)) {
+                        r = safe_atou_optional_plus(attr, &index);
+                        if (r < 0)
+                                return r;
+
+                        has_plus = r;
+                }
+
+                if (index == 0)
+                        strpcpy_full(&s, l, event->program_result, &truncated);
+                else {
+                        const char *start, *p;
+                        unsigned i;
+
+                        p = skip_leading_chars(event->program_result, NULL);
+
+                        for (i = 1; i < index; i++) {
+                                while (*p && !strchr(WHITESPACE, *p))
+                                        p++;
+                                p = skip_leading_chars(p, NULL);
+                                if (*p == '\0')
+                                        break;
+                        }
+                        if (i != index) {
+                                log_device_debug(dev, "requested part of result string not found");
+                                goto null_terminate;
+                        }
+
+                        start = p;
+                        /* %c{2+} copies the whole string from the second part on */
+                        if (has_plus)
+                                strpcpy_full(&s, l, start, &truncated);
+                        else {
+                                while (*p && !strchr(WHITESPACE, *p))
+                                        p++;
+                                strnpcpy_full(&s, l, start, p - start, &truncated);
+                        }
+                }
+                break;
+        }
+        case FORMAT_SUBST_ATTR: {
+                char vbuf[UDEV_NAME_SIZE];
+                int count;
+                bool t;
+
+                if (isempty(attr))
+                        return -EINVAL;
+
+                /* try to read the value specified by "[dmi/id]product_name" */
+                if (udev_resolve_subsys_kernel(attr, vbuf, sizeof(vbuf), true) == 0)
+                        val = vbuf;
+
+                /* try to read the attribute the device */
+                if (!val)
+                        (void) sd_device_get_sysattr_value(dev, attr, &val);
+
+                /* try to read the attribute of the parent device, other matches have selected */
+                if (!val && event->dev_parent && event->dev_parent != dev)
+                        (void) sd_device_get_sysattr_value(event->dev_parent, attr, &val);
+
+                if (!val)
+                        goto null_terminate;
+
+                /* strip trailing whitespace, and replace unwanted characters */
+                if (val != vbuf)
+                        strscpy_full(vbuf, sizeof(vbuf), val, &truncated);
+                delete_trailing_chars(vbuf, NULL);
+                count = udev_replace_chars(vbuf, UDEV_ALLOWED_CHARS_INPUT);
+                if (count > 0)
+                        log_device_debug(dev, "%i character(s) replaced", count);
+                strpcpy_full(&s, l, vbuf, &t);
+                truncated = truncated || t;
+                break;
+        }
+        case FORMAT_SUBST_PARENT:
+                r = sd_device_get_parent(dev, &parent);
+                if (r == -ENOENT)
+                        goto null_terminate;
+                if (r < 0)
+                        return r;
+                r = sd_device_get_devname(parent, &val);
+                if (r == -ENOENT)
+                        goto null_terminate;
+                if (r < 0)
+                        return r;
+                strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
+                break;
+        case FORMAT_SUBST_DEVNODE:
+                r = sd_device_get_devname(dev, &val);
+                if (r == -ENOENT)
+                        goto null_terminate;
+                if (r < 0)
+                        return r;
+                strpcpy_full(&s, l, val, &truncated);
+                break;
+        case FORMAT_SUBST_NAME:
+                if (event->name)
+                        strpcpy_full(&s, l, event->name, &truncated);
+                else if (sd_device_get_devname(dev, &val) >= 0)
+                        strpcpy_full(&s, l, val + STRLEN("/dev/"), &truncated);
+                else {
+                        r = sd_device_get_sysname(dev, &val);
+                        if (r < 0)
+                                return r;
+                        strpcpy_full(&s, l, val, &truncated);
+                }
+                break;
+        case FORMAT_SUBST_LINKS:
+                FOREACH_DEVICE_DEVLINK(dev, link) {
+                        if (s == dest)
+                                strpcpy_full(&s, l, link + STRLEN("/dev/"), &truncated);
+                        else
+                                strpcpyl_full(&s, l, &truncated, " ", link + STRLEN("/dev/"), NULL);
+                        if (truncated)
+                                break;
+                }
+                if (s == dest)
+                        goto null_terminate;
+                break;
+        case FORMAT_SUBST_ROOT:
+                strpcpy_full(&s, l, "/dev", &truncated);
+                break;
+        case FORMAT_SUBST_SYS:
+                strpcpy_full(&s, l, "/sys", &truncated);
+                break;
+        case FORMAT_SUBST_ENV:
+                if (isempty(attr))
+                        return -EINVAL;
+                r = sd_device_get_property_value(dev, attr, &val);
+                if (r == -ENOENT)
+                        goto null_terminate;
+                if (r < 0)
+                        return r;
+                strpcpy_full(&s, l, val, &truncated);
+                break;
+        default:
+                assert_not_reached();
+        }
+
+        if (ret_truncated)
+                *ret_truncated = truncated;
+
+        return s - dest;
+
+null_terminate:
+        if (ret_truncated)
+                *ret_truncated = truncated;
+
+        *s = '\0';
+        return 0;
+}
+
+size_t udev_event_apply_format(
+                UdevEvent *event,
+                const char *src,
+                char *dest,
+                size_t size,
+                bool replace_whitespace,
+                bool *ret_truncated) {
+
+        bool truncated = false;
+        const char *s = ASSERT_PTR(src);
+        int r;
+
+        assert(event);
+        assert(event->dev);
+        assert(dest);
+        assert(size > 0);
+
+        while (*s) {
+                FormatSubstitutionType type;
+                char attr[UDEV_PATH_SIZE];
+                ssize_t subst_len;
+                bool t;
+
+                r = get_subst_type(&s, false, &type, attr);
+                if (r < 0) {
+                        log_device_warning_errno(event->dev, r, "Invalid format string, ignoring: %s", src);
+                        break;
+                } else if (r == 0) {
+                        if (size < 2) {
+                                /* need space for this char and the terminating NUL */
+                                truncated = true;
+                                break;
+                        }
+                        *dest++ = *s++;
+                        size--;
+                        continue;
+                }
+
+                subst_len = udev_event_subst_format(event, type, attr, dest, size, &t);
+                if (subst_len < 0) {
+                        log_device_warning_errno(event->dev, subst_len,
+                                                 "Failed to substitute variable '$%s' or apply format '%%%c', ignoring: %m",
+                                                 format_type_to_string(type), format_type_to_char(type));
+                        break;
+                }
+
+                truncated = truncated || t;
+
+                /* FORMAT_SUBST_RESULT handles spaces itself */
+                if (replace_whitespace && type != FORMAT_SUBST_RESULT)
+                        /* udev_replace_whitespace can replace in-place,
+                         * and does nothing if subst_len == 0 */
+                        subst_len = udev_replace_whitespace(dest, dest, subst_len);
+
+                dest += subst_len;
+                size -= subst_len;
+        }
+
+        assert(size >= 1);
+
+        if (ret_truncated)
+                *ret_truncated = truncated;
+
+        *dest = '\0';
+        return size;
+}
+
+int udev_check_format(const char *value, size_t *offset, const char **hint) {
+        FormatSubstitutionType type;
+        const char *s = value;
+        char attr[UDEV_PATH_SIZE];
+        int r;
+
+        while (*s) {
+                r = get_subst_type(&s, true, &type, attr);
+                if (r < 0) {
+                        if (offset)
+                                *offset = s - value;
+                        if (hint)
+                                *hint = "invalid substitution type";
+                        return r;
+                } else if (r == 0) {
+                        s++;
+                        continue;
+                }
+
+                if (IN_SET(type, FORMAT_SUBST_ATTR, FORMAT_SUBST_ENV) && isempty(attr)) {
+                        if (offset)
+                                *offset = s - value;
+                        if (hint)
+                                *hint = "attribute value missing";
+                        return -EINVAL;
+                }
+
+                if (type == FORMAT_SUBST_RESULT && !isempty(attr)) {
+                        unsigned i;
+
+                        r = safe_atou_optional_plus(attr, &i);
+                        if (r < 0) {
+                                if (offset)
+                                        *offset = s - value;
+                                if (hint)
+                                        *hint = "attribute value not a valid number";
+                                return r;
+                        }
+                }
+        }
+
+        return 0;
+}
diff --git a/src/udev/udev-format.h b/src/udev/udev-format.h
new file mode 100644 (file)
index 0000000..0dbdd56
--- /dev/null
@@ -0,0 +1,18 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+
+typedef struct UdevEvent UdevEvent;
+
+#define UDEV_ALLOWED_CHARS_INPUT        "/ $%?,"
+
+size_t udev_event_apply_format(
+                UdevEvent *event,
+                const char *src,
+                char *dest,
+                size_t size,
+                bool replace_whitespace,
+                bool *ret_truncated);
+int udev_check_format(const char *value, size_t *offset, const char **hint);
index 2c9797f09993b156f6ce76df6e924f3183dd732d..c4f2a7ffbb2cb763bda779a23dba34e1e390facb 100644 (file)
 #include "syslog-util.h"
 #include "udev-builtin.h"
 #include "udev-event.h"
+#include "udev-format.h"
 #include "udev-node.h"
 #include "udev-rules.h"
+#include "udev-spawn.h"
 #include "udev-trace.h"
 #include "udev-util.h"
 #include "user-util.h"
diff --git a/src/udev/udev-spawn.c b/src/udev/udev-spawn.c
new file mode 100644 (file)
index 0000000..f90b9c6
--- /dev/null
@@ -0,0 +1,355 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include "sd-event.h"
+
+#include "device-private.h"
+#include "device-util.h"
+#include "fd-util.h"
+#include "path-util.h"
+#include "process-util.h"
+#include "signal-util.h"
+#include "string-util.h"
+#include "strv.h"
+#include "udev-builtin.h"
+#include "udev-event.h"
+#include "udev-spawn.h"
+#include "udev-trace.h"
+
+typedef struct Spawn {
+        sd_device *device;
+        const char *cmd;
+        pid_t pid;
+        usec_t timeout_warn_usec;
+        usec_t timeout_usec;
+        int timeout_signal;
+        usec_t event_birth_usec;
+        bool accept_failure;
+        int fd_stdout;
+        int fd_stderr;
+        char *result;
+        size_t result_size;
+        size_t result_len;
+        bool truncated;
+} Spawn;
+
+static int on_spawn_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+        Spawn *spawn = ASSERT_PTR(userdata);
+        char buf[4096], *p;
+        size_t size;
+        ssize_t l;
+        int r;
+
+        assert(fd == spawn->fd_stdout || fd == spawn->fd_stderr);
+        assert(!spawn->result || spawn->result_len < spawn->result_size);
+
+        if (fd == spawn->fd_stdout && spawn->result) {
+                p = spawn->result + spawn->result_len;
+                size = spawn->result_size - spawn->result_len;
+        } else {
+                p = buf;
+                size = sizeof(buf);
+        }
+
+        l = read(fd, p, size - (p == buf));
+        if (l < 0) {
+                if (errno == EAGAIN)
+                        goto reenable;
+
+                log_device_error_errno(spawn->device, errno,
+                                       "Failed to read stdout of '%s': %m", spawn->cmd);
+
+                return 0;
+        }
+
+        if ((size_t) l == size) {
+                log_device_warning(spawn->device, "Truncating stdout of '%s' up to %zu byte.",
+                                   spawn->cmd, spawn->result_size);
+                l--;
+                spawn->truncated = true;
+        }
+
+        p[l] = '\0';
+        if (fd == spawn->fd_stdout && spawn->result)
+                spawn->result_len += l;
+
+        /* Log output only if we watch stderr. */
+        if (l > 0 && spawn->fd_stderr >= 0) {
+                _cleanup_strv_free_ char **v = NULL;
+
+                r = strv_split_newlines_full(&v, p, EXTRACT_RETAIN_ESCAPE);
+                if (r < 0)
+                        log_device_debug(spawn->device,
+                                         "Failed to split output from '%s'(%s), ignoring: %m",
+                                         spawn->cmd, fd == spawn->fd_stdout ? "out" : "err");
+
+                STRV_FOREACH(q, v)
+                        log_device_debug(spawn->device, "'%s'(%s) '%s'", spawn->cmd,
+                                         fd == spawn->fd_stdout ? "out" : "err", *q);
+        }
+
+        if (l == 0 || spawn->truncated)
+                return 0;
+
+reenable:
+        /* Re-enable the event source if we did not encounter EOF */
+
+        r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
+        if (r < 0)
+                log_device_error_errno(spawn->device, r,
+                                       "Failed to reactivate IO source of '%s'", spawn->cmd);
+        return 0;
+}
+
+static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
+        Spawn *spawn = ASSERT_PTR(userdata);
+
+        DEVICE_TRACE_POINT(spawn_timeout, spawn->device, spawn->cmd);
+
+        kill_and_sigcont(spawn->pid, spawn->timeout_signal);
+
+        log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing",
+                         spawn->cmd, spawn->pid,
+                         FORMAT_TIMESPAN(spawn->timeout_usec, USEC_PER_SEC));
+
+        return 1;
+}
+
+static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
+        Spawn *spawn = ASSERT_PTR(userdata);
+
+        log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete",
+                           spawn->cmd, spawn->pid,
+                           FORMAT_TIMESPAN(spawn->timeout_warn_usec, USEC_PER_SEC));
+
+        return 1;
+}
+
+static int on_spawn_sigchld(sd_event_source *s, const siginfo_t *si, void *userdata) {
+        Spawn *spawn = ASSERT_PTR(userdata);
+        int ret = -EIO;
+
+        switch (si->si_code) {
+        case CLD_EXITED:
+                if (si->si_status == 0)
+                        log_device_debug(spawn->device, "Process '%s' succeeded.", spawn->cmd);
+                else
+                        log_device_full(spawn->device, spawn->accept_failure ? LOG_DEBUG : LOG_WARNING,
+                                        "Process '%s' failed with exit code %i.", spawn->cmd, si->si_status);
+                ret = si->si_status;
+                break;
+        case CLD_KILLED:
+        case CLD_DUMPED:
+                log_device_error(spawn->device, "Process '%s' terminated by signal %s.", spawn->cmd, signal_to_string(si->si_status));
+                break;
+        default:
+                log_device_error(spawn->device, "Process '%s' failed due to unknown reason.", spawn->cmd);
+        }
+
+        DEVICE_TRACE_POINT(spawn_exit, spawn->device, spawn->cmd);
+
+        sd_event_exit(sd_event_source_get_event(s), ret);
+        return 1;
+}
+
+static int spawn_wait(Spawn *spawn) {
+        _cleanup_(sd_event_unrefp) sd_event *e = NULL;
+        _cleanup_(sd_event_source_disable_unrefp) sd_event_source *sigchld_source = NULL;
+        _cleanup_(sd_event_source_disable_unrefp) sd_event_source *stdout_source = NULL;
+        _cleanup_(sd_event_source_disable_unrefp) sd_event_source *stderr_source = NULL;
+        int r;
+
+        assert(spawn);
+
+        r = sd_event_new(&e);
+        if (r < 0)
+                return log_device_debug_errno(spawn->device, r, "Failed to allocate sd-event object: %m");
+
+        if (spawn->timeout_usec > 0) {
+                usec_t usec, age_usec;
+
+                usec = now(CLOCK_MONOTONIC);
+                age_usec = usec - spawn->event_birth_usec;
+                if (age_usec < spawn->timeout_usec) {
+                        if (spawn->timeout_warn_usec > 0 &&
+                            spawn->timeout_warn_usec < spawn->timeout_usec &&
+                            spawn->timeout_warn_usec > age_usec) {
+                                spawn->timeout_warn_usec -= age_usec;
+
+                                r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
+                                                      usec + spawn->timeout_warn_usec, USEC_PER_SEC,
+                                                      on_spawn_timeout_warning, spawn);
+                                if (r < 0)
+                                        return log_device_debug_errno(spawn->device, r, "Failed to create timeout warning event source: %m");
+                        }
+
+                        spawn->timeout_usec -= age_usec;
+
+                        r = sd_event_add_time(e, NULL, CLOCK_MONOTONIC,
+                                              usec + spawn->timeout_usec, USEC_PER_SEC, on_spawn_timeout, spawn);
+                        if (r < 0)
+                                return log_device_debug_errno(spawn->device, r, "Failed to create timeout event source: %m");
+                }
+        }
+
+        if (spawn->fd_stdout >= 0) {
+                r = sd_event_add_io(e, &stdout_source, spawn->fd_stdout, EPOLLIN, on_spawn_io, spawn);
+                if (r < 0)
+                        return log_device_debug_errno(spawn->device, r, "Failed to create stdio event source: %m");
+                r = sd_event_source_set_enabled(stdout_source, SD_EVENT_ONESHOT);
+                if (r < 0)
+                        return log_device_debug_errno(spawn->device, r, "Failed to enable stdio event source: %m");
+        }
+
+        if (spawn->fd_stderr >= 0) {
+                r = sd_event_add_io(e, &stderr_source, spawn->fd_stderr, EPOLLIN, on_spawn_io, spawn);
+                if (r < 0)
+                        return log_device_debug_errno(spawn->device, r, "Failed to create stderr event source: %m");
+                r = sd_event_source_set_enabled(stderr_source, SD_EVENT_ONESHOT);
+                if (r < 0)
+                        return log_device_debug_errno(spawn->device, r, "Failed to enable stderr event source: %m");
+        }
+
+        r = sd_event_add_child(e, &sigchld_source, spawn->pid, WEXITED, on_spawn_sigchld, spawn);
+        if (r < 0)
+                return log_device_debug_errno(spawn->device, r, "Failed to create sigchild event source: %m");
+        /* SIGCHLD should be processed after IO is complete */
+        r = sd_event_source_set_priority(sigchld_source, SD_EVENT_PRIORITY_NORMAL + 1);
+        if (r < 0)
+                return log_device_debug_errno(spawn->device, r, "Failed to set priority to sigchild event source: %m");
+
+        return sd_event_loop(e);
+}
+
+int 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) {
+
+        _cleanup_close_pair_ int outpipe[2] = PIPE_EBADF, errpipe[2] = PIPE_EBADF;
+        _cleanup_strv_free_ char **argv = NULL;
+        char **envp = NULL;
+        Spawn spawn;
+        pid_t pid;
+        int r;
+
+        assert(event);
+        assert(event->dev);
+        assert(result || ressize == 0);
+
+        /* pipes from child to parent */
+        if (result || log_get_max_level() >= LOG_INFO)
+                if (pipe2(outpipe, O_NONBLOCK|O_CLOEXEC) != 0)
+                        return log_device_error_errno(event->dev, errno,
+                                                      "Failed to create pipe for command '%s': %m", cmd);
+
+        if (log_get_max_level() >= LOG_INFO)
+                if (pipe2(errpipe, O_NONBLOCK|O_CLOEXEC) != 0)
+                        return log_device_error_errno(event->dev, errno,
+                                                      "Failed to create pipe for command '%s': %m", cmd);
+
+        r = strv_split_full(&argv, cmd, NULL, EXTRACT_UNQUOTE | EXTRACT_RELAX | EXTRACT_RETAIN_ESCAPE);
+        if (r < 0)
+                return log_device_error_errno(event->dev, r, "Failed to split command: %m");
+
+        if (isempty(argv[0]))
+                return log_device_error_errno(event->dev, SYNTHETIC_ERRNO(EINVAL),
+                                              "Invalid command '%s'", cmd);
+
+        /* allow programs in /usr/lib/udev/ to be called without the path */
+        if (!path_is_absolute(argv[0])) {
+                char *program;
+
+                program = path_join(UDEVLIBEXECDIR, argv[0]);
+                if (!program)
+                        return log_oom();
+
+                free_and_replace(argv[0], program);
+        }
+
+        r = device_get_properties_strv(event->dev, &envp);
+        if (r < 0)
+                return log_device_error_errno(event->dev, r, "Failed to get device properties");
+
+        log_device_debug(event->dev, "Starting '%s'", cmd);
+
+        r = safe_fork_full("(spawn)",
+                           (int[]) { -EBADF, outpipe[WRITE_END], errpipe[WRITE_END] },
+                           NULL, 0,
+                           FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_REARRANGE_STDIO|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE,
+                           &pid);
+        if (r < 0)
+                return log_device_error_errno(event->dev, r,
+                                              "Failed to fork() to execute command '%s': %m", cmd);
+        if (r == 0) {
+                DEVICE_TRACE_POINT(spawn_exec, event->dev, cmd);
+                execve(argv[0], argv, envp);
+                _exit(EXIT_FAILURE);
+        }
+
+        /* parent closed child's ends of pipes */
+        outpipe[WRITE_END] = safe_close(outpipe[WRITE_END]);
+        errpipe[WRITE_END] = safe_close(errpipe[WRITE_END]);
+
+        spawn = (Spawn) {
+                .device = event->dev,
+                .cmd = cmd,
+                .pid = pid,
+                .accept_failure = accept_failure,
+                .timeout_warn_usec = udev_warn_timeout(timeout_usec),
+                .timeout_usec = timeout_usec,
+                .timeout_signal = timeout_signal,
+                .event_birth_usec = event->birth_usec,
+                .fd_stdout = outpipe[READ_END],
+                .fd_stderr = errpipe[READ_END],
+                .result = result,
+                .result_size = ressize,
+        };
+        r = spawn_wait(&spawn);
+        if (r < 0)
+                return log_device_error_errno(event->dev, r,
+                                              "Failed to wait for spawned command '%s': %m", cmd);
+
+        if (result)
+                result[spawn.result_len] = '\0';
+
+        if (ret_truncated)
+                *ret_truncated = spawn.truncated;
+
+        return r; /* 0 for success, and positive if the program failed */
+}
+
+void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal) {
+        const char *command;
+        void *val;
+        int r;
+
+        ORDERED_HASHMAP_FOREACH_KEY(val, command, event->run_list) {
+                UdevBuiltinCommand builtin_cmd = PTR_TO_UDEV_BUILTIN_CMD(val);
+
+                if (builtin_cmd != _UDEV_BUILTIN_INVALID) {
+                        log_device_debug(event->dev, "Running built-in command \"%s\"", command);
+                        r = udev_builtin_run(event, builtin_cmd, command, false);
+                        if (r < 0)
+                                log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command);
+                } else {
+                        if (event->exec_delay_usec > 0) {
+                                log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.",
+                                                 command, FORMAT_TIMESPAN(event->exec_delay_usec, USEC_PER_SEC));
+                                (void) usleep_safe(event->exec_delay_usec);
+                        }
+
+                        log_device_debug(event->dev, "Running command \"%s\"", command);
+
+                        r = udev_event_spawn(event, timeout_usec, timeout_signal, false, command, NULL, 0, NULL);
+                        if (r < 0)
+                                log_device_warning_errno(event->dev, r, "Failed to execute '%s', ignoring: %m", command);
+                        else if (r > 0) /* returned value is positive when program fails */
+                                log_device_debug(event->dev, "Command \"%s\" returned %d (error), ignoring.", command, r);
+                }
+        }
+}
diff --git a/src/udev/udev-spawn.h b/src/udev/udev-spawn.h
new file mode 100644 (file)
index 0000000..5efea2e
--- /dev/null
@@ -0,0 +1,28 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+#pragma once
+
+#include <stdbool.h>
+#include <stddef.h>
+
+#include "macro.h"
+#include "time-util.h"
+
+#define READ_END  0
+#define WRITE_END 1
+
+typedef struct UdevEvent UdevEvent;
+
+int 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);
+void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal);
+
+static inline usec_t udev_warn_timeout(usec_t timeout_usec) {
+        return DIV_ROUND_UP(timeout_usec, 3);
+}
index 682ff5672062ed51ccbedac15fe7d2460882f079..8590bf3bf55e40e59f46835025ac4fbab6e41795 100644 (file)
@@ -21,6 +21,7 @@
 #include "strxcpyx.h"
 #include "udev-builtin.h"
 #include "udev-event.h"
+#include "udev-format.h"
 #include "udevadm-util.h"
 #include "udevadm.h"
 
index b545abd3e449f411066ec6e729295e8296a72a3d..a2b164e933a77487b80181958621a0645ea06abf 100644 (file)
 #include "strv.h"
 #include "strxcpyx.h"
 #include "syslog-util.h"
-#include "udevd.h"
 #include "udev-builtin.h"
 #include "udev-ctrl.h"
 #include "udev-event.h"
 #include "udev-node.h"
+#include "udev-spawn.h"
 #include "udev-trace.h"
 #include "udev-util.h"
 #include "udev-watch.h"
+#include "udevd.h"
 #include "user-util.h"
 #include "version.h"