1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include "core-varlink.h"
4 #include "mkdir-label.h"
9 typedef struct LookupParameters
{
10 const char *user_name
;
11 const char *group_name
;
19 static const char* const managed_oom_mode_properties
[] = {
21 "ManagedOOMMemoryPressure",
24 static int build_user_json(const char *user_name
, uid_t uid
, JsonVariant
**ret
) {
26 assert(uid_is_valid(uid
));
29 return json_build(ret
, JSON_BUILD_OBJECT(
30 JSON_BUILD_PAIR("record", JSON_BUILD_OBJECT(
31 JSON_BUILD_PAIR("userName", JSON_BUILD_STRING(user_name
)),
32 JSON_BUILD_PAIR("uid", JSON_BUILD_UNSIGNED(uid
)),
33 JSON_BUILD_PAIR("gid", JSON_BUILD_UNSIGNED(uid
)),
34 JSON_BUILD_PAIR("realName", JSON_BUILD_CONST_STRING("Dynamic User")),
35 JSON_BUILD_PAIR("homeDirectory", JSON_BUILD_CONST_STRING("/")),
36 JSON_BUILD_PAIR("shell", JSON_BUILD_CONST_STRING(NOLOGIN
)),
37 JSON_BUILD_PAIR("locked", JSON_BUILD_BOOLEAN(true)),
38 JSON_BUILD_PAIR("service", JSON_BUILD_CONST_STRING("io.systemd.DynamicUser")),
39 JSON_BUILD_PAIR("disposition", JSON_BUILD_CONST_STRING("dynamic"))))));
42 static bool user_match_lookup_parameters(LookupParameters
*p
, const char *name
, uid_t uid
) {
45 if (p
->user_name
&& !streq(name
, p
->user_name
))
48 if (uid_is_valid(p
->uid
) && uid
!= p
->uid
)
54 static int build_managed_oom_json_array_element(Unit
*u
, const char *property
, JsonVariant
**ret_v
) {
55 bool use_limit
= false;
63 if (!UNIT_VTABLE(u
)->can_set_managed_oom
)
66 c
= unit_get_cgroup_context(u
);
70 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u
)))
71 /* systemd-oomd should always treat inactive units as though they didn't enable any action since they
72 * should not have a valid cgroup */
73 mode
= managed_oom_mode_to_string(MANAGED_OOM_AUTO
);
74 else if (streq(property
, "ManagedOOMSwap"))
75 mode
= managed_oom_mode_to_string(c
->moom_swap
);
76 else if (streq(property
, "ManagedOOMMemoryPressure")) {
77 mode
= managed_oom_mode_to_string(c
->moom_mem_pressure
);
82 return json_build(ret_v
, JSON_BUILD_OBJECT(
83 JSON_BUILD_PAIR("mode", JSON_BUILD_STRING(mode
)),
84 JSON_BUILD_PAIR("path", JSON_BUILD_STRING(u
->cgroup_path
)),
85 JSON_BUILD_PAIR("property", JSON_BUILD_STRING(property
)),
86 JSON_BUILD_PAIR_CONDITION(use_limit
, "limit", JSON_BUILD_UNSIGNED(c
->moom_mem_pressure_limit
))));
89 int manager_varlink_send_managed_oom_update(Unit
*u
) {
90 _cleanup_(json_variant_unrefp
) JsonVariant
*arr
= NULL
, *v
= NULL
;
96 if (!UNIT_VTABLE(u
)->can_set_managed_oom
|| !u
->manager
|| !u
->cgroup_path
)
99 if (MANAGER_IS_SYSTEM(u
->manager
)) {
100 /* In system mode we can't send any notifications unless oomd connected back to us. In this
101 * mode oomd must initiate communication, not us. */
102 if (!u
->manager
->managed_oom_varlink
)
105 /* If we are in user mode, let's connect to oomd if we aren't connected yet. In this mode we
106 * must initiate communication to oomd, not the other way round. */
107 r
= manager_varlink_init(u
->manager
);
112 c
= unit_get_cgroup_context(u
);
116 r
= json_build(&arr
, JSON_BUILD_EMPTY_ARRAY
);
120 for (size_t i
= 0; i
< ELEMENTSOF(managed_oom_mode_properties
); i
++) {
121 _cleanup_(json_variant_unrefp
) JsonVariant
*e
= NULL
;
123 r
= build_managed_oom_json_array_element(u
, managed_oom_mode_properties
[i
], &e
);
127 r
= json_variant_append_array(&arr
, e
);
132 r
= json_build(&v
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("cgroups", JSON_BUILD_VARIANT(arr
))));
136 if (MANAGER_IS_SYSTEM(u
->manager
))
137 /* in system mode, oomd is our client, thus send out notifications as replies to the
138 * initiating method call from them. */
139 r
= varlink_notify(u
->manager
->managed_oom_varlink
, v
);
141 /* in user mode, we are oomd's client, thus send out notifications as method calls that do
142 * not expect a reply. */
143 r
= varlink_send(u
->manager
->managed_oom_varlink
, "io.systemd.oom.ReportManagedOOMCGroups", v
);
148 static int build_managed_oom_cgroups_json(Manager
*m
, JsonVariant
**ret
) {
149 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
, *arr
= NULL
;
155 r
= json_build(&arr
, JSON_BUILD_EMPTY_ARRAY
);
159 for (UnitType t
= 0; t
< _UNIT_TYPE_MAX
; t
++) {
161 if (!unit_vtable
[t
]->can_set_managed_oom
)
164 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[t
]) {
167 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u
)))
170 c
= unit_get_cgroup_context(u
);
174 for (size_t j
= 0; j
< ELEMENTSOF(managed_oom_mode_properties
); j
++) {
175 _cleanup_(json_variant_unrefp
) JsonVariant
*e
= NULL
;
177 /* For the initial varlink call we only care about units that enabled (i.e. mode is not
178 * set to "auto") oomd properties. */
179 if (!(streq(managed_oom_mode_properties
[j
], "ManagedOOMSwap") && c
->moom_swap
== MANAGED_OOM_KILL
) &&
180 !(streq(managed_oom_mode_properties
[j
], "ManagedOOMMemoryPressure") && c
->moom_mem_pressure
== MANAGED_OOM_KILL
))
183 r
= build_managed_oom_json_array_element(u
, managed_oom_mode_properties
[j
], &e
);
187 r
= json_variant_append_array(&arr
, e
);
194 r
= json_build(&v
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("cgroups", JSON_BUILD_VARIANT(arr
))));
202 static int vl_method_subscribe_managed_oom_cgroups(
204 JsonVariant
*parameters
,
205 VarlinkMethodFlags flags
,
208 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
209 Manager
*m
= ASSERT_PTR(userdata
);
216 r
= varlink_get_peer_pid(link
, &pid
);
220 u
= manager_get_unit_by_pid(m
, pid
);
222 return varlink_error(link
, VARLINK_ERROR_PERMISSION_DENIED
, NULL
);
224 /* This is meant to be a deterrent and not actual security. The alternative is to check for the systemd-oom
225 * user that this unit runs as, but NSS lookups are blocking and not allowed from PID 1. */
226 if (!streq(u
->id
, "systemd-oomd.service"))
227 return varlink_error(link
, VARLINK_ERROR_PERMISSION_DENIED
, NULL
);
229 if (json_variant_elements(parameters
) > 0)
230 return varlink_error_invalid_parameter(link
, parameters
);
232 /* We only take one subscriber for this method so return an error if there's already an existing one.
233 * This shouldn't happen since systemd-oomd is the only client of this method. */
234 if (FLAGS_SET(flags
, VARLINK_METHOD_MORE
) && m
->managed_oom_varlink
)
235 return varlink_error(link
, VARLINK_ERROR_SUBSCRIPTION_TAKEN
, NULL
);
237 r
= build_managed_oom_cgroups_json(m
, &v
);
241 if (!FLAGS_SET(flags
, VARLINK_METHOD_MORE
))
242 return varlink_reply(link
, v
);
244 assert(!m
->managed_oom_varlink
);
245 m
->managed_oom_varlink
= varlink_ref(link
);
246 return varlink_notify(m
->managed_oom_varlink
, v
);
249 static int manager_varlink_send_managed_oom_initial(Manager
*m
) {
250 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
255 if (MANAGER_IS_SYSTEM(m
))
258 assert(m
->managed_oom_varlink
);
260 r
= build_managed_oom_cgroups_json(m
, &v
);
264 return varlink_send(m
->managed_oom_varlink
, "io.systemd.oom.ReportManagedOOMCGroups", v
);
267 static int vl_method_get_user_record(Varlink
*link
, JsonVariant
*parameters
, VarlinkMethodFlags flags
, void *userdata
) {
269 static const JsonDispatch dispatch_table
[] = {
270 { "uid", JSON_VARIANT_UNSIGNED
, json_dispatch_uid_gid
, offsetof(LookupParameters
, uid
), 0 },
271 { "userName", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, user_name
), JSON_SAFE
},
272 { "service", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, service
), 0 },
276 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
277 LookupParameters p
= {
280 _cleanup_free_
char *found_name
= NULL
;
281 uid_t found_uid
= UID_INVALID
, uid
;
282 Manager
*m
= ASSERT_PTR(userdata
);
288 r
= json_dispatch(parameters
, dispatch_table
, NULL
, 0, &p
);
292 if (!streq_ptr(p
.service
, "io.systemd.DynamicUser"))
293 return varlink_error(link
, "io.systemd.UserDatabase.BadService", NULL
);
295 if (uid_is_valid(p
.uid
))
296 r
= dynamic_user_lookup_uid(m
, p
.uid
, &found_name
);
297 else if (p
.user_name
)
298 r
= dynamic_user_lookup_name(m
, p
.user_name
, &found_uid
);
302 HASHMAP_FOREACH(d
, m
->dynamic_users
) {
303 r
= dynamic_user_current(d
, &uid
);
304 if (r
== -EAGAIN
) /* not realized yet? */
309 if (!user_match_lookup_parameters(&p
, d
->name
, uid
))
313 r
= varlink_notify(link
, v
);
317 v
= json_variant_unref(v
);
320 r
= build_user_json(d
->name
, uid
, &v
);
326 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
328 return varlink_reply(link
, v
);
331 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
335 uid
= uid_is_valid(found_uid
) ? found_uid
: p
.uid
;
336 un
= found_name
?: p
.user_name
;
338 if (!user_match_lookup_parameters(&p
, un
, uid
))
339 return varlink_error(link
, "io.systemd.UserDatabase.ConflictingRecordFound", NULL
);
341 r
= build_user_json(un
, uid
, &v
);
345 return varlink_reply(link
, v
);
348 static int build_group_json(const char *group_name
, gid_t gid
, JsonVariant
**ret
) {
350 assert(gid_is_valid(gid
));
353 return json_build(ret
, JSON_BUILD_OBJECT(
354 JSON_BUILD_PAIR("record", JSON_BUILD_OBJECT(
355 JSON_BUILD_PAIR("groupName", JSON_BUILD_STRING(group_name
)),
356 JSON_BUILD_PAIR("description", JSON_BUILD_CONST_STRING("Dynamic Group")),
357 JSON_BUILD_PAIR("gid", JSON_BUILD_UNSIGNED(gid
)),
358 JSON_BUILD_PAIR("service", JSON_BUILD_CONST_STRING("io.systemd.DynamicUser")),
359 JSON_BUILD_PAIR("disposition", JSON_BUILD_CONST_STRING("dynamic"))))));
362 static bool group_match_lookup_parameters(LookupParameters
*p
, const char *name
, gid_t gid
) {
365 if (p
->group_name
&& !streq(name
, p
->group_name
))
368 if (gid_is_valid(p
->gid
) && gid
!= p
->gid
)
374 static int vl_method_get_group_record(Varlink
*link
, JsonVariant
*parameters
, VarlinkMethodFlags flags
, void *userdata
) {
376 static const JsonDispatch dispatch_table
[] = {
377 { "gid", JSON_VARIANT_UNSIGNED
, json_dispatch_uid_gid
, offsetof(LookupParameters
, gid
), 0 },
378 { "groupName", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, group_name
), JSON_SAFE
},
379 { "service", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, service
), 0 },
383 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
384 LookupParameters p
= {
387 _cleanup_free_
char *found_name
= NULL
;
388 uid_t found_gid
= GID_INVALID
, gid
;
389 Manager
*m
= ASSERT_PTR(userdata
);
395 r
= json_dispatch(parameters
, dispatch_table
, NULL
, 0, &p
);
399 if (!streq_ptr(p
.service
, "io.systemd.DynamicUser"))
400 return varlink_error(link
, "io.systemd.UserDatabase.BadService", NULL
);
402 if (gid_is_valid(p
.gid
))
403 r
= dynamic_user_lookup_uid(m
, (uid_t
) p
.gid
, &found_name
);
404 else if (p
.group_name
)
405 r
= dynamic_user_lookup_name(m
, p
.group_name
, (uid_t
*) &found_gid
);
409 HASHMAP_FOREACH(d
, m
->dynamic_users
) {
412 r
= dynamic_user_current(d
, &uid
);
418 if (!group_match_lookup_parameters(&p
, d
->name
, (gid_t
) uid
))
422 r
= varlink_notify(link
, v
);
426 v
= json_variant_unref(v
);
429 r
= build_group_json(d
->name
, (gid_t
) uid
, &v
);
435 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
437 return varlink_reply(link
, v
);
440 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
444 gid
= gid_is_valid(found_gid
) ? found_gid
: p
.gid
;
445 gn
= found_name
?: p
.group_name
;
447 if (!group_match_lookup_parameters(&p
, gn
, gid
))
448 return varlink_error(link
, "io.systemd.UserDatabase.ConflictingRecordFound", NULL
);
450 r
= build_group_json(gn
, gid
, &v
);
454 return varlink_reply(link
, v
);
457 static int vl_method_get_memberships(Varlink
*link
, JsonVariant
*parameters
, VarlinkMethodFlags flags
, void *userdata
) {
459 static const JsonDispatch dispatch_table
[] = {
460 { "userName", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, user_name
), JSON_SAFE
},
461 { "groupName", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, group_name
), JSON_SAFE
},
462 { "service", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, service
), 0 },
466 LookupParameters p
= {};
471 r
= json_dispatch(parameters
, dispatch_table
, NULL
, 0, &p
);
475 if (!streq_ptr(p
.service
, "io.systemd.DynamicUser"))
476 return varlink_error(link
, "io.systemd.UserDatabase.BadService", NULL
);
478 /* We don't support auxiliary groups with dynamic users. */
479 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
482 static void vl_disconnect(VarlinkServer
*s
, Varlink
*link
, void *userdata
) {
483 Manager
*m
= ASSERT_PTR(userdata
);
488 if (link
== m
->managed_oom_varlink
)
489 m
->managed_oom_varlink
= varlink_unref(link
);
492 static int manager_varlink_init_system(Manager
*m
) {
493 _cleanup_(varlink_server_unrefp
) VarlinkServer
*s
= NULL
;
498 if (m
->varlink_server
)
501 if (!MANAGER_IS_SYSTEM(m
))
504 r
= manager_setup_varlink_server(m
, &s
);
506 return log_error_errno(r
, "Failed to set up varlink server: %m");
508 if (!MANAGER_IS_TEST_RUN(m
)) {
509 (void) mkdir_p_label("/run/systemd/userdb", 0755);
511 r
= varlink_server_listen_address(s
, "/run/systemd/userdb/io.systemd.DynamicUser", 0666);
513 return log_error_errno(r
, "Failed to bind to varlink socket: %m");
515 r
= varlink_server_listen_address(s
, VARLINK_ADDR_PATH_MANAGED_OOM_SYSTEM
, 0666);
517 return log_error_errno(r
, "Failed to bind to varlink socket: %m");
520 r
= varlink_server_attach_event(s
, m
->event
, SD_EVENT_PRIORITY_NORMAL
);
522 return log_error_errno(r
, "Failed to attach varlink connection to event loop: %m");
524 m
->varlink_server
= TAKE_PTR(s
);
528 static int vl_reply(Varlink
*link
, JsonVariant
*parameters
, const char *error_id
, VarlinkReplyFlags flags
, void *userdata
) {
529 Manager
*m
= ASSERT_PTR(userdata
);
533 log_debug("varlink systemd-oomd client error: %s", error_id
);
535 if (FLAGS_SET(flags
, VARLINK_REPLY_ERROR
) && FLAGS_SET(flags
, VARLINK_REPLY_LOCAL
)) {
536 /* Varlink connection was closed, likely because of systemd-oomd restart. Let's try to
537 * reconnect and send the initial ManagedOOM update again. */
539 m
->managed_oom_varlink
= varlink_unref(link
);
541 log_debug("Reconnecting to %s", VARLINK_ADDR_PATH_MANAGED_OOM_USER
);
543 r
= manager_varlink_init(m
);
551 static int manager_varlink_init_user(Manager
*m
) {
552 _cleanup_(varlink_close_unrefp
) Varlink
*link
= NULL
;
557 if (m
->managed_oom_varlink
)
560 if (MANAGER_IS_TEST_RUN(m
))
563 r
= varlink_connect_address(&link
, VARLINK_ADDR_PATH_MANAGED_OOM_USER
);
565 if (r
== -ENOENT
|| ERRNO_IS_DISCONNECT(r
)) {
566 log_debug("systemd-oomd varlink unix socket not found, skipping user manager varlink setup");
569 return log_error_errno(r
, "Failed to connect to %s: %m", VARLINK_ADDR_PATH_MANAGED_OOM_USER
);
572 varlink_set_userdata(link
, m
);
574 r
= varlink_bind_reply(link
, vl_reply
);
578 r
= varlink_attach_event(link
, m
->event
, SD_EVENT_PRIORITY_NORMAL
);
580 return log_error_errno(r
, "Failed to attach varlink connection to event loop: %m");
582 m
->managed_oom_varlink
= TAKE_PTR(link
);
584 /* Queue the initial ManagedOOM update. */
585 (void) manager_varlink_send_managed_oom_initial(m
);
590 int manager_setup_varlink_server(Manager
*m
, VarlinkServer
**ret
) {
591 _cleanup_(varlink_server_unrefp
) VarlinkServer
*s
= NULL
;
597 r
= varlink_server_new(&s
, VARLINK_SERVER_ACCOUNT_UID
|VARLINK_SERVER_INHERIT_USERDATA
);
599 return log_debug_errno(r
, "Failed to allocate varlink server object: %m");
601 varlink_server_set_userdata(s
, m
);
603 r
= varlink_server_bind_method_many(
605 "io.systemd.UserDatabase.GetUserRecord", vl_method_get_user_record
,
606 "io.systemd.UserDatabase.GetGroupRecord", vl_method_get_group_record
,
607 "io.systemd.UserDatabase.GetMemberships", vl_method_get_memberships
,
608 "io.systemd.ManagedOOM.SubscribeManagedOOMCGroups", vl_method_subscribe_managed_oom_cgroups
);
610 return log_debug_errno(r
, "Failed to register varlink methods: %m");
612 r
= varlink_server_bind_disconnect(s
, vl_disconnect
);
614 return log_debug_errno(r
, "Failed to register varlink disconnect handler: %m");
620 int manager_varlink_init(Manager
*m
) {
621 return MANAGER_IS_SYSTEM(m
) ? manager_varlink_init_system(m
) : manager_varlink_init_user(m
);
624 void manager_varlink_done(Manager
*m
) {
627 /* Explicitly close the varlink connection to oomd. Note we first take the varlink connection out of
628 * the manager, and only then disconnect it — in two steps – so that we don't end up accidentally
629 * unreffing it twice. After all, closing the connection might cause the disconnect handler we
630 * installed (vl_disconnect() above) to be called, where we will unref it too. */
631 varlink_close_unref(TAKE_PTR(m
->managed_oom_varlink
));
633 m
->varlink_server
= varlink_server_unref(m
->varlink_server
);
634 m
->managed_oom_varlink
= varlink_close_unref(m
->managed_oom_varlink
);