HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/varlink-unit.c

91,016 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 339ec20f2e254c770e3f813b3b5c1281f2f8519e

Lines 1001–1917 of 1,917

                        p->unsupported_property = strjoin("Exec.", p->context.bad_exec_field);
                else if (streq(bad_field, "Service") && !isempty(p->context.bad_service_field))
                        p->unsupported_property = strjoin("Service.", p->context.bad_service_field);
                else
                        p->unsupported_property = strdup(bad_field);
                if (!p->unsupported_property)
                        return -ENOMEM;
        }
        return r;
}
 
static int transient_unit_apply_properties(Unit *u, StartTransientContextParameters *p) {
        int r;
 
        assert(u);
        assert(p);
 
        if (p->description) {
                r = unit_set_description(u, p->description);
                if (r < 0)
                        return r;
                unit_write_settingf(u, UNIT_RUNTIME|UNIT_ESCAPE_SPECIFIERS, "Description", "Description=%s", p->description);
        }
 
        if (p->collect_mode >= 0) {
                u->collect_mode = p->collect_mode;
                unit_write_settingf(u, UNIT_RUNTIME, "CollectMode", "CollectMode=%s", collect_mode_to_string(p->collect_mode));
        }
 
        return 0;
}
 
static int transient_apply_set_credentials(
                Unit *u,
                ExecContext *c,
                const TransientSetCredential *items,
                size_t n_items,
                bool encrypted) {
 
        int r;
 
        assert(u);
        assert(c);
 
        FOREACH_ARRAY(item, items, n_items) {
                const char *err = NULL;
 
                r = exec_context_apply_set_credential(u, c, item->id, item->value.iov_base, item->value.iov_len,
                                                     encrypted, UNIT_RUNTIME|UNIT_PRIVATE, &err);
                if (r == -EINVAL)
                        return log_debug_errno(r, "%s: %s", err, item->id);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int apply_exec_environment(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        int r;
 
        assert(p);
 
        if (!p->environment_set)
                return 0;
 
        r = exec_context_apply_environment(u, c, p->environment, UNIT_RUNTIME|UNIT_PRIVATE);
        if (IN_SET(r, -E2BIG, -EINVAL))
                /* Convert E2BIG into EINVAL so the central loop maps it to Exec.Environment. */
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       r == -E2BIG ? "Too many environment assignments." : "Invalid Environment list.");
        return r;
}
 
static int apply_exec_nice(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        assert(p);
 
        if (!p->nice_set)
                return 0;
 
        if (!nice_is_valid(p->nice))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid Nice= value: %i", p->nice);
 
        c->nice = p->nice;
        c->nice_set = true;
 
        unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "Nice", "Nice=%i", p->nice);
        return 0;
}
 
static int apply_exec_oom_score_adjust(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        if (!p->oom_score_adjust_set)
                return 0;
 
        if (!oom_score_adjust_is_valid(p->oom_score_adjust))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid OOMScoreAdjust= value: %i", p->oom_score_adjust);
 
        c->oom_score_adjust = p->oom_score_adjust;
        c->oom_score_adjust_set = true;
 
        unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "OOMScoreAdjust",
                            "OOMScoreAdjust=%i", p->oom_score_adjust);
        return 0;
}
 
static int apply_exec_set_credential(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        assert(p);
 
        if (!p->set_credentials_set)
                return 0;
        return transient_apply_set_credentials(u, c, p->set_credentials, p->n_set_credentials, /* encrypted= */ false);
}
 
static int apply_exec_set_credential_encrypted(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        assert(p);
 
        if (!p->set_credentials_encrypted_set)
                return 0;
        return transient_apply_set_credentials(u, c, p->set_credentials_encrypted, p->n_set_credentials_encrypted, /* encrypted= */ true);
}
 
static int apply_exec_supplementary_groups(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        _cleanup_free_ char *joined = NULL;
        int r;
 
        assert(p);
 
        if (!p->supplementary_groups)
                return 0;
 
        STRV_FOREACH(g, p->supplementary_groups)
                if (!valid_user_group_name(*g, VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Invalid supplementary group name: %s", *g);
 
        r = strv_extend_strv(&c->supplementary_groups, p->supplementary_groups, /* filter_duplicates= */ true);
        if (r < 0)
                return r;
 
        joined = strv_join(p->supplementary_groups, " ");
        if (!joined)
                return -ENOMEM;
 
        unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, "SupplementaryGroups",
                            "SupplementaryGroups=%s", joined);
        return 0;
}
 
static int apply_exec_umask(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        if (!p->umask_set)
                return 0;
 
        /* mode_t bits beyond 07777 are reserved/meaningless; reject so a caller passing a stray
         * negative or out-of-range int fails clearly instead of having the kernel silently mask it. */
        if (p->umask > 07777)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid UMask= value: %#" PRIo32, p->umask);
 
        c->umask = (mode_t) p->umask;
 
        unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "UMask", "UMask=%04" PRIo32, p->umask);
        return 0;
}
 
static int apply_exec_working_directory(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        _cleanup_free_ char *simplified = NULL;
        TransientWorkingDirectory *wd = &p->working_directory;
        int r;
 
        assert(p);
 
        if (!p->working_directory_set)
                return 0;
 
        if (wd->home && wd->path)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "WorkingDirectory: 'home' and 'path' are mutually exclusive");
        if (!wd->home && !wd->path)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "WorkingDirectory: must specify either 'home' or 'path'");
 
        if (!wd->home) {
                if (!path_is_absolute(wd->path))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "WorkingDirectory: expects an absolute path");
                r = path_simplify_alloc(wd->path, &simplified);
                if (r < 0)
                        return r;
                if (!path_is_normalized(simplified))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "WorkingDirectory: expects a normalized path");
        }
 
        free_and_replace(c->working_directory, simplified);
        c->working_directory_home = wd->home;
        c->working_directory_missing_ok = wd->missing_ok;
 
        unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, "WorkingDirectory",
                            "WorkingDirectory=%s%s",
                            c->working_directory_missing_ok ? "-" : "",
                            c->working_directory_home ? "~" : strempty(c->working_directory));
        return 0;
}
 
/* Generate an apply fn for an exec-context string field: copy the parsed value to ExecContext and
 * write the corresponding "Name=value" line, skipping if the caller didn't set the field.
 * Used where the parsed value is NULL or already validated by the dispatch callback. */
#define DEFINE_APPLY_EXEC_STRING(field, JsonName)                       \
        static int apply_exec_##field(Unit *u, ExecContext *c, TransientExecContextParameters *p) { \
                int r;                                                  \
                                                                        \
                assert(p);                                              \
                                                                        \
                if (!p->field)                                          \
                        return 0;                                       \
                                                                        \
                r = free_and_strdup(&c->field, p->field);               \
                if (r < 0)                                              \
                        return r;                                       \
                                                                        \
                unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, JsonName, \
                                    JsonName "=%s", p->field);          \
                return 0;                                               \
        }
 
DEFINE_APPLY_EXEC_STRING(user,  "User");
DEFINE_APPLY_EXEC_STRING(group, "Group");
 
/* Generate an apply fn for an exec-context tristate bool: copy the parsed value to ExecContext and
 * write the corresponding "Name=yes/no" line, skipping if the caller didn't set the field.
 * Used for the sandbox bool batch where parse and apply are entirely mechanical. */
#define DEFINE_APPLY_EXEC_TRISTATE_BOOL(field, JsonName)                \
        static int apply_exec_##field(Unit *u, ExecContext *c, TransientExecContextParameters *p) { \
                assert(c);                                              \
                assert(p);                                              \
                if (p->field < 0)                                       \
                        return 0;                                       \
                c->field = p->field;                                    \
                unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, JsonName, \
                                    JsonName "=%s", yes_no(p->field));  \
                return 0;                                               \
        }
 
DEFINE_APPLY_EXEC_TRISTATE_BOOL(dynamic_user,              "DynamicUser");
DEFINE_APPLY_EXEC_TRISTATE_BOOL(ignore_sigpipe,            "IgnoreSIGPIPE");
DEFINE_APPLY_EXEC_TRISTATE_BOOL(lock_personality,          "LockPersonality");
DEFINE_APPLY_EXEC_TRISTATE_BOOL(memory_deny_write_execute, "MemoryDenyWriteExecute");
DEFINE_APPLY_EXEC_TRISTATE_BOOL(no_new_privileges,         "NoNewPrivileges");
DEFINE_APPLY_EXEC_TRISTATE_BOOL(remove_ipc,                "RemoveIPC");
DEFINE_APPLY_EXEC_TRISTATE_BOOL(restrict_realtime,         "RestrictRealtime");
DEFINE_APPLY_EXEC_TRISTATE_BOOL(restrict_suid_sgid,        "RestrictSUIDSGID");
DEFINE_APPLY_EXEC_TRISTATE_BOOL(root_ephemeral,            "RootEphemeral");
 
/* Generate an apply fn for an exec-context absolute-path string: validate via path_is_absolute(),
 * copy into ExecContext, write "Name=<path>". Mirrors D-Bus bus_set_transient_path. */
#define DEFINE_APPLY_EXEC_ABSOLUTE_PATH(field, JsonName)                \
        static int apply_exec_##field(Unit *u, ExecContext *c, TransientExecContextParameters *p) { \
                int r;                                                  \
                assert(c);                                              \
                assert(p);                                              \
                if (!p->field)                                          \
                        return 0;                                       \
                if (!path_is_absolute(p->field))                        \
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), \
                                               JsonName ": expects an absolute path"); \
                r = free_and_strdup(&c->field, p->field);               \
                if (r < 0)                                              \
                        return r;                                       \
                unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, JsonName, \
                                    JsonName "=%s", p->field);          \
                return 0;                                               \
        }
 
DEFINE_APPLY_EXEC_ABSOLUTE_PATH(ipc_namespace_path,     "IPCNamespacePath");
DEFINE_APPLY_EXEC_ABSOLUTE_PATH(network_namespace_path, "NetworkNamespacePath");
DEFINE_APPLY_EXEC_ABSOLUTE_PATH(root_directory,         "RootDirectory");
DEFINE_APPLY_EXEC_ABSOLUTE_PATH(root_image,             "RootImage");
DEFINE_APPLY_EXEC_ABSOLUTE_PATH(root_mstack,            "RootMStack");
DEFINE_APPLY_EXEC_ABSOLUTE_PATH(root_verity,            "RootVerity");
DEFINE_APPLY_EXEC_ABSOLUTE_PATH(user_namespace_path,    "UserNamespacePath");
 
/* RootHashPath and RootHashSignaturePath need custom apply fns: the corresponding unit-file
 * directive is "RootHash="/"RootHashSignature=" (not the JSON name), and setting the path form
 * must clear the byte-buffer (iovec) form to match the D-Bus semantics. */
static int apply_exec_root_hash_path(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        int r;
 
        assert(c);
        assert(p);
 
        if (!p->root_hash_path)
                return 0;
 
        if (!path_is_absolute(p->root_hash_path))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "RootHashPath: expects an absolute path");
 
        r = free_and_strdup(&c->root_hash_path, p->root_hash_path);
        if (r < 0)
                return r;
        iovec_done(&c->root_hash);
 
        unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, "RootHash",
                            "RootHash=%s", p->root_hash_path);
        return 0;
}
 
static int apply_exec_root_hash_sig_path(Unit *u, ExecContext *c, TransientExecContextParameters *p) {
        int r;
 
        assert(c);
        assert(p);
 
        if (!p->root_hash_sig_path)
                return 0;
 
        if (!path_is_absolute(p->root_hash_sig_path))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "RootHashSignaturePath: expects an absolute path");
 
        r = free_and_strdup(&c->root_hash_sig_path, p->root_hash_sig_path);
        if (r < 0)
                return r;
        iovec_done(&c->root_hash_sig);
 
        unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, "RootHashSignature",
                            "RootHashSignature=%s", p->root_hash_sig_path);
        return 0;
}
 
/* Per-property descriptor for fields of the Exec context.
 *
 *   json_name     - JSON key inside the Exec object (e.g. "Nice").
 *   err_field     - Qualified field name used for varlink error replies (e.g. "Exec.Nice").
 *   json_type     - Expected JSON type for sd_json_dispatch_full().
 *   dispatch      - Parses the JSON value into TransientExecContextParameters.
 *   parse_offset  - offsetof() into TransientExecContextParameters; 0 if dispatch writes via &p directly.
 *   json_flags    - Per-field flags forwarded to sd_json_dispatch_full().
 *   apply         - Writes the parsed value to ExecContext. Returns 0 on success (whether or not
 *                   the property was set), <0 on error. -EINVAL is mapped to err_field by the
 *                   central loop.
 *   tristate      - If true, the int at parse_offset is initialized to -1 (absent sentinel) by
 *                   transient_exec_context_parameters_init(). Defaults to false.
 */
typedef struct TransientExecProperty {
        const char *json_name;
        const char *err_field;
        sd_json_variant_type_t json_type;
        sd_json_dispatch_callback_t dispatch;
        size_t parse_offset;
        sd_json_dispatch_flags_t json_flags;
        int (*apply)(Unit *u, ExecContext *c, TransientExecContextParameters *p);
        bool tristate;
} TransientExecProperty;
 
/* Property descriptors for the Exec object. Ordered to match src/shared/varlink-io.systemd.Unit.c so related
 * fields (e.g. User/Group) stay close. JSON keys match the D-Bus property names. */
#define EXEC_PROPERTY(json, type, dispatch_fn, parse_offset, json_flags, apply_fn) \
        { json, "Exec." json, type, dispatch_fn, parse_offset, json_flags, apply_fn }
 
/* Tristate-bool property: parsed via sd_json_dispatch_tristate into an int (-1 = absent).
 * Sets .tristate=true so transient_exec_context_parameters_init() seeds the int to -1 before
 * dispatch. */
#define EXEC_PROPERTY_TRISTATE_BOOL(json, field)                                          \
        { json, "Exec." json, SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate,         \
          offsetof(TransientExecContextParameters, field), 0, apply_exec_##field, true }
 
/* String property: dispatched into a const char* field and applied via the matching
 * DEFINE_APPLY_EXEC_STRING() function. dispatch_fn/json_flags vary per field (e.g. User/Group use
 * json_dispatch_const_user_group_name with SD_JSON_RELAX). */
#define EXEC_PROPERTY_STRING(json, field, dispatch_fn, json_flags)                         \
        { json, "Exec." json, SD_JSON_VARIANT_STRING, dispatch_fn,                         \
          offsetof(TransientExecContextParameters, field), json_flags, apply_exec_##field }
 
/* Absolute-path string property: parsed via sd_json_dispatch_const_string + path_is_absolute(). */
#define EXEC_PROPERTY_ABSOLUTE_PATH(json, field)                                          \
        { json, "Exec." json, SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string,      \
          offsetof(TransientExecContextParameters, field), 0, apply_exec_##field }
 
static const TransientExecProperty exec_properties[] = {
        EXEC_PROPERTY              ("WorkingDirectory",       SD_JSON_VARIANT_OBJECT,        dispatch_transient_working_directory,        0,                                                                       0,             apply_exec_working_directory),
        EXEC_PROPERTY_ABSOLUTE_PATH("RootDirectory",          root_directory),
        EXEC_PROPERTY_ABSOLUTE_PATH("RootImage",              root_image),
        EXEC_PROPERTY_ABSOLUTE_PATH("RootMStack",             root_mstack),
        EXEC_PROPERTY_TRISTATE_BOOL("RootEphemeral",          root_ephemeral),
        EXEC_PROPERTY              ("RootHashPath",           SD_JSON_VARIANT_STRING,        sd_json_dispatch_const_string,               offsetof(TransientExecContextParameters, root_hash_path),                0,             apply_exec_root_hash_path),
        EXEC_PROPERTY              ("RootHashSignaturePath",  SD_JSON_VARIANT_STRING,        sd_json_dispatch_const_string,               offsetof(TransientExecContextParameters, root_hash_sig_path),            0,             apply_exec_root_hash_sig_path),
        EXEC_PROPERTY_ABSOLUTE_PATH("RootVerity",             root_verity),
        EXEC_PROPERTY_STRING       ("User",                   user,  json_dispatch_const_user_group_name, SD_JSON_RELAX),
        EXEC_PROPERTY_STRING       ("Group",                  group, json_dispatch_const_user_group_name, SD_JSON_RELAX),
        EXEC_PROPERTY_TRISTATE_BOOL("DynamicUser",            dynamic_user),
        EXEC_PROPERTY              ("SupplementaryGroups",    SD_JSON_VARIANT_ARRAY,         sd_json_dispatch_strv,                       offsetof(TransientExecContextParameters, supplementary_groups),          0,             apply_exec_supplementary_groups),
        EXEC_PROPERTY_TRISTATE_BOOL("NoNewPrivileges",        no_new_privileges),
        EXEC_PROPERTY              ("UMask",                  SD_JSON_VARIANT_INTEGER,       dispatch_transient_umask,                    0,                                                                       0,             apply_exec_umask),
        EXEC_PROPERTY              ("OOMScoreAdjust",         SD_JSON_VARIANT_INTEGER,       dispatch_transient_oom_score_adjust,         0,                                                                       0,             apply_exec_oom_score_adjust),
        EXEC_PROPERTY_TRISTATE_BOOL("IgnoreSIGPIPE",          ignore_sigpipe),
        EXEC_PROPERTY              ("Nice",                   SD_JSON_VARIANT_INTEGER,       dispatch_transient_nice,                     0,                                                                       0,             apply_exec_nice),
        EXEC_PROPERTY_ABSOLUTE_PATH("NetworkNamespacePath",   network_namespace_path),
        EXEC_PROPERTY_ABSOLUTE_PATH("IPCNamespacePath",       ipc_namespace_path),
        EXEC_PROPERTY_ABSOLUTE_PATH("UserNamespacePath",      user_namespace_path),
        EXEC_PROPERTY_TRISTATE_BOOL("LockPersonality",        lock_personality),
        EXEC_PROPERTY_TRISTATE_BOOL("MemoryDenyWriteExecute", memory_deny_write_execute),
        EXEC_PROPERTY_TRISTATE_BOOL("RestrictRealtime",       restrict_realtime),
        EXEC_PROPERTY_TRISTATE_BOOL("RestrictSUIDSGID",       restrict_suid_sgid),
        EXEC_PROPERTY_TRISTATE_BOOL("RemoveIPC",              remove_ipc),
        EXEC_PROPERTY              ("Environment",            _SD_JSON_VARIANT_TYPE_INVALID, dispatch_transient_environment,              0,                                                                       0,             apply_exec_environment),
        EXEC_PROPERTY              ("SetCredential",          SD_JSON_VARIANT_ARRAY,         dispatch_transient_set_credential,           0,                                                                       0,             apply_exec_set_credential),
        EXEC_PROPERTY              ("SetCredentialEncrypted", SD_JSON_VARIANT_ARRAY,         dispatch_transient_set_credential_encrypted, 0,                                                                       0,             apply_exec_set_credential_encrypted),
};
#undef EXEC_PROPERTY
#undef EXEC_PROPERTY_TRISTATE_BOOL
#undef EXEC_PROPERTY_STRING
#undef EXEC_PROPERTY_ABSOLUTE_PATH
 
/* Tristate-bool fields default to -1 (= absent). Default-zeroed slots would look "explicitly false"
 * to the apply path. Initialize all tristate fields here so adding a new tristate property only
 * requires a new exec_properties[] row, never a fresh designated initializer at the call site.
 * The .tristate descriptor flag drives the loop -- mirrors the .cleanup hook used on the Service
 * side, and avoids fragile dispatch-function-pointer equality checks. */
static void transient_exec_context_parameters_init(TransientExecContextParameters *p) {
        assert(p);
        FOREACH_ELEMENT(prop, exec_properties)
                if (prop->tristate)
                        *(int*) ((uint8_t*) p + prop->parse_offset) = -1;
}
 
static int dispatch_transient_exec_context(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
        /* Build dispatch table only once, its constant. */
        static sd_json_dispatch_field exec_dispatch[ELEMENTSOF(exec_properties) + 1] = {};
        static bool exec_dispatch_set = false;
 
        StartTransientContextParameters *p = ASSERT_PTR(userdata);
 
        if (!exec_dispatch_set) {
                FOREACH_ELEMENT(prop, exec_properties)
                        exec_dispatch[prop - exec_properties] = (sd_json_dispatch_field) {
                                .name = prop->json_name,
                                .type = prop->json_type,
                                .callback = prop->dispatch,
                                .offset = prop->parse_offset,
                                .flags = prop->json_flags,
                        };
                exec_dispatch_set = true;
        }
 
        p->exec.present = true;
        return sd_json_dispatch_full(variant, exec_dispatch, /* bad= */ NULL, /* flags= */ 0, &p->exec, &p->bad_exec_field);
}
 
static int transient_exec_context_apply_properties(Unit *u, ExecContext *c, TransientExecContextParameters *p, const char **reterr_field) {
        int r;
 
        assert(u);
        assert(c);
        assert(p);
 
        FOREACH_ELEMENT(prop, exec_properties) {
                r = prop->apply(u, c, p);
                if (r < 0) {
                        if (reterr_field)
                                *reterr_field = r == -EINVAL ? prop->err_field : NULL;
                        return r;
                }
        }
 
        return 0;
}
 
static int transient_service_resolve_one_stdio_fd(
                sd_varlink *link,
                unsigned idx,
                int accmode,
                int *ret_fd) {
 
        int r;
 
        assert(link);
        assert(ret_fd);
 
        if (idx == UINT_MAX) /* not specified */
                return 0;
 
        /* Dup non-destructively off the connection, so that a re-dispatch of the method (e.g. after a
         * deferred polkit authorization) can resolve the same index again. */
        _cleanup_close_ int fd = sd_varlink_peek_dup_fd(link, (size_t) idx);
        if (fd < 0)
                return fd;
 
        r = fd_vet_accmode(fd, accmode);
        if (r < 0)
                return r;
 
        *ret_fd = TAKE_FD(fd);
        return 1;
}
 
/* Resolve stdio fd indices to fds attached to the method call. Ownership of the resolved fds lands in
 * the parameters and is released by transient_service_parameters_done(). */
static int transient_service_resolve_stdio_fds(sd_varlink *link, TransientServiceParameters *sp, const char **reterr_field) {
        int r;
 
        assert(link);
        assert(sp);
 
        r = transient_service_resolve_one_stdio_fd(link, sp->stdin_fd_index, O_RDONLY, &sp->stdin_fd);
        if (r < 0) {
                if (reterr_field)
                        *reterr_field = "Service.StandardInputFileDescriptor";
                return r;
        }
 
        r = transient_service_resolve_one_stdio_fd(link, sp->stdout_fd_index, O_WRONLY, &sp->stdout_fd);
        if (r < 0) {
                if (reterr_field)
                        *reterr_field = "Service.StandardOutputFileDescriptor";
                return r;
        }
 
        r = transient_service_resolve_one_stdio_fd(link, sp->stderr_fd_index, O_WRONLY, &sp->stderr_fd);
        if (r < 0) {
                if (reterr_field)
                        *reterr_field = "Service.StandardErrorFileDescriptor";
                return r;
        }
 
        return 0;
}
 
static int transient_service_apply_properties(Service *s, TransientServiceParameters *sp, const char **reterr_field) {
        Unit *u = UNIT(ASSERT_PTR(s));
        int r;
 
        assert(sp);
 
        if (sp->type >= 0) {
                s->type = sp->type;
                unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "Type", "Type=%s", service_type_to_string(sp->type));
        }
 
        /* Passed stdio fds, resolved earlier by transient_service_resolve_stdio_fds(): store them on the
         * Service and flag the exec context. Not written as a text setting; fd serialization across
         * reexec is handled by service_serialize(). */
        if (sp->stdin_fd >= 0) {
                asynchronous_close(s->stdin_fd);
                s->stdin_fd = TAKE_FD(sp->stdin_fd);
                s->exec_context.stdio_as_fds = true;
        }
        if (sp->stdout_fd >= 0) {
                asynchronous_close(s->stdout_fd);
                s->stdout_fd = TAKE_FD(sp->stdout_fd);
                s->exec_context.stdio_as_fds = true;
        }
        if (sp->stderr_fd >= 0) {
                asynchronous_close(s->stderr_fd);
                s->stderr_fd = TAKE_FD(sp->stderr_fd);
                s->exec_context.stdio_as_fds = true;
        }
 
        if (sp->remain_after_exit >= 0) {
                s->remain_after_exit = sp->remain_after_exit;
                unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "RemainAfterExit", "RemainAfterExit=%s", yes_no(sp->remain_after_exit));
        }
 
        FOREACH_ARRAY(item, sp->exec_start, sp->n_exec_start) {
                _cleanup_(exec_command_freep) ExecCommand *c = NULL;
                _cleanup_strv_free_ char **argv = NULL;
 
                if (!filename_or_absolute_path_is_valid(item->path)) {
                        if (reterr_field)
                                *reterr_field = "Service.ExecStart";
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid ExecStart path: %s", item->path);
                }
 
                if (!strv_isempty(item->arguments)) {
                        argv = strv_copy(item->arguments);
                        if (!argv)
                                return -ENOMEM;
                }
 
                c = new0(ExecCommand, 1);
                if (!c)
                        return -ENOMEM;
 
                r = path_simplify_alloc(item->path, &c->path);
                if (r < 0)
                        return r;
 
                /* If no arguments were provided, default argv[0] to the executable path.
                 * Otherwise the caller is expected to include argv[0] in the arguments array. */
                if (strv_isempty(argv)) {
                        r = strv_extend(&argv, c->path);
                        if (r < 0)
                                return r;
                }
 
                c->argv = TAKE_PTR(argv);
 
                exec_command_append_list(&s->exec_command[SERVICE_EXEC_START], TAKE_PTR(c));
        }
 
        /* Write ExecStart= lines to the transient file */
        if (sp->n_exec_start > 0) {
                UnitWriteFlags esc_flags = UNIT_ESCAPE_SPECIFIERS|UNIT_ESCAPE_EXEC_SYNTAX_ENV;
 
                LIST_FOREACH(command, c, s->exec_command[SERVICE_EXEC_START]) {
                        _cleanup_free_ char *a = NULL;
 
                        a = unit_concat_strv(c->argv, esc_flags);
                        if (!a)
                                return -ENOMEM;
 
                        /* streq() instead path_equal() as argv[0] can be arbitrary and may not be a path */
                        if (streq(c->path, c->argv[0]))
                                unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "ExecStart", "ExecStart=%s", a);
                        else {
                                _cleanup_free_ char *t = NULL;
                                const char *p;
 
                                p = unit_escape_setting(c->path, esc_flags, &t);
                                if (!p)
                                        return -ENOMEM;
 
                                unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "ExecStart", "ExecStart=@%s %s", p, a);
                        }
                }
        }
 
        return 0;
}
 
int vl_method_start_transient_unit(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
        static const sd_json_dispatch_field dispatch_table[] = {
                { "context",            SD_JSON_VARIANT_OBJECT,  dispatch_transient_context, 0,                                                       SD_JSON_MANDATORY },
                { "mode",               SD_JSON_VARIANT_STRING,  dispatch_job_mode,          offsetof(StartTransientParameters, mode),                0                 },
                { "notifyJobChanges",   SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate,  offsetof(StartTransientParameters, notify_job_changes),  0                 },
                { "notifyUnitChanges",  SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate,  offsetof(StartTransientParameters, notify_unit_changes), 0                 },
                {}
        };
 
        _cleanup_(sd_bus_error_free) sd_bus_error bus_error = SD_BUS_ERROR_NULL;
        _cleanup_(start_transient_parameters_done) StartTransientParameters p = {};
        Manager *manager = ASSERT_PTR(userdata);
        const char *bad_field = NULL;
        Unit *u;
        int r;
 
        assert(link);
        assert(parameters);
 
        start_transient_parameters_init(&p);
 
        r = mac_selinux_access_check_varlink(link, "start");
        if (r < 0)
                return r;
 
        r = sd_json_dispatch_full(parameters, dispatch_table, /* bad= */ NULL, /* flags= */ 0, &p, &bad_field);
        if (r < 0) {
                /* An unknown field in 'context' maps to PropertyNotSupported (the field is defined in the
                 * UnitContext schema but cannot be set at creation time). Anything else is a bad parameter. */
                if (streq_ptr(bad_field, "context") && r == -EADDRNOTAVAIL && p.unsupported_property)
                        return sd_varlink_errorbo(
                                        link,
                                        "io.systemd.Unit.PropertyNotSupported",
                                        SD_JSON_BUILD_PAIR_STRING("property", p.unsupported_property));
                if (bad_field)
                        return sd_varlink_error_invalid_parameter_name(link, bad_field);
                return r;
        }
 
        /* Pre-check unit type early and return targeted varlink error as manager_setup_transient_unit() the
         * too generic SD_BUS_ERROR_INVALID_ARGS. */
        UnitType t = unit_name_to_type(p.context.id);
        if (t < 0)
                return sd_varlink_error_invalid_parameter_name(link, "context");
        if (!unit_vtable[t]->can_transient)
                return sd_varlink_error(link, VARLINK_ERROR_UNIT_TYPE_NOT_SUPPORTED, NULL);
 
        r = varlink_verify_polkit_async(
                        link,
                        manager->system_bus,
                        "org.freedesktop.systemd1.manage-units",
                        (const char**) STRV_MAKE(
                                        "unit", p.context.id,
                                        "verb", "start",
                                        "polkit.message", N_("Authentication is required to start transient unit '$(unit)'."),
                                        "polkit.gettext_domain", GETTEXT_PACKAGE),
                        &manager->polkit_registry);
        if (r <= 0)
                return r;
 
        /* Resolve stdio fd indices against the fds attached to this method call before the unit exists,
         * so a failure (bad index, wrong access mode) doesn't leave a half-configured transient unit. */
        bad_field = NULL;
        r = transient_service_resolve_stdio_fds(link, &p.context.service, &bad_field);
        if (IN_SET(r, -ENXIO, -EPROTOTYPE, -EBADFD, -EISDIR)) /* bad index or unsuitable fd */
                return sd_varlink_error_invalid_parameter_name(link, bad_field ?: "Service");
        if (r < 0)
                return sd_varlink_error_errno(link, r);
 
        r = manager_setup_transient_unit(manager, p.context.id, &u, &bus_error);
        if (r < 0)
                return varlink_reply_bus_error(link, r, &bus_error);
 
        /* Apply unit-level properties from context */
        r = transient_unit_apply_properties(u, &p.context);
        if (r == -EINVAL)
                return sd_varlink_error_invalid_parameter_name(link, "context");
        if (r < 0)
                return sd_varlink_error_errno(link, r);
 
        /* Apply context.Exec only when an Exec object was actually sent. The tristate bool fields are
         * seeded to -1 ("absent") during Exec dispatch; without an Exec object they stay 0, which the
         * apply functions would misread as "explicitly false" and write out bogus FooBar=no lines. */
        if (p.context.exec.present) {
                ExecContext *c = unit_get_exec_context(u);
                if (!c)
                        return sd_varlink_error(link, VARLINK_ERROR_UNIT_TYPE_NOT_SUPPORTED, NULL);
 
                bad_field = NULL;
                r = transient_exec_context_apply_properties(u, c, &p.context.exec, &bad_field);
                if (r == -EINVAL)
                        return sd_varlink_error_invalid_parameter_name(link, bad_field ?: "Exec");
                if (r < 0)
                        return sd_varlink_error_errno(link, r);
        }
 
        /* Apply service-specific properties from context.Service */
        Service *s = SERVICE(u);
        if (s) {
                bad_field = NULL;
                r = transient_service_apply_properties(s, &p.context.service, &bad_field);
                if (r == -EINVAL)
                        return sd_varlink_error_invalid_parameter_name(link, bad_field ?: "Service");
                if (r < 0)
                        return sd_varlink_error_errno(link, r);
        } else if (p.context.service.present)
                return sd_varlink_error(link, VARLINK_ERROR_UNIT_TYPE_NOT_SUPPORTED, NULL);
 
        unit_add_to_load_queue(u);
        manager_dispatch_load_queue(manager);
 
        if (u->load_state == UNIT_BAD_SETTING)
                return sd_varlink_error_invalid_parameter_name(link, "context");
        if (!UNIT_IS_LOAD_COMPLETE(u->load_state))
                return sd_varlink_error(link, VARLINK_ERROR_UNIT_NO_SUCH_UNIT, NULL);
 
        Job *j;
        r = varlink_unit_queue_job_one(
                        u,
                        JOB_START,
                        p.mode,
                        /* reload_if_possible= */ false,
                        /* ret_job_id= */ NULL,
                        &j,
                        &bus_error);
        if (r < 0)
                return varlink_reply_bus_error(link, r, &bus_error);
 
        bool notify_job = p.notify_job_changes > 0;
        bool notify_unit = p.notify_unit_changes > 0;
 
        /* Non-streaming, or fire-and-forget (no notification flags set): return full unit context
         * and runtime, plus the job object so the caller can correlate with later state. */
        if (!FLAGS_SET(flags, SD_VARLINK_METHOD_MORE) || (!notify_job && !notify_unit))
                return sd_varlink_replybo(
                                link,
                                SD_JSON_BUILD_PAIR_CALLBACK("context", unit_context_build_json, u),
                                SD_JSON_BUILD_PAIR_CALLBACK("runtime", unit_runtime_build_json, u),
                                SD_JSON_BUILD_PAIR_CALLBACK("job", job_build_json, j));
 
        /* Streaming: always attach to the job for the final reply, and optionally to the unit for state
         * change notifications. j->varlink owns the stream lifetime, u->varlink_unit_change is just a flag
         * to also send unit state notifications along the way. */
        assert(!j->varlink);
        j->varlink = sd_varlink_ref(link);
        j->varlink_notify_job_changes = notify_job;
        if (notify_unit) {
                assert(!u->varlink_unit_change);
                u->varlink_unit_change = sd_varlink_ref(link);
        }
 
        /* Send initial job state notification if requested. Unit state change notifications are not sent
         * here; they will arrive via varlink_unit_send_change_signal() when the unit actually transitions,
         * matching D-Bus PropertiesChanged behavior. */
        if (notify_job)
                return sd_varlink_notifybo(
                                link,
                                SD_JSON_BUILD_PAIR_CALLBACK("job", job_build_json, j));
 
        return 0;
}
 
typedef struct UnitSetPropertiesParameters {
        const char *unsupported_property; /* For error reporting */
        const char *name;
        bool runtime;
 
        bool markers_found;
        unsigned markers, markers_mask;
} UnitSetPropertiesParameters;
 
static int parse_unit_markers(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
        UnitSetPropertiesParameters *p = ASSERT_PTR(userdata);
        bool some_plus_minus = false, some_absolute = false;
        unsigned settings = 0, mask = 0;
        sd_json_variant *e;
        int r;
 
        assert(variant);
 
        JSON_VARIANT_ARRAY_FOREACH(e, variant) {
                if (!sd_json_variant_is_string(e))
                        return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "Marker is not an array of strings.");
 
                const char *word = sd_json_variant_string(e);
 
                r = parse_unit_marker(word, &settings, &mask);
                if (r < 0)
                        return json_log(variant, flags, r, "Failed to parse marker '%s'.", word);
                if (r > 0)
                        some_plus_minus = true;
                else
                        some_absolute = true;
        }
 
        if (some_plus_minus && some_absolute)
                return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "Absolute and non-absolute markers in the same setting.");
 
        if (some_absolute || sd_json_variant_elements(variant) == 0)
                mask = UINT_MAX;
 
        p->markers = settings;
        p->markers_mask = mask;
        p->markers_found = true;
 
        return 0;
}
 
static int unit_dispatch_properties(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
        static const sd_json_dispatch_field dispatch_table[] = {
                { "Markers", SD_JSON_VARIANT_ARRAY, parse_unit_markers, 0, 0 },
                {}
        };
        UnitSetPropertiesParameters *p = ASSERT_PTR(userdata);
        const char *bad_field = NULL;
        int r;
 
        r = sd_json_dispatch_full(variant, dispatch_table, /* bad= */ NULL, flags, userdata, &bad_field);
        if (r == -EADDRNOTAVAIL && !isempty(bad_field))
                /* When properties contains a valid field, but that we don't currently support, make sure to
                 * return the offending property, rather than generic invalid argument. */
                p->unsupported_property = bad_field;
        return r;
}
 
int vl_method_set_unit_properties(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
        static const sd_json_dispatch_field dispatch_table[] = {
                { "name",       SD_JSON_VARIANT_STRING,  json_dispatch_const_unit_name, offsetof(UnitSetPropertiesParameters, name),    SD_JSON_MANDATORY },
                { "runtime",    SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool,      offsetof(UnitSetPropertiesParameters, runtime), SD_JSON_MANDATORY },
                { "properties", SD_JSON_VARIANT_OBJECT,  unit_dispatch_properties,      0,                                              SD_JSON_MANDATORY },
                {}
        };
 
        UnitSetPropertiesParameters p = {};
        Manager *manager = ASSERT_PTR(userdata);
        const char *bad_field = NULL;
        Unit *unit;
        int r;
 
        assert(link);
        assert(parameters);
 
        r = sd_json_dispatch_full(parameters, dispatch_table, /* bad= */ NULL, /* flags= */ 0, &p, &bad_field);
        if (r < 0) {
                /* When properties contains a valid field, but that we don't currently support, make sure to
                 * return a specific error, rather than generic invalid argument. */
                if (streq_ptr(bad_field, "properties") && r == -EADDRNOTAVAIL)
                        return sd_varlink_errorbo(
                                link,
                                "io.systemd.Unit.PropertyNotSupported",
                                SD_JSON_BUILD_PAIR_CONDITION(!!p.unsupported_property, "property", SD_JSON_BUILD_STRING(p.unsupported_property)));
                if (bad_field)
                        return sd_varlink_error_invalid_parameter_name(link, bad_field);
                return r;
        }
 
        /* Only Markers is supported, and it cannot be persisted as unit configuration. */
        if (!p.runtime)
                return sd_varlink_errorbo(
                                link,
                                "io.systemd.Unit.PropertyNotSupported",
                                SD_JSON_BUILD_PAIR_STRING("property", "runtime"));
 
        r = load_unit_and_check(link, manager, p.name, &unit);
        if (r < 0)
                return r;
 
        r = mac_selinux_unit_access_check_varlink(unit, link, "start");
        if (r < 0)
                return sd_varlink_error(link, SD_VARLINK_ERROR_PERMISSION_DENIED, NULL);
 
        r = varlink_verify_polkit_async(
                        link,
                        manager->system_bus,
                        "org.freedesktop.systemd1.manage-units",
                        /* details= */ NULL,
                        &manager->polkit_registry);
        if (r <= 0)
                return r;
 
        if (p.markers_found)
                unit->markers = unit_normalize_markers((unit->markers & ~p.markers_mask), p.markers);
 
        return sd_varlink_reply(link, NULL);
}