Debian Codegraph @

src/core/varlink-unit.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-bus.h"
4 #include "sd-json.h"
5
6 #include "bitfield.h"
7 #include "bus-polkit.h"
8 #include "cgroup.h"
9 #include "condition.h"
10 #include "dbus-job.h"
11 #include "execute.h"
12 #include "format-util.h"
13 #include "install.h"
14 #include "iovec-util.h"
15 #include "job.h"
16 #include "json-util.h"
17 #include "locale-util.h"
18 #include "manager.h"
19 #include "path-util.h"
20 #include "pidref.h"
21 #include "process-util.h"
22 #include "selinux-access.h"
23 #include "service.h"
24 #include "set.h"
25 #include "strv.h"
26 #include "unit-name.h"
27 #include "unit.h"
28 #include "user-util.h"
29 #include "varlink-automount.h"
30 #include "varlink-cgroup.h"
31 #include "varlink-common.h"
32 #include "varlink-execute.h"
33 #include "varlink-job.h"
34 #include "varlink-kill.h"
35 #include "varlink-mount.h"
36 #include "varlink-path.h"
37 #include "varlink-scope.h"
38 #include "varlink-service.h"
39 #include "varlink-socket.h"
40 #include "varlink-swap.h"
41 #include "varlink-timer.h"
42 #include "varlink-unit.h"
43 #include "varlink-util.h"
44
45 #define JSON_BUILD_EMERGENCY_ACTION_NON_EMPTY(name, value) \
46 SD_JSON_BUILD_PAIR_CONDITION(value > EMERGENCY_ACTION_NONE, name, JSON_BUILD_STRING_UNDERSCORIFY(emergency_action_to_string(value)))
47
48 static int unit_dependencies_build_json(sd_json_variant **ret, const char *name, void *userdata) {
49 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
50 Unit *u = ASSERT_PTR(userdata);
51 UnitDependency d;
52 int r;
53
54 assert(ret);
55 assert(name);
56
57 d = unit_dependency_from_string(name);
58 if (d < 0)
59 return log_debug_errno(d, "Failed to get unit dependency for '%s': %m", name);
60
61 void *value;
62 Unit *other;
63 HASHMAP_FOREACH_KEY(value, other, unit_get_dependencies(u, d)) {
64 r = sd_json_variant_append_arrayb(&v, SD_JSON_BUILD_STRING(other->id));
65 if (r < 0)
66 return r;
67 }
68
69 *ret = TAKE_PTR(v);
70 return 0;
71 }
72
73 static int unit_mounts_for_build_json(sd_json_variant **ret, const char *name, void *userdata) {
74 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
75 Hashmap **mounts_for = userdata;
76 UnitMountDependencyType d;
77 const char *p;
78 void *value;
79 int r;
80
81 assert(ret);
82 assert(name);
83
84 if (!mounts_for) {
85 *ret = NULL;
86 return 0;
87 }
88
89 d = unit_mount_dependency_type_from_string(name);
90 if (d < 0)
91 return log_debug_errno(d, "Failed to get unit mount dependency for '%s': %m", name);
92
93 HASHMAP_FOREACH_KEY(value, p, mounts_for[d]) {
94 r = sd_json_variant_append_arrayb(&v, SD_JSON_BUILD_STRING(p));
95 if (r < 0)
96 return r;
97 }
98
99 *ret = TAKE_PTR(v);
100 return 0;
101 }
102
103 static int unit_conditions_build_json(sd_json_variant **ret, const char *name, void *userdata) {
104 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
105 bool do_asserts = streq(name, "Asserts");
106 Condition *list = userdata;
107 int r;
108
109 assert(ret);
110
111 LIST_FOREACH(conditions, c, list) {
112 r = sd_json_variant_append_arraybo(
113 &v,
114 SD_JSON_BUILD_PAIR_STRING("type", do_asserts ? assert_type_to_string(c->type)
115 : condition_type_to_string(c->type)),
116 SD_JSON_BUILD_PAIR_BOOLEAN("trigger", c->trigger),
117 SD_JSON_BUILD_PAIR_BOOLEAN("negate", c->negate),
118 JSON_BUILD_PAIR_STRING_NON_EMPTY("parameter", c->parameter));
119 if (r < 0)
120 return r;
121 }
122
123 *ret = TAKE_PTR(v);
124 return 0;
125 }
126
127 static int unit_context_build_json(sd_json_variant **ret, const char *name, void *userdata) {
128 Unit *u = ASSERT_PTR(userdata);
129
130 /* The main principle behind context/runtime split is the following:
131 * If it make sense to place a property into a config/unit file it belongs to Context.
132 * Otherwise it's a 'Runtime'. */
133
134 /* TODO missing callbacks */
135 static const sd_json_build_callback_t unit_type_callbacks[_UNIT_TYPE_MAX] = {
136 [UNIT_AUTOMOUNT] = automount_context_build_json,
137 [UNIT_MOUNT] = mount_context_build_json,
138 [UNIT_PATH] = path_context_build_json,
139 [UNIT_SCOPE] = scope_context_build_json,
140 [UNIT_SERVICE] = service_context_build_json,
141 [UNIT_SOCKET] = socket_context_build_json,
142 [UNIT_SWAP] = swap_context_build_json,
143 [UNIT_TIMER] = timer_context_build_json,
144 };
145
146 return sd_json_buildo(
147 ASSERT_PTR(ret),
148 SD_JSON_BUILD_PAIR_STRING("Type", unit_type_to_string(u->type)),
149 SD_JSON_BUILD_PAIR_STRING("ID", u->id),
150 SD_JSON_BUILD_PAIR_CONDITION(!set_isempty(u->aliases), "Names", JSON_BUILD_STRING_SET(u->aliases)),
151
152 /* [Unit] Section Options
153 * https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html#%5BUnit%5D%20Section%20Options */
154 JSON_BUILD_PAIR_STRING_NON_EMPTY("Description", u->description),
155 JSON_BUILD_PAIR_STRV_NON_EMPTY("Documentation", u->documentation),
156 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Wants", unit_dependencies_build_json, u),
157 JSON_BUILD_PAIR_CALLBACK_NON_NULL("WantedBy", unit_dependencies_build_json, u),
158 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Requires", unit_dependencies_build_json, u),
159 JSON_BUILD_PAIR_CALLBACK_NON_NULL("RequiredBy", unit_dependencies_build_json, u),
160 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Requisite", unit_dependencies_build_json, u),
161 JSON_BUILD_PAIR_CALLBACK_NON_NULL("RequisiteOf", unit_dependencies_build_json, u),
162 JSON_BUILD_PAIR_CALLBACK_NON_NULL("BindsTo", unit_dependencies_build_json, u),
163 JSON_BUILD_PAIR_CALLBACK_NON_NULL("BoundBy", unit_dependencies_build_json, u),
164 JSON_BUILD_PAIR_CALLBACK_NON_NULL("PartOf", unit_dependencies_build_json, u),
165 JSON_BUILD_PAIR_CALLBACK_NON_NULL("ConsistsOf", unit_dependencies_build_json, u),
166 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Upholds", unit_dependencies_build_json, u),
167 JSON_BUILD_PAIR_CALLBACK_NON_NULL("UpheldBy", unit_dependencies_build_json, u),
168 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Conflicts", unit_dependencies_build_json, u),
169 JSON_BUILD_PAIR_CALLBACK_NON_NULL("ConflictedBy", unit_dependencies_build_json, u),
170 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Before", unit_dependencies_build_json, u),
171 JSON_BUILD_PAIR_CALLBACK_NON_NULL("After", unit_dependencies_build_json, u),
172 JSON_BUILD_PAIR_CALLBACK_NON_NULL("OnFailure", unit_dependencies_build_json, u),
173 JSON_BUILD_PAIR_CALLBACK_NON_NULL("OnFailureOf", unit_dependencies_build_json, u),
174 JSON_BUILD_PAIR_CALLBACK_NON_NULL("OnSuccess", unit_dependencies_build_json, u),
175 JSON_BUILD_PAIR_CALLBACK_NON_NULL("OnSuccessOf", unit_dependencies_build_json, u),
176 JSON_BUILD_PAIR_CALLBACK_NON_NULL("PropagatesReloadTo", unit_dependencies_build_json, u),
177 JSON_BUILD_PAIR_CALLBACK_NON_NULL("ReloadPropagatedFrom", unit_dependencies_build_json, u),
178 JSON_BUILD_PAIR_CALLBACK_NON_NULL("PropagatesStopTo", unit_dependencies_build_json, u),
179 JSON_BUILD_PAIR_CALLBACK_NON_NULL("StopPropagatedFrom", unit_dependencies_build_json, u),
180 JSON_BUILD_PAIR_CALLBACK_NON_NULL("JoinsNamespaceOf", unit_dependencies_build_json, u),
181 JSON_BUILD_PAIR_CALLBACK_NON_NULL("RequiresMountsFor", unit_mounts_for_build_json, &u->mounts_for),
182 JSON_BUILD_PAIR_CALLBACK_NON_NULL("WantsMountsFor", unit_mounts_for_build_json, &u->mounts_for),
183 JSON_BUILD_PAIR_ENUM("OnSuccessJobMode", job_mode_to_string(u->on_success_job_mode)),
184 JSON_BUILD_PAIR_ENUM("OnFailureJobMode", job_mode_to_string(u->on_failure_job_mode)),
185 SD_JSON_BUILD_PAIR_BOOLEAN("IgnoreOnIsolate", u->ignore_on_isolate),
186 SD_JSON_BUILD_PAIR_BOOLEAN("StopWhenUnneeded", u->stop_when_unneeded),
187 SD_JSON_BUILD_PAIR_BOOLEAN("RefuseManualStart", u->refuse_manual_start),
188 SD_JSON_BUILD_PAIR_BOOLEAN("RefuseManualStop", u->refuse_manual_stop),
189 SD_JSON_BUILD_PAIR_BOOLEAN("AllowIsolate", u->allow_isolate),
190 SD_JSON_BUILD_PAIR_BOOLEAN("DefaultDependencies", u->default_dependencies),
191 SD_JSON_BUILD_PAIR_BOOLEAN("SurviveFinalKillSignal", u->survive_final_kill_signal),
192 JSON_BUILD_PAIR_ENUM("CollectMode", collect_mode_to_string(u->collect_mode)),
193 JSON_BUILD_EMERGENCY_ACTION_NON_EMPTY("FailureAction", u->failure_action),
194 JSON_BUILD_EMERGENCY_ACTION_NON_EMPTY("SuccessAction", u->success_action),
195 JSON_BUILD_PAIR_INTEGER_NON_NEGATIVE("FailureActionExitStatus", u->failure_action_exit_status),
196 JSON_BUILD_PAIR_INTEGER_NON_NEGATIVE("SuccessActionExitStatus", u->success_action_exit_status),
197 JSON_BUILD_PAIR_FINITE_USEC("JobTimeoutUSec", u->job_timeout),
198 JSON_BUILD_PAIR_FINITE_USEC("JobRunningTimeoutUSec", u->job_running_timeout),
199 JSON_BUILD_EMERGENCY_ACTION_NON_EMPTY("JobTimeoutAction", u->job_timeout_action),
200 JSON_BUILD_PAIR_STRING_NON_EMPTY("JobTimeoutRebootArgument", u->job_timeout_reboot_arg),
201 JSON_BUILD_PAIR_RATELIMIT_ENABLED("StartLimit", &u->start_ratelimit),
202 JSON_BUILD_EMERGENCY_ACTION_NON_EMPTY("StartLimitAction", u->start_limit_action),
203 JSON_BUILD_PAIR_STRING_NON_EMPTY("RebootArgument", u->reboot_arg),
204
205 /* Conditions and Asserts
206 * https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html#Conditions%20and%20Asserts */
207 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Conditions", unit_conditions_build_json, u->conditions),
208 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Asserts", unit_conditions_build_json, u->asserts),
209
210 /* Others */
211 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Triggers", unit_dependencies_build_json, u),
212 JSON_BUILD_PAIR_CALLBACK_NON_NULL("TriggeredBy", unit_dependencies_build_json, u),
213 JSON_BUILD_PAIR_STRING_NON_EMPTY("AccessSELinuxContext", u->access_selinux_context),
214 JSON_BUILD_PAIR_STRING_NON_EMPTY("FragmentPath", u->fragment_path),
215 JSON_BUILD_PAIR_STRING_NON_EMPTY("SourcePath", u->source_path),
216 JSON_BUILD_PAIR_STRV_NON_EMPTY("DropInPaths", u->dropin_paths),
217 JSON_BUILD_PAIR_STRING_NON_EMPTY("UnitFilePreset", preset_action_past_tense_to_string(unit_get_unit_file_preset(u))),
218 SD_JSON_BUILD_PAIR_BOOLEAN("Transient", u->transient),
219 SD_JSON_BUILD_PAIR_BOOLEAN("Perpetual", u->perpetual),
220 SD_JSON_BUILD_PAIR_BOOLEAN("DebugInvocation", u->debug_invocation),
221
222 JSON_BUILD_PAIR_CALLBACK_NON_NULL("CGroup", unit_cgroup_context_build_json, u),
223 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Exec", unit_exec_context_build_json, u),
224 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Kill", unit_kill_context_build_json, unit_get_kill_context(u)),
225 JSON_BUILD_PAIR_CALLBACK_NON_NULL(unit_type_to_capitalized_string(u->type), unit_type_callbacks[u->type], u));
226 }
227
228 static int can_clean_build_json(sd_json_variant **ret, const char *name, void *userdata) {
229 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
230 Unit *u = ASSERT_PTR(userdata);
231 ExecCleanMask mask;
232 int r;
233
234 assert(ret);
235
236 r = unit_can_clean(u, &mask);
237 if (r < 0)
238 return log_debug_errno(r, "Failed to check if unit can be cleaned: %m");
239
240 for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
241 if (!BIT_SET(mask, t))
242 continue;
243
244 r = sd_json_variant_append_arrayb(&v, SD_JSON_BUILD_STRING(exec_resource_type_to_string(t)));
245 if (r < 0)
246 return r;
247 }
248
249 if (FLAGS_SET(mask, EXEC_CLEAN_FDSTORE)) {
250 r = sd_json_variant_append_arrayb(&v, JSON_BUILD_CONST_STRING("fdstore"));
251 if (r < 0)
252 return r;
253 }
254
255 *ret = TAKE_PTR(v);
256 return 0;
257 }
258
259 static int markers_build_json(sd_json_variant **ret, const char *name, void *userdata) {
260 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
261 unsigned *markers = ASSERT_PTR(userdata);
262 int r;
263
264 assert(ret);
265
266 BIT_FOREACH(m, *markers) {
267 r = sd_json_variant_append_arrayb(&v, SD_JSON_BUILD_STRING(unit_marker_to_string(m)));
268 if (r < 0)
269 return r;
270 }
271
272 *ret = TAKE_PTR(v);
273 return 0;
274 }
275
276 static int activation_details_build_json(sd_json_variant **ret, const char *name, void *userdata) {
277 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
278 const ActivationDetails *activation_details = userdata;
279 _cleanup_strv_free_ char **pairs = NULL;
280 int r;
281
282 assert(ret);
283
284 /* activation_details_append_pair() gracefully takes activation_details==NULL */
285 r = activation_details_append_pair(activation_details, &pairs);
286 if (r < 0)
287 return log_debug_errno(r, "Failed to get activation details: %m");
288
289 STRV_FOREACH_PAIR(key, value, pairs) {
290 r = sd_json_variant_append_arraybo(&v,
291 SD_JSON_BUILD_PAIR_STRING("type", *key),
292 SD_JSON_BUILD_PAIR_STRING("name", *value));
293 if (r < 0)
294 return r;
295 }
296
297 *ret = TAKE_PTR(v);
298 return 0;
299 }
300
301 static int unit_runtime_build_json(sd_json_variant **ret, const char *name, void *userdata) {
302 Unit *u = ASSERT_PTR(userdata);
303 Unit *f = unit_following(u);
304
305 /* TODO missing callbacks */
306 static const sd_json_build_callback_t unit_type_callbacks[_UNIT_TYPE_MAX] = {
307 [UNIT_AUTOMOUNT] = automount_runtime_build_json,
308 [UNIT_MOUNT] = mount_runtime_build_json,
309 [UNIT_PATH] = path_runtime_build_json,
310 [UNIT_SCOPE] = scope_runtime_build_json,
311 [UNIT_SERVICE] = service_runtime_build_json,
312 [UNIT_SOCKET] = socket_runtime_build_json,
313 [UNIT_SWAP] = swap_runtime_build_json,
314 [UNIT_TIMER] = timer_runtime_build_json,
315 };
316
317 return sd_json_buildo(
318 ASSERT_PTR(ret),
319 JSON_BUILD_PAIR_STRING_NON_EMPTY("Following", f ? f->id : NULL),
320 SD_JSON_BUILD_PAIR_STRING("LoadState", unit_load_state_to_string(u->load_state)),
321 SD_JSON_BUILD_PAIR_STRING("ActiveState", unit_active_state_to_string(unit_active_state(u))),
322 SD_JSON_BUILD_PAIR_STRING("FreezerState", freezer_state_to_string(u->freezer_state)),
323 SD_JSON_BUILD_PAIR_STRING("SubState", unit_sub_state_to_string(u)),
324 JSON_BUILD_PAIR_STRING_NON_EMPTY("UnitFileState", unit_file_state_to_string(unit_get_unit_file_state(u))),
325 JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL("StateChangeTimestamp", &u->state_change_timestamp),
326 JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL("ActiveEnterTimestamp", &u->active_enter_timestamp),
327 JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL("ActiveExitTimestamp", &u->active_exit_timestamp),
328 JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL("InactiveEnterTimestamp", &u->inactive_enter_timestamp),
329 JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL("InactiveExitTimestamp", &u->inactive_exit_timestamp),
330 SD_JSON_BUILD_PAIR_BOOLEAN("CanStart", unit_can_start_refuse_manual(u)),
331 SD_JSON_BUILD_PAIR_BOOLEAN("CanStop", unit_can_stop_refuse_manual(u)),
332 SD_JSON_BUILD_PAIR_BOOLEAN("CanReload", unit_can_reload(u)),
333 SD_JSON_BUILD_PAIR_BOOLEAN("CanIsolate", unit_can_isolate_refuse_manual(u)),
334 JSON_BUILD_PAIR_CALLBACK_NON_NULL("CanClean", can_clean_build_json, u),
335 SD_JSON_BUILD_PAIR_BOOLEAN("CanFreeze", unit_can_freeze(u)),
336 SD_JSON_BUILD_PAIR_BOOLEAN("CanLiveMount", unit_can_live_mount(u, /* reterr_error= */ NULL) >= 0),
337 JSON_BUILD_PAIR_UNSIGNED_NON_ZERO("JobId", u->job ? u->job->id : 0),
338 SD_JSON_BUILD_PAIR_BOOLEAN("NeedDaemonReload", unit_need_daemon_reload(u)),
339 SD_JSON_BUILD_PAIR_BOOLEAN("ConditionResult", u->condition_result),
340 SD_JSON_BUILD_PAIR_BOOLEAN("AssertResult", u->assert_result),
341 JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL("ConditionTimestamp", &u->condition_timestamp),
342 JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL("AssertTimestamp", &u->assert_timestamp),
343 SD_JSON_BUILD_PAIR_CONDITION(!sd_id128_is_null(u->invocation_id), "InvocationID", SD_JSON_BUILD_UUID(u->invocation_id)),
344 JSON_BUILD_PAIR_CALLBACK_NON_NULL("Markers", markers_build_json, &u->markers),
345 JSON_BUILD_PAIR_CALLBACK_NON_NULL("ActivationDetails", activation_details_build_json, u->activation_details),
346 JSON_BUILD_PAIR_CALLBACK_NON_NULL("CGroup", unit_cgroup_runtime_build_json, u),
347 JSON_BUILD_PAIR_CALLBACK_NON_NULL(unit_type_to_capitalized_string(u->type), unit_type_callbacks[u->type], u));
348 }
349
350 static int list_unit_one(sd_varlink *link, Unit *unit) {
351 assert(link);
352 assert(unit);
353
354 return sd_varlink_replybo(link,
355 SD_JSON_BUILD_PAIR_CALLBACK("context", unit_context_build_json, unit),
356 SD_JSON_BUILD_PAIR_CALLBACK("runtime", unit_runtime_build_json, unit));
357 }
358
359 static int list_unit_one_with_selinux_access_check(sd_varlink *link, Unit *unit) {
360 int r;
361
362 assert(link);
363 assert(unit);
364
365 r = mac_selinux_unit_access_check_varlink(unit, link, "status");
366 if (r < 0)
367 /* If mac_selinux_unit_access_check_varlink() returned a error,
368 * it means that SELinux enforce is on. It also does all the logging(). */
369 return sd_varlink_error(link, SD_VARLINK_ERROR_PERMISSION_DENIED, NULL);
370
371 return list_unit_one(link, unit);
372 }
373
374 static int lookup_unit_by_pidref(sd_varlink *link, Manager *manager, PidRef *pidref, Unit **ret_unit) {
375 _cleanup_(pidref_done) PidRef peer = PIDREF_NULL;
376 Unit *unit;
377 int r;
378
379 assert(link);
380 assert(manager);
381 assert(ret_unit);
382
383 if (pidref_is_automatic(pidref)) {
384 r = varlink_get_peer_pidref(link, &peer);
385 if (r < 0)
386 return log_debug_errno(r, "Failed to get peer pidref: %m");
387
388 pidref = &peer;
389 } else if (!pidref_is_set(pidref))
390 return -EINVAL;
391
392 unit = manager_get_unit_by_pidref(manager, pidref);
393 if (!unit)
394 return -ESRCH;
395
396 *ret_unit = unit;
397 return 0;
398 }
399
400 static int load_unit_and_check(sd_varlink *link, Manager *manager, const char *name, Unit **ret_unit) {
401 Unit *unit;
402 int r;
403
404 assert(link);
405 assert(manager);
406 assert(name);
407 assert(ret_unit);
408
409 r = manager_load_unit(manager, name, /* path= */ NULL, /* e= */ NULL, &unit);
410 if (r < 0)
411 return r;
412
413 /* manager_load_unit() will create an object regardless of whether the unit actually exists, so
414 * check the state and refuse if it's not in a good state. */
415 if (IN_SET(unit->load_state, UNIT_NOT_FOUND, UNIT_STUB, UNIT_MERGED))
416 return sd_varlink_error(link, "io.systemd.Unit.NoSuchUnit", NULL);
417 if (unit->load_state == UNIT_BAD_SETTING)
418 return sd_varlink_error(link, "io.systemd.Unit.UnitError", NULL);
419 if (unit->load_state == UNIT_ERROR)
420 return sd_varlink_errorbo(
421 link,
422 SD_VARLINK_ERROR_SYSTEM,
423 SD_JSON_BUILD_PAIR_STRING("origin", "linux"),
424 SD_JSON_BUILD_PAIR_INTEGER("errno", unit->load_error),
425 JSON_BUILD_PAIR_STRING_NON_EMPTY("errnoName", "io.systemd.Unit.UnitError"));
426 if (unit->load_state == UNIT_MASKED)
427 return sd_varlink_error(link, "io.systemd.Unit.UnitMasked", NULL);
428 assert(UNIT_IS_LOAD_COMPLETE(unit->load_state));
429
430 *ret_unit = unit;
431 return 0;
432 }
433
434 typedef struct UnitLookupParameters {
435 const char *name, *cgroup;
436 PidRef pidref;
437 sd_id128_t invocation_id;
438 } UnitLookupParameters;
439
440 static void unit_lookup_parameters_done(UnitLookupParameters *p) {
441 assert(p);
442 pidref_done(&p->pidref);
443 }
444
445 static int varlink_error_conflict_lookup_parameters(sd_varlink *v, const UnitLookupParameters *p) {
446 log_debug("Unit lookup by parameters name='%s' pid='"PID_FMT"' cgroup='%s' invocationID='%s' resulted in multiple different units.",
447 strnull(p->name),
448 pidref_is_automatic(&p->pidref) ? 0 : pidref_is_set(&p->pidref) ? p->pidref.pid : (pid_t) -1,
449 strnull(p->cgroup),
450 sd_id128_is_null(p->invocation_id) ? "" : SD_ID128_TO_UUID_STRING(p->invocation_id));
451
452 return varlink_error_no_such_unit(v, /* name= */ NULL);
453 }
454
455 static int lookup_unit_by_parameters(
456 sd_varlink *link,
457 Manager *manager,
458 UnitLookupParameters *p,
459 Unit **ret) {
460
461 /* The function can return ret_unit=NULL if no lookup parameters provided */
462 Unit *unit = NULL;
463 int r;
464
465 assert(link);
466 assert(manager);
467 assert(p);
468 assert(ret);
469
470 if (p->name) {
471 r = load_unit_and_check(link, manager, p->name, &unit);
472 if (r < 0)
473 return r;
474 }
475
476 if (pidref_is_set_or_automatic(&p->pidref)) {
477 Unit *pid_unit;
478
479 r = lookup_unit_by_pidref(link, manager, &p->pidref, &pid_unit);
480 if (r == -EINVAL)
481 return sd_varlink_error_invalid_parameter_name(link, "pid");
482 if (r == -ESRCH)
483 return varlink_error_no_such_unit(link, "pid");
484 if (r < 0)
485 return r;
486 if (unit && pid_unit != unit)
487 return varlink_error_conflict_lookup_parameters(link, p);
488
489 unit = pid_unit;
490 }
491
492 if (p->cgroup) {
493 if (!path_is_absolute(p->cgroup) || !path_is_normalized(p->cgroup))
494 return sd_varlink_error_invalid_parameter_name(link, "cgroup");
495
496 Unit *cgroup_unit = manager_get_unit_by_cgroup(manager, p->cgroup);
497 if (!cgroup_unit)
498 return varlink_error_no_such_unit(link, "cgroup");
499 if (unit && cgroup_unit != unit)
500 return varlink_error_conflict_lookup_parameters(link, p);
501
502 unit = cgroup_unit;
503 }
504
505 if (!sd_id128_is_null(p->invocation_id)) {
506 Unit *id128_unit = hashmap_get(manager->units_by_invocation_id, &p->invocation_id);
507 if (!id128_unit)
508 return varlink_error_no_such_unit(link, "invocationID");
509 if (unit && id128_unit != unit)
510 return varlink_error_conflict_lookup_parameters(link, p);
511
512 unit = id128_unit;
513 }
514
515 *ret = unit;
516 return !!unit;
517 }
518
519 int vl_method_list_units(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
520 static const sd_json_dispatch_field dispatch_table[] = {
521 { "name", SD_JSON_VARIANT_STRING, json_dispatch_const_unit_name, offsetof(UnitLookupParameters, name), 0 /* allows UNIT_NAME_PLAIN | UNIT_NAME_INSTANCE */ },
522 { "pid", _SD_JSON_VARIANT_TYPE_INVALID, json_dispatch_pidref, offsetof(UnitLookupParameters, pidref), SD_JSON_RELAX /* allows PID_AUTOMATIC */ },
523 { "cgroup", SD_JSON_VARIANT_STRING, json_dispatch_const_path, offsetof(UnitLookupParameters, cgroup), SD_JSON_STRICT /* require normalized path */ },
524 { "invocationID", SD_JSON_VARIANT_STRING, sd_json_dispatch_id128, offsetof(UnitLookupParameters, invocation_id), 0 },
525 {}
526 };
527
528 Manager *manager = ASSERT_PTR(userdata);
529 _cleanup_(unit_lookup_parameters_done) UnitLookupParameters p = {
530 .pidref = PIDREF_NULL,
531 };
532 Unit *unit;
533 const char *k;
534 int r;
535
536 assert(link);
537 assert(parameters);
538
539 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
540 if (r != 0)
541 return r;
542
543 r = lookup_unit_by_parameters(link, manager, &p, &unit);
544 if (r < 0)
545 return r;
546 if (r > 0)
547 return list_unit_one_with_selinux_access_check(link, unit);
548
549 if (!FLAGS_SET(flags, SD_VARLINK_METHOD_MORE))
550 return sd_varlink_error(link, SD_VARLINK_ERROR_EXPECTED_MORE, NULL);
551
552 r = sd_varlink_set_sentinel(link, VARLINK_ERROR_UNIT_NO_SUCH_UNIT);
553 if (r < 0)
554 return r;
555
556 HASHMAP_FOREACH_KEY(unit, k, manager->units) {
557 /* ignore aliases */
558 if (k != unit->id)
559 continue;
560
561 r = mac_selinux_unit_access_check_varlink(unit, link, "status");
562 if (r < 0)
563 continue; /* silently skip units the caller is not allowed to see */
564
565 r = list_unit_one(link, unit);
566 if (r < 0)
567 return r;
568 }
569
570 return 0;
571 }
572
573 int varlink_unit_queue_job_one(
574 Unit *u,
575 JobType type,
576 JobMode mode,
577 bool reload_if_possible,
578 uint32_t *ret_job_id,
579 Job **ret_job,
580 sd_bus_error *reterr_bus_error) {
581
582 int r;
583
584 assert(u);
585
586 r = unit_queue_job_check_and_mangle_type(u, &type, reload_if_possible, reterr_bus_error);
587 if (r < 0)
588 return r;
589
590 Job *j;
591 r = manager_add_job(u->manager, type, u, mode, reterr_bus_error, &j);
592 if (r < 0)
593 return r;
594
595 /* Before we send the method reply, force out the announcement JobNew for this job */
596 bus_job_send_pending_change_signal(j, /* including_new= */ true);
597
598 if (ret_job_id)
599 *ret_job_id = j->id;
600 if (ret_job)
601 *ret_job = j;
602
603 return 0;
604 }
605
606 int varlink_error_no_such_unit(sd_varlink *v, const char *name) {
607 return sd_varlink_errorbo(
608 ASSERT_PTR(v),
609 VARLINK_ERROR_UNIT_NO_SUCH_UNIT,
610 JSON_BUILD_PAIR_STRING_NON_EMPTY("parameter", name));
611 }
612
613 void varlink_unit_send_change_signal(Unit *u) {
614 assert(u);
615
616 if (!u->varlink_unit_change)
617 return;
618
619 (void) sd_varlink_notifybo(
620 u->varlink_unit_change,
621 SD_JSON_BUILD_PAIR_CALLBACK("runtime", unit_runtime_build_json, u));
622 }
623
624 void varlink_job_send_change_signal(Job *j) {
625 assert(j);
626
627 if (!j->varlink || !j->varlink_notify_job_changes)
628 return;
629
630 (void) sd_varlink_notifybo(
631 j->varlink,
632 SD_JSON_BUILD_PAIR_CALLBACK("job", job_build_json, j));
633 }
634
635 void varlink_job_send_removed_signal(Job *j) {
636 assert(j);
637
638 if (!j->varlink)
639 return;
640
641 /* Send the final reply, which completes the method call */
642 (void) sd_varlink_replybo(
643 j->varlink,
644 SD_JSON_BUILD_PAIR_CALLBACK("context", unit_context_build_json, j->unit),
645 SD_JSON_BUILD_PAIR_CALLBACK("runtime", unit_runtime_build_json, j->unit),
646 SD_JSON_BUILD_PAIR_CALLBACK("job", job_build_json, j));
647
648 j->varlink = sd_varlink_unref(j->varlink);
649 j->unit->varlink_unit_change = sd_varlink_unref(j->unit->varlink_unit_change);
650 }
651
652 typedef struct TransientExecCommandItem {
653 const char *path;
654 char **arguments;
655 } TransientExecCommandItem;
656
657 static void transient_exec_command_item_done(TransientExecCommandItem *i) {
658 assert(i);
659 strv_free(i->arguments);
660 }
661
662 static JSON_DISPATCH_ENUM_DEFINE(dispatch_service_type, ServiceType, service_type_from_string);
663 static JSON_DISPATCH_ENUM_DEFINE(dispatch_job_mode, JobMode, job_mode_from_string);
664
665 typedef struct TransientWorkingDirectory {
666 const char *path;
667 bool home;
668 bool missing_ok;
669 } TransientWorkingDirectory;
670
671 typedef struct TransientSetCredential {
672 const char *id;
673 struct iovec value;
674 } TransientSetCredential;
675
676 typedef struct TransientExecContextParameters {
677 bool present;
678 bool working_directory_set;
679 TransientWorkingDirectory working_directory;
680 bool environment_set;
681 char **environment;
682
683 bool set_credentials_set;
684 TransientSetCredential *set_credentials;
685 size_t n_set_credentials;
686
687 bool set_credentials_encrypted_set;
688 TransientSetCredential *set_credentials_encrypted;
689 size_t n_set_credentials_encrypted;
690
691 const char *user;
692 const char *group;
693 char **supplementary_groups;
694 int nice; /* INT_MAX means unset */
695 } TransientExecContextParameters;
696
697 static void transient_set_credential_array_free(TransientSetCredential *items, size_t n) {
698 FOREACH_ARRAY(item, items, n)
699 iovec_done_erase(&item->value);
700 free(items);
701 }
702
703 static void transient_exec_context_parameters_done(TransientExecContextParameters *p) {
704 assert(p);
705 strv_free(p->environment);
706 strv_free(p->supplementary_groups);
707 transient_set_credential_array_free(p->set_credentials, p->n_set_credentials);
708 transient_set_credential_array_free(p->set_credentials_encrypted, p->n_set_credentials_encrypted);
709 }
710
711 typedef struct TransientServiceParameters {
712 bool present;
713 ServiceType type;
714 TransientExecCommandItem *exec_start;
715 size_t n_exec_start;
716 int remain_after_exit;
717 } TransientServiceParameters;
718
719 static void transient_service_parameters_done(TransientServiceParameters *p) {
720 assert(p);
721 FOREACH_ARRAY(i, p->exec_start, p->n_exec_start)
722 transient_exec_command_item_done(i);
723 free(p->exec_start);
724 }
725
726 static int dispatch_transient_exec_command(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
727 static const sd_json_dispatch_field exec_command_dispatch[] = {
728 { "path", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(TransientExecCommandItem, path), SD_JSON_MANDATORY },
729 { "arguments", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_strv, offsetof(TransientExecCommandItem, arguments), 0 },
730 {}
731 };
732
733 TransientServiceParameters *p = ASSERT_PTR(userdata);
734 size_t n;
735 int r;
736
737 if (!sd_json_variant_is_array(variant))
738 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "Expected JSON array for ExecStart.");
739
740 n = sd_json_variant_elements(variant);
741 if (n == 0)
742 return 0;
743
744 p->exec_start = new0(TransientExecCommandItem, n);
745 if (!p->exec_start)
746 return -ENOMEM;
747 p->n_exec_start = n;
748
749 for (size_t i = 0; i < n; i++) {
750 sd_json_variant *element = sd_json_variant_by_index(variant, i);
751
752 r = sd_json_dispatch(element, exec_command_dispatch, /* flags= */ 0, &p->exec_start[i]);
753 if (r < 0)
754 return r;
755 }
756 return 0;
757 }
758
759 typedef struct StartTransientContextParameters {
760 const char *id;
761 const char *description;
762 TransientExecContextParameters exec;
763 TransientServiceParameters service;
764 const char *bad_exec_field; /* Set by inner Exec dispatcher to the unknown sub-property name */
765 const char *bad_service_field;
766 } StartTransientContextParameters;
767
768 static void start_transient_context_parameters_done(StartTransientContextParameters *p) {
769 assert(p);
770 transient_exec_context_parameters_done(&p->exec);
771 transient_service_parameters_done(&p->service);
772 }
773
774 typedef struct StartTransientParameters {
775 StartTransientContextParameters context;
776 JobMode mode;
777 int notify_job_changes;
778 int notify_unit_changes;
779 char *unsupported_property; /* For error reporting on unknown context fields */
780 } StartTransientParameters;
781
782 static void start_transient_parameters_done(StartTransientParameters *p) {
783 assert(p);
784 start_transient_context_parameters_done(&p->context);
785 free(p->unsupported_property);
786 }
787
788 static int dispatch_const_string_empty_as_null(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
789 const char **s = ASSERT_PTR(userdata);
790 int r;
791
792 r = sd_json_dispatch_const_string(name, variant, flags, s);
793 if (r >= 0 && isempty(*s))
794 *s = NULL;
795 return r;
796 }
797
798 static int dispatch_transient_working_directory(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
799 /* No equivalent D-Bus properties, so use varlink camelCase */
800 static const sd_json_dispatch_field dispatch[] = {
801 { "path", SD_JSON_VARIANT_STRING, dispatch_const_string_empty_as_null, offsetof(TransientWorkingDirectory, path), 0 },
802 { "home", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(TransientWorkingDirectory, home), 0 },
803 { "missingOK", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(TransientWorkingDirectory, missing_ok), 0 },
804 {}
805 };
806
807 TransientExecContextParameters *p = ASSERT_PTR(userdata);
808 p->working_directory_set = true;
809 return sd_json_dispatch(variant, dispatch, flags, &p->working_directory);
810 }
811
812 static int dispatch_transient_environment(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
813 TransientExecContextParameters *p = ASSERT_PTR(userdata);
814 p->environment_set = true;
815 return sd_json_dispatch_strv(name, variant, flags, &p->environment);
816 }
817
818 static int dispatch_transient_set_credential_array(
819 sd_json_variant *variant,
820 TransientSetCredential **ret_items,
821 size_t *ret_n) {
822
823 static const sd_json_dispatch_field item_dispatch[] = {
824 { "id", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(TransientSetCredential, id), SD_JSON_MANDATORY },
825 { "value", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(TransientSetCredential, value), SD_JSON_MANDATORY },
826 {}
827 };
828
829 TransientSetCredential *items = NULL;
830 size_t n = 0;
831 int r;
832
833 assert(ret_items);
834 assert(ret_n);
835
836 CLEANUP_ARRAY(items, n, transient_set_credential_array_free);
837
838 size_t n_items = sd_json_variant_elements(variant);
839 if (n_items == 0) {
840 *ret_items = NULL;
841 *ret_n = 0;
842 return 0;
843 }
844
845 items = new0(TransientSetCredential, n_items);
846 if (!items)
847 return -ENOMEM;
848
849 for (; n < n_items; n++) {
850 r = sd_json_dispatch(sd_json_variant_by_index(variant, n), item_dispatch, /* flags= */ 0, &items[n]);
851 if (r < 0)
852 return r;
853 }
854
855 *ret_n = n;
856 *ret_items = TAKE_PTR(items);
857 return 0;
858 }
859
860 static int dispatch_transient_set_credential(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
861 TransientExecContextParameters *p = ASSERT_PTR(userdata);
862 p->set_credentials_set = true;
863 return dispatch_transient_set_credential_array(variant, &p->set_credentials, &p->n_set_credentials);
864 }
865
866 static int dispatch_transient_set_credential_encrypted(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
867 TransientExecContextParameters *p = ASSERT_PTR(userdata);
868 p->set_credentials_encrypted_set = true;
869 return dispatch_transient_set_credential_array(variant, &p->set_credentials_encrypted, &p->n_set_credentials_encrypted);
870 }
871
872 static int dispatch_transient_exec_context(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
873 /* Key names compatible with D-Bus property names. */
874 static const sd_json_dispatch_field exec_dispatch[] = {
875 { "Environment", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_transient_environment, 0, 0 },
876 { "Group", SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(TransientExecContextParameters, group), SD_JSON_RELAX },
877 { "Nice", SD_JSON_VARIANT_INTEGER, sd_json_dispatch_int32, offsetof(TransientExecContextParameters, nice), 0 },
878 { "SetCredential", SD_JSON_VARIANT_ARRAY, dispatch_transient_set_credential, 0, 0 },
879 { "SetCredentialEncrypted", SD_JSON_VARIANT_ARRAY, dispatch_transient_set_credential_encrypted, 0, 0 },
880 { "SupplementaryGroups", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_strv, offsetof(TransientExecContextParameters, supplementary_groups), 0 },
881 { "User", SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(TransientExecContextParameters, user), SD_JSON_RELAX },
882 { "WorkingDirectory", SD_JSON_VARIANT_OBJECT, dispatch_transient_working_directory, 0, 0 },
883 {}
884 };
885
886 StartTransientContextParameters *p = ASSERT_PTR(userdata);
887 p->exec.present = true;
888 return sd_json_dispatch_full(variant, exec_dispatch, /* bad= */ NULL, /* flags= */ 0, &p->exec, &p->bad_exec_field);
889 }
890
891 static int dispatch_transient_service(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
892 static const sd_json_dispatch_field service_dispatch[] = {
893 { "Type", SD_JSON_VARIANT_STRING, dispatch_service_type, offsetof(TransientServiceParameters, type), 0 },
894 { "ExecStart", SD_JSON_VARIANT_ARRAY, dispatch_transient_exec_command, 0, 0 },
895 { "RemainAfterExit", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate, offsetof(TransientServiceParameters, remain_after_exit), 0 },
896 {}
897 };
898
899 StartTransientContextParameters *p = ASSERT_PTR(userdata);
900 p->service.present = true;
901 return sd_json_dispatch_full(variant, service_dispatch, /* bad= */ NULL, /* flags= */ 0, &p->service, &p->bad_service_field);
902 }
903
904 static int dispatch_transient_context(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
905 static const sd_json_dispatch_field context_dispatch[] = {
906 { "ID", SD_JSON_VARIANT_STRING, json_dispatch_const_unit_name, offsetof(StartTransientContextParameters, id), SD_JSON_MANDATORY },
907 { "Description", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(StartTransientContextParameters, description), 0 },
908 { "Exec", SD_JSON_VARIANT_OBJECT, dispatch_transient_exec_context, 0, 0 },
909 { "Service", SD_JSON_VARIANT_OBJECT, dispatch_transient_service, 0, 0 },
910 {}
911 };
912
913 StartTransientParameters *p = ASSERT_PTR(userdata);
914 const char *bad_field = NULL;
915 int r;
916
917 /* Don't propagate the caller's flags (in particular SD_JSON_MANDATORY from the outer 'context'
918 * field) into the nested dispatch, otherwise every inner field becomes mandatory. */
919 r = sd_json_dispatch_full(variant, context_dispatch, /* bad= */ NULL, /* flags= */ 0, &p->context, &bad_field);
920 if (r == -EADDRNOTAVAIL && !isempty(bad_field)) {
921 /* A UnitContext field that exists in the schema but is not settable at creation time: stash
922 * the name so the caller can map this to io.systemd.Unit.PropertyNotSupported. If the
923 * unknown field lives inside the nested Exec object, compose a dotted name to identify the
924 * actual sub-property. */
925 if (streq(bad_field, "Exec") && !isempty(p->context.bad_exec_field))
926 p->unsupported_property = strjoin("Exec.", p->context.bad_exec_field);
927 else if (streq(bad_field, "Service") && !isempty(p->context.bad_service_field))
928 p->unsupported_property = strjoin("Service.", p->context.bad_service_field);
929 else
930 p->unsupported_property = strdup(bad_field);
931 if (!p->unsupported_property)
932 return -ENOMEM;
933 }
934 return r;
935 }
936
937 static int transient_unit_apply_properties(Unit *u, StartTransientContextParameters *p) {
938 int r;
939
940 assert(u);
941 assert(p);
942
943 if (p->description) {
944 r = unit_set_description(u, p->description);
945 if (r < 0)
946 return r;
947 unit_write_settingf(u, UNIT_RUNTIME|UNIT_ESCAPE_SPECIFIERS, "Description", "Description=%s", p->description);
948 }
949
950 return 0;
951 }
952
953 static int transient_apply_set_credentials(
954 Unit *u,
955 ExecContext *c,
956 const TransientSetCredential *items,
957 size_t n_items,
958 bool encrypted) {
959
960 int r;
961
962 assert(u);
963 assert(c);
964
965 FOREACH_ARRAY(item, items, n_items) {
966 const char *err = NULL;
967
968 r = exec_context_apply_set_credential(u, c, item->id, item->value.iov_base, item->value.iov_len,
969 encrypted, UNIT_RUNTIME|UNIT_PRIVATE, &err);
970 if (r == -EINVAL)
971 return log_debug_errno(r, "%s: %s", err, item->id);
972 if (r < 0)
973 return r;
974 }
975
976 return 0;
977 }
978
979 static int transient_exec_context_apply_properties(
980 Unit *u,
981 ExecContext *c,
982 TransientExecContextParameters *p,
983 const char **reterr_field) {
984
985 int r;
986
987 assert(u);
988 assert(c);
989 assert(p);
990
991 if (p->working_directory_set) {
992 TransientWorkingDirectory *wd = &p->working_directory;
993 _cleanup_free_ char *simplified = NULL;
994
995 if (wd->home && wd->path) {
996 if (reterr_field)
997 *reterr_field = "Exec.WorkingDirectory";
998 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
999 "WorkingDirectory: 'home' and 'path' are mutually exclusive");
1000 }
1001 if (!wd->home && !wd->path) {
1002 if (reterr_field)
1003 *reterr_field = "Exec.WorkingDirectory";
1004 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1005 "WorkingDirectory: must specify either 'home' or 'path'");
1006 }
1007
1008 if (!wd->home) {
1009 if (!path_is_absolute(wd->path)) {
1010 if (reterr_field)
1011 *reterr_field = "Exec.WorkingDirectory";
1012 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1013 "WorkingDirectory: expects an absolute path");
1014 }
1015 r = path_simplify_alloc(wd->path, &simplified);
1016 if (r < 0)
1017 return r;
1018 if (!path_is_normalized(simplified)) {
1019 if (reterr_field)
1020 *reterr_field = "Exec.WorkingDirectory";
1021 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1022 "WorkingDirectory: expects a normalized path");
1023 }
1024 }
1025
1026 free_and_replace(c->working_directory, simplified);
1027 c->working_directory_home = wd->home;
1028 c->working_directory_missing_ok = wd->missing_ok;
1029
1030 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, "WorkingDirectory",
1031 "WorkingDirectory=%s%s",
1032 c->working_directory_missing_ok ? "-" : "",
1033 c->working_directory_home ? "~" : strempty(c->working_directory));
1034 }
1035
1036 if (p->environment_set) {
1037 r = exec_context_apply_environment(u, c, p->environment, UNIT_RUNTIME|UNIT_PRIVATE);
1038 if (IN_SET(r, -E2BIG, -EINVAL)) {
1039 if (reterr_field)
1040 *reterr_field = "Exec.Environment";
1041 /* Convert E2BIG into EINVAL to ensure upper layers get the right error context */
1042 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1043 r == -E2BIG ? "Too many environment assignments." : "Invalid Environment list.");
1044 }
1045 if (r < 0)
1046 return r;
1047 }
1048
1049 if (p->set_credentials_set) {
1050 r = transient_apply_set_credentials(u, c, p->set_credentials, p->n_set_credentials, /* encrypted= */ false);
1051 if (r == -EINVAL && reterr_field)
1052 *reterr_field = "Exec.SetCredential";
1053 if (r < 0)
1054 return r;
1055 }
1056
1057 if (p->set_credentials_encrypted_set) {
1058 r = transient_apply_set_credentials(u, c, p->set_credentials_encrypted, p->n_set_credentials_encrypted, /* encrypted= */ true);
1059 if (r == -EINVAL && reterr_field)
1060 *reterr_field = "Exec.SetCredentialEncrypted";
1061 if (r < 0)
1062 return r;
1063 }
1064
1065 /* User/Group names already validated by json_dispatch_const_user_group_name() in the dispatch table:
1066 * either NULL or a non-empty validated name. */
1067 if (p->user) {
1068 r = free_and_strdup(&c->user, p->user);
1069 if (r < 0)
1070 return r;
1071
1072 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, "User",
1073 "User=%s", p->user);
1074 }
1075
1076 if (p->group) {
1077 r = free_and_strdup(&c->group, p->group);
1078 if (r < 0)
1079 return r;
1080
1081 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, "Group",
1082 "Group=%s", p->group);
1083 }
1084
1085 if (p->supplementary_groups) {
1086 _cleanup_free_ char *joined = NULL;
1087
1088 STRV_FOREACH(g, p->supplementary_groups)
1089 if (!valid_user_group_name(*g, VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)) {
1090 if (reterr_field)
1091 *reterr_field = "Exec.SupplementaryGroups";
1092 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1093 "Invalid supplementary group name: %s", *g);
1094 }
1095
1096 r = strv_extend_strv(&c->supplementary_groups, p->supplementary_groups, /* filter_duplicates= */ true);
1097 if (r < 0)
1098 return r;
1099
1100 joined = strv_join(p->supplementary_groups, " ");
1101 if (!joined)
1102 return -ENOMEM;
1103
1104 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE|UNIT_ESCAPE_SPECIFIERS, "SupplementaryGroups",
1105 "SupplementaryGroups=%s", joined);
1106 }
1107
1108 if (p->nice != INT_MAX) {
1109 if (!nice_is_valid(p->nice)) {
1110 if (reterr_field)
1111 *reterr_field = "Exec.Nice";
1112 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid Nice= value: %i", p->nice);
1113 }
1114
1115 c->nice = p->nice;
1116 c->nice_set = true;
1117
1118 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "Nice", "Nice=%i", p->nice);
1119 }
1120
1121 return 0;
1122 }
1123
1124 static int transient_service_apply_properties(Service *s, TransientServiceParameters *sp, const char **reterr_field) {
1125 Unit *u = UNIT(ASSERT_PTR(s));
1126 int r;
1127
1128 assert(sp);
1129
1130 if (sp->type >= 0) {
1131 s->type = sp->type;
1132 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "Type", "Type=%s", service_type_to_string(sp->type));
1133 }
1134
1135 if (sp->remain_after_exit >= 0) {
1136 s->remain_after_exit = sp->remain_after_exit;
1137 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "RemainAfterExit", "RemainAfterExit=%s", yes_no(sp->remain_after_exit));
1138 }
1139
1140 FOREACH_ARRAY(item, sp->exec_start, sp->n_exec_start) {
1141 _cleanup_(exec_command_freep) ExecCommand *c = NULL;
1142 _cleanup_strv_free_ char **argv = NULL;
1143
1144 if (!filename_or_absolute_path_is_valid(item->path)) {
1145 if (reterr_field)
1146 *reterr_field = "Service.ExecStart";
1147 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid ExecStart path: %s", item->path);
1148 }
1149
1150 if (!strv_isempty(item->arguments)) {
1151 argv = strv_copy(item->arguments);
1152 if (!argv)
1153 return -ENOMEM;
1154 }
1155
1156 c = new0(ExecCommand, 1);
1157 if (!c)
1158 return -ENOMEM;
1159
1160 r = path_simplify_alloc(item->path, &c->path);
1161 if (r < 0)
1162 return r;
1163
1164 /* If no arguments were provided, default argv[0] to the executable path.
1165 * Otherwise the caller is expected to include argv[0] in the arguments array. */
1166 if (strv_isempty(argv)) {
1167 r = strv_extend(&argv, c->path);
1168 if (r < 0)
1169 return r;
1170 }
1171
1172 c->argv = TAKE_PTR(argv);
1173
1174 exec_command_append_list(&s->exec_command[SERVICE_EXEC_START], TAKE_PTR(c));
1175 }
1176
1177 /* Write ExecStart= lines to the transient file */
1178 if (sp->n_exec_start > 0) {
1179 UnitWriteFlags esc_flags = UNIT_ESCAPE_SPECIFIERS|UNIT_ESCAPE_EXEC_SYNTAX_ENV;
1180
1181 LIST_FOREACH(command, c, s->exec_command[SERVICE_EXEC_START]) {
1182 _cleanup_free_ char *a = NULL;
1183
1184 a = unit_concat_strv(c->argv, esc_flags);
1185 if (!a)
1186 return -ENOMEM;
1187
1188 /* streq() instead path_equal() as argv[0] can be arbitrary and may not be a path */
1189 if (streq(c->path, c->argv[0]))
1190 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "ExecStart", "ExecStart=%s", a);
1191 else {
1192 _cleanup_free_ char *t = NULL;
1193 const char *p;
1194
1195 p = unit_escape_setting(c->path, esc_flags, &t);
1196 if (!p)
1197 return -ENOMEM;
1198
1199 unit_write_settingf(u, UNIT_RUNTIME|UNIT_PRIVATE, "ExecStart", "ExecStart=@%s %s", p, a);
1200 }
1201 }
1202 }
1203
1204 return 0;
1205 }
1206
1207 int vl_method_start_transient_unit(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
1208 static const sd_json_dispatch_field dispatch_table[] = {
1209 { "context", SD_JSON_VARIANT_OBJECT, dispatch_transient_context, 0, SD_JSON_MANDATORY },
1210 { "mode", SD_JSON_VARIANT_STRING, dispatch_job_mode, offsetof(StartTransientParameters, mode), 0 },
1211 { "notifyJobChanges", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate, offsetof(StartTransientParameters, notify_job_changes), 0 },
1212 { "notifyUnitChanges", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_tristate, offsetof(StartTransientParameters, notify_unit_changes), 0 },
1213 {}
1214 };
1215
1216 _cleanup_(sd_bus_error_free) sd_bus_error bus_error = SD_BUS_ERROR_NULL;
1217 _cleanup_(start_transient_parameters_done) StartTransientParameters p = {
1218 .mode = JOB_REPLACE,
1219 .notify_job_changes = -1,
1220 .notify_unit_changes = -1,
1221 .context.service.type = _SERVICE_TYPE_INVALID,
1222 .context.service.remain_after_exit = -1,
1223 .context.exec.nice = INT_MAX,
1224 };
1225 Manager *manager = ASSERT_PTR(userdata);
1226 const char *bad_field = NULL;
1227 Unit *u;
1228 int r;
1229
1230 assert(link);
1231 assert(parameters);
1232
1233 r = mac_selinux_access_check_varlink(link, "start");
1234 if (r < 0)
1235 return r;
1236
1237 r = sd_json_dispatch_full(parameters, dispatch_table, /* bad= */ NULL, /* flags= */ 0, &p, &bad_field);
1238 if (r < 0) {
1239 /* An unknown field in 'context' maps to PropertyNotSupported (the field is defined in the
1240 * UnitContext schema but cannot be set at creation time). Anything else is a bad parameter. */
1241 if (streq_ptr(bad_field, "context") && r == -EADDRNOTAVAIL && p.unsupported_property)
1242 return sd_varlink_errorbo(
1243 link,
1244 "io.systemd.Unit.PropertyNotSupported",
1245 SD_JSON_BUILD_PAIR_STRING("property", p.unsupported_property));
1246 if (bad_field)
1247 return sd_varlink_error_invalid_parameter_name(link, bad_field);
1248 return r;
1249 }
1250
1251 /* Pre-check unit type early and return targeted varlink error as manager_setup_transient_unit() the
1252 * too generic SD_BUS_ERROR_INVALID_ARGS. */
1253 UnitType t = unit_name_to_type(p.context.id);
1254 if (t < 0)
1255 return sd_varlink_error_invalid_parameter_name(link, "context");
1256 if (!unit_vtable[t]->can_transient)
1257 return sd_varlink_error(link, VARLINK_ERROR_UNIT_TYPE_NOT_SUPPORTED, NULL);
1258
1259 r = varlink_verify_polkit_async(
1260 link,
1261 manager->system_bus,
1262 "org.freedesktop.systemd1.manage-units",
1263 (const char**) STRV_MAKE(
1264 "unit", p.context.id,
1265 "verb", "start",
1266 "polkit.message", N_("Authentication is required to start transient unit '$(unit)'."),
1267 "polkit.gettext_domain", GETTEXT_PACKAGE),
1268 &manager->polkit_registry);
1269 if (r <= 0)
1270 return r;
1271
1272 r = manager_setup_transient_unit(manager, p.context.id, &u, &bus_error);
1273 if (r < 0)
1274 return varlink_reply_bus_error(link, r, &bus_error);
1275
1276 /* Apply unit-level properties from context */
1277 r = transient_unit_apply_properties(u, &p.context);
1278 if (r == -EINVAL)
1279 return sd_varlink_error_invalid_parameter_name(link, "context");
1280 if (r < 0)
1281 return sd_varlink_error_errno(link, r);
1282
1283 /* Apply exec-specific properties from context.Exec */
1284 ExecContext *c = unit_get_exec_context(u);
1285 if (c) {
1286 bad_field = NULL;
1287 r = transient_exec_context_apply_properties(u, c, &p.context.exec, &bad_field);
1288 if (r == -EINVAL)
1289 return sd_varlink_error_invalid_parameter_name(link, bad_field ?: "Exec");
1290 if (r < 0)
1291 return sd_varlink_error_errno(link, r);
1292 } else if (p.context.exec.present)
1293 return sd_varlink_error(link, VARLINK_ERROR_UNIT_TYPE_NOT_SUPPORTED, NULL);
1294
1295 /* Apply service-specific properties from context.Service */
1296 Service *s = SERVICE(u);
1297 if (s) {
1298 bad_field = NULL;
1299 r = transient_service_apply_properties(s, &p.context.service, &bad_field);
1300 if (r == -EINVAL)
1301 return sd_varlink_error_invalid_parameter_name(link, bad_field ?: "Service");
1302 if (r < 0)
1303 return sd_varlink_error_errno(link, r);
1304 } else if (p.context.service.present)
1305 return sd_varlink_error(link, VARLINK_ERROR_UNIT_TYPE_NOT_SUPPORTED, NULL);
1306
1307 unit_add_to_load_queue(u);
1308 manager_dispatch_load_queue(manager);
1309
1310 if (u->load_state == UNIT_BAD_SETTING)
1311 return sd_varlink_error_invalid_parameter_name(link, "context");
1312 if (!UNIT_IS_LOAD_COMPLETE(u->load_state))
1313 return sd_varlink_error(link, VARLINK_ERROR_UNIT_NO_SUCH_UNIT, NULL);
1314
1315 Job *j;
1316 r = varlink_unit_queue_job_one(
1317 u,
1318 JOB_START,
1319 p.mode,
1320 /* reload_if_possible= */ false,
1321 /* ret_job_id= */ NULL,
1322 &j,
1323 &bus_error);
1324 if (r < 0)
1325 return varlink_reply_bus_error(link, r, &bus_error);
1326
1327 bool notify_job = p.notify_job_changes > 0;
1328 bool notify_unit = p.notify_unit_changes > 0;
1329
1330 /* Non-streaming, or fire-and-forget (no notification flags set): return full unit context
1331 * and runtime, plus the job object so the caller can correlate with later state. */
1332 if (!FLAGS_SET(flags, SD_VARLINK_METHOD_MORE) || (!notify_job && !notify_unit))
1333 return sd_varlink_replybo(
1334 link,
1335 SD_JSON_BUILD_PAIR_CALLBACK("context", unit_context_build_json, u),
1336 SD_JSON_BUILD_PAIR_CALLBACK("runtime", unit_runtime_build_json, u),
1337 SD_JSON_BUILD_PAIR_CALLBACK("job", job_build_json, j));
1338
1339 /* Streaming: always attach to the job for the final reply, and optionally to the unit for state
1340 * change notifications. j->varlink owns the stream lifetime, u->varlink_unit_change is just a flag
1341 * to also send unit state notifications along the way. */
1342 assert(!j->varlink);
1343 j->varlink = sd_varlink_ref(link);
1344 j->varlink_notify_job_changes = notify_job;
1345 if (notify_unit) {
1346 assert(!u->varlink_unit_change);
1347 u->varlink_unit_change = sd_varlink_ref(link);
1348 }
1349
1350 /* Send initial job state notification if requested. Unit state change notifications are not sent
1351 * here; they will arrive via varlink_unit_send_change_signal() when the unit actually transitions,
1352 * matching D-Bus PropertiesChanged behavior. */
1353 if (notify_job)
1354 return sd_varlink_notifybo(
1355 link,
1356 SD_JSON_BUILD_PAIR_CALLBACK("job", job_build_json, j));
1357
1358 return 0;
1359 }
1360
1361 typedef struct UnitSetPropertiesParameters {
1362 const char *unsupported_property; /* For error reporting */
1363 const char *name;
1364 bool runtime;
1365
1366 bool markers_found;
1367 unsigned markers, markers_mask;
1368 } UnitSetPropertiesParameters;
1369
1370 static int parse_unit_markers(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
1371 UnitSetPropertiesParameters *p = ASSERT_PTR(userdata);
1372 bool some_plus_minus = false, some_absolute = false;
1373 unsigned settings = 0, mask = 0;
1374 sd_json_variant *e;
1375 int r;
1376
1377 assert(variant);
1378
1379 JSON_VARIANT_ARRAY_FOREACH(e, variant) {
1380 if (!sd_json_variant_is_string(e))
1381 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "Marker is not an array of strings.");
1382
1383 const char *word = sd_json_variant_string(e);
1384
1385 r = parse_unit_marker(word, &settings, &mask);
1386 if (r < 0)
1387 return json_log(variant, flags, r, "Failed to parse marker '%s'.", word);
1388 if (r > 0)
1389 some_plus_minus = true;
1390 else
1391 some_absolute = true;
1392 }
1393
1394 if (some_plus_minus && some_absolute)
1395 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "Absolute and non-absolute markers in the same setting.");
1396
1397 if (some_absolute || sd_json_variant_elements(variant) == 0)
1398 mask = UINT_MAX;
1399
1400 p->markers = settings;
1401 p->markers_mask = mask;
1402 p->markers_found = true;
1403
1404 return 0;
1405 }
1406
1407 static int unit_dispatch_properties(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
1408 static const sd_json_dispatch_field dispatch_table[] = {
1409 { "Markers", SD_JSON_VARIANT_ARRAY, parse_unit_markers, 0, 0 },
1410 {}
1411 };
1412 UnitSetPropertiesParameters *p = ASSERT_PTR(userdata);
1413 const char *bad_field = NULL;
1414 int r;
1415
1416 r = sd_json_dispatch_full(variant, dispatch_table, /* bad= */ NULL, flags, userdata, &bad_field);
1417 if (r == -EADDRNOTAVAIL && !isempty(bad_field))
1418 /* When properties contains a valid field, but that we don't currently support, make sure to
1419 * return the offending property, rather than generic invalid argument. */
1420 p->unsupported_property = bad_field;
1421 return r;
1422 }
1423
1424 int vl_method_set_unit_properties(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
1425 static const sd_json_dispatch_field dispatch_table[] = {
1426 { "name", SD_JSON_VARIANT_STRING, json_dispatch_const_unit_name, offsetof(UnitSetPropertiesParameters, name), SD_JSON_MANDATORY },
1427 { "runtime", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(UnitSetPropertiesParameters, runtime), SD_JSON_MANDATORY },
1428 { "properties", SD_JSON_VARIANT_OBJECT, unit_dispatch_properties, 0, SD_JSON_MANDATORY },
1429 {}
1430 };
1431
1432 UnitSetPropertiesParameters p = {};
1433 Manager *manager = ASSERT_PTR(userdata);
1434 const char *bad_field = NULL;
1435 Unit *unit;
1436 int r;
1437
1438 assert(link);
1439 assert(parameters);
1440
1441 r = sd_json_dispatch_full(parameters, dispatch_table, /* bad= */ NULL, /* flags= */ 0, &p, &bad_field);
1442 if (r < 0) {
1443 /* When properties contains a valid field, but that we don't currently support, make sure to
1444 * return a specific error, rather than generic invalid argument. */
1445 if (streq_ptr(bad_field, "properties") && r == -EADDRNOTAVAIL)
1446 return sd_varlink_errorbo(
1447 link,
1448 "io.systemd.Unit.PropertyNotSupported",
1449 SD_JSON_BUILD_PAIR_CONDITION(!!p.unsupported_property, "property", SD_JSON_BUILD_STRING(p.unsupported_property)));
1450 if (bad_field)
1451 return sd_varlink_error_invalid_parameter_name(link, bad_field);
1452 return r;
1453 }
1454
1455 r = load_unit_and_check(link, manager, p.name, &unit);
1456 if (r < 0)
1457 return r;
1458
1459 r = mac_selinux_unit_access_check_varlink(unit, link, "start");
1460 if (r < 0)
1461 return sd_varlink_error(link, SD_VARLINK_ERROR_PERMISSION_DENIED, NULL);
1462
1463 r = varlink_verify_polkit_async(
1464 link,
1465 manager->system_bus,
1466 "org.freedesktop.systemd1.manage-units",
1467 /* details= */ NULL,
1468 &manager->polkit_registry);
1469 if (r <= 0)
1470 return r;
1471
1472 if (p.markers_found)
1473 unit->markers = unit_normalize_markers((unit->markers & ~p.markers_mask), p.markers);
1474
1475 return sd_varlink_reply(link, NULL);
1476 }