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 static const UnitType supported_unit_types
[] = { UNIT_SLICE
, UNIT_SERVICE
, UNIT_SCOPE
};
150 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
, *arr
= NULL
;
156 r
= json_build(&arr
, JSON_BUILD_EMPTY_ARRAY
);
160 for (size_t i
= 0; i
< ELEMENTSOF(supported_unit_types
); i
++)
161 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[supported_unit_types
[i
]]) {
164 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u
)))
167 c
= unit_get_cgroup_context(u
);
171 for (size_t j
= 0; j
< ELEMENTSOF(managed_oom_mode_properties
); j
++) {
172 _cleanup_(json_variant_unrefp
) JsonVariant
*e
= NULL
;
174 /* For the initial varlink call we only care about units that enabled (i.e. mode is not
175 * set to "auto") oomd properties. */
176 if (!(streq(managed_oom_mode_properties
[j
], "ManagedOOMSwap") && c
->moom_swap
== MANAGED_OOM_KILL
) &&
177 !(streq(managed_oom_mode_properties
[j
], "ManagedOOMMemoryPressure") && c
->moom_mem_pressure
== MANAGED_OOM_KILL
))
180 r
= build_managed_oom_json_array_element(u
, managed_oom_mode_properties
[j
], &e
);
184 r
= json_variant_append_array(&arr
, e
);
190 r
= json_build(&v
, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("cgroups", JSON_BUILD_VARIANT(arr
))));
198 static int vl_method_subscribe_managed_oom_cgroups(
200 JsonVariant
*parameters
,
201 VarlinkMethodFlags flags
,
204 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
205 Manager
*m
= ASSERT_PTR(userdata
);
212 r
= varlink_get_peer_pid(link
, &pid
);
216 u
= manager_get_unit_by_pid(m
, pid
);
218 return varlink_error(link
, VARLINK_ERROR_PERMISSION_DENIED
, NULL
);
220 /* This is meant to be a deterrent and not actual security. The alternative is to check for the systemd-oom
221 * user that this unit runs as, but NSS lookups are blocking and not allowed from PID 1. */
222 if (!streq(u
->id
, "systemd-oomd.service"))
223 return varlink_error(link
, VARLINK_ERROR_PERMISSION_DENIED
, NULL
);
225 if (json_variant_elements(parameters
) > 0)
226 return varlink_error_invalid_parameter(link
, parameters
);
228 /* We only take one subscriber for this method so return an error if there's already an existing one.
229 * This shouldn't happen since systemd-oomd is the only client of this method. */
230 if (FLAGS_SET(flags
, VARLINK_METHOD_MORE
) && m
->managed_oom_varlink
)
231 return varlink_error(link
, VARLINK_ERROR_SUBSCRIPTION_TAKEN
, NULL
);
233 r
= build_managed_oom_cgroups_json(m
, &v
);
237 if (!FLAGS_SET(flags
, VARLINK_METHOD_MORE
))
238 return varlink_reply(link
, v
);
240 assert(!m
->managed_oom_varlink
);
241 m
->managed_oom_varlink
= varlink_ref(link
);
242 return varlink_notify(m
->managed_oom_varlink
, v
);
245 static int manager_varlink_send_managed_oom_initial(Manager
*m
) {
246 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
251 if (MANAGER_IS_SYSTEM(m
))
254 assert(m
->managed_oom_varlink
);
256 r
= build_managed_oom_cgroups_json(m
, &v
);
260 return varlink_send(m
->managed_oom_varlink
, "io.systemd.oom.ReportManagedOOMCGroups", v
);
263 static int vl_method_get_user_record(Varlink
*link
, JsonVariant
*parameters
, VarlinkMethodFlags flags
, void *userdata
) {
265 static const JsonDispatch dispatch_table
[] = {
266 { "uid", JSON_VARIANT_UNSIGNED
, json_dispatch_uid_gid
, offsetof(LookupParameters
, uid
), 0 },
267 { "userName", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, user_name
), JSON_SAFE
},
268 { "service", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, service
), 0 },
272 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
273 LookupParameters p
= {
276 _cleanup_free_
char *found_name
= NULL
;
277 uid_t found_uid
= UID_INVALID
, uid
;
278 Manager
*m
= ASSERT_PTR(userdata
);
284 r
= json_dispatch(parameters
, dispatch_table
, NULL
, 0, &p
);
288 if (!streq_ptr(p
.service
, "io.systemd.DynamicUser"))
289 return varlink_error(link
, "io.systemd.UserDatabase.BadService", NULL
);
291 if (uid_is_valid(p
.uid
))
292 r
= dynamic_user_lookup_uid(m
, p
.uid
, &found_name
);
293 else if (p
.user_name
)
294 r
= dynamic_user_lookup_name(m
, p
.user_name
, &found_uid
);
298 HASHMAP_FOREACH(d
, m
->dynamic_users
) {
299 r
= dynamic_user_current(d
, &uid
);
300 if (r
== -EAGAIN
) /* not realized yet? */
305 if (!user_match_lookup_parameters(&p
, d
->name
, uid
))
309 r
= varlink_notify(link
, v
);
313 v
= json_variant_unref(v
);
316 r
= build_user_json(d
->name
, uid
, &v
);
322 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
324 return varlink_reply(link
, v
);
327 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
331 uid
= uid_is_valid(found_uid
) ? found_uid
: p
.uid
;
332 un
= found_name
?: p
.user_name
;
334 if (!user_match_lookup_parameters(&p
, un
, uid
))
335 return varlink_error(link
, "io.systemd.UserDatabase.ConflictingRecordFound", NULL
);
337 r
= build_user_json(un
, uid
, &v
);
341 return varlink_reply(link
, v
);
344 static int build_group_json(const char *group_name
, gid_t gid
, JsonVariant
**ret
) {
346 assert(gid_is_valid(gid
));
349 return json_build(ret
, JSON_BUILD_OBJECT(
350 JSON_BUILD_PAIR("record", JSON_BUILD_OBJECT(
351 JSON_BUILD_PAIR("groupName", JSON_BUILD_STRING(group_name
)),
352 JSON_BUILD_PAIR("description", JSON_BUILD_CONST_STRING("Dynamic Group")),
353 JSON_BUILD_PAIR("gid", JSON_BUILD_UNSIGNED(gid
)),
354 JSON_BUILD_PAIR("service", JSON_BUILD_CONST_STRING("io.systemd.DynamicUser")),
355 JSON_BUILD_PAIR("disposition", JSON_BUILD_CONST_STRING("dynamic"))))));
358 static bool group_match_lookup_parameters(LookupParameters
*p
, const char *name
, gid_t gid
) {
361 if (p
->group_name
&& !streq(name
, p
->group_name
))
364 if (gid_is_valid(p
->gid
) && gid
!= p
->gid
)
370 static int vl_method_get_group_record(Varlink
*link
, JsonVariant
*parameters
, VarlinkMethodFlags flags
, void *userdata
) {
372 static const JsonDispatch dispatch_table
[] = {
373 { "gid", JSON_VARIANT_UNSIGNED
, json_dispatch_uid_gid
, offsetof(LookupParameters
, gid
), 0 },
374 { "groupName", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, group_name
), JSON_SAFE
},
375 { "service", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, service
), 0 },
379 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
380 LookupParameters p
= {
383 _cleanup_free_
char *found_name
= NULL
;
384 uid_t found_gid
= GID_INVALID
, gid
;
385 Manager
*m
= ASSERT_PTR(userdata
);
391 r
= json_dispatch(parameters
, dispatch_table
, NULL
, 0, &p
);
395 if (!streq_ptr(p
.service
, "io.systemd.DynamicUser"))
396 return varlink_error(link
, "io.systemd.UserDatabase.BadService", NULL
);
398 if (gid_is_valid(p
.gid
))
399 r
= dynamic_user_lookup_uid(m
, (uid_t
) p
.gid
, &found_name
);
400 else if (p
.group_name
)
401 r
= dynamic_user_lookup_name(m
, p
.group_name
, (uid_t
*) &found_gid
);
405 HASHMAP_FOREACH(d
, m
->dynamic_users
) {
408 r
= dynamic_user_current(d
, &uid
);
414 if (!group_match_lookup_parameters(&p
, d
->name
, (gid_t
) uid
))
418 r
= varlink_notify(link
, v
);
422 v
= json_variant_unref(v
);
425 r
= build_group_json(d
->name
, (gid_t
) uid
, &v
);
431 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
433 return varlink_reply(link
, v
);
436 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
440 gid
= gid_is_valid(found_gid
) ? found_gid
: p
.gid
;
441 gn
= found_name
?: p
.group_name
;
443 if (!group_match_lookup_parameters(&p
, gn
, gid
))
444 return varlink_error(link
, "io.systemd.UserDatabase.ConflictingRecordFound", NULL
);
446 r
= build_group_json(gn
, gid
, &v
);
450 return varlink_reply(link
, v
);
453 static int vl_method_get_memberships(Varlink
*link
, JsonVariant
*parameters
, VarlinkMethodFlags flags
, void *userdata
) {
455 static const JsonDispatch dispatch_table
[] = {
456 { "userName", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, user_name
), JSON_SAFE
},
457 { "groupName", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, group_name
), JSON_SAFE
},
458 { "service", JSON_VARIANT_STRING
, json_dispatch_const_string
, offsetof(LookupParameters
, service
), 0 },
462 LookupParameters p
= {};
467 r
= json_dispatch(parameters
, dispatch_table
, NULL
, 0, &p
);
471 if (!streq_ptr(p
.service
, "io.systemd.DynamicUser"))
472 return varlink_error(link
, "io.systemd.UserDatabase.BadService", NULL
);
474 /* We don't support auxiliary groups with dynamic users. */
475 return varlink_error(link
, "io.systemd.UserDatabase.NoRecordFound", NULL
);
478 static void vl_disconnect(VarlinkServer
*s
, Varlink
*link
, void *userdata
) {
479 Manager
*m
= ASSERT_PTR(userdata
);
484 if (link
== m
->managed_oom_varlink
)
485 m
->managed_oom_varlink
= varlink_unref(link
);
488 static int manager_varlink_init_system(Manager
*m
) {
489 _cleanup_(varlink_server_unrefp
) VarlinkServer
*s
= NULL
;
494 if (m
->varlink_server
)
497 if (!MANAGER_IS_SYSTEM(m
))
500 r
= manager_setup_varlink_server(m
, &s
);
502 return log_error_errno(r
, "Failed to set up varlink server: %m");
504 if (!MANAGER_IS_TEST_RUN(m
)) {
505 (void) mkdir_p_label("/run/systemd/userdb", 0755);
507 r
= varlink_server_listen_address(s
, "/run/systemd/userdb/io.systemd.DynamicUser", 0666);
509 return log_error_errno(r
, "Failed to bind to varlink socket: %m");
511 r
= varlink_server_listen_address(s
, VARLINK_ADDR_PATH_MANAGED_OOM_SYSTEM
, 0666);
513 return log_error_errno(r
, "Failed to bind to varlink socket: %m");
516 r
= varlink_server_attach_event(s
, m
->event
, SD_EVENT_PRIORITY_NORMAL
);
518 return log_error_errno(r
, "Failed to attach varlink connection to event loop: %m");
520 m
->varlink_server
= TAKE_PTR(s
);
524 static int vl_reply(Varlink
*link
, JsonVariant
*parameters
, const char *error_id
, VarlinkReplyFlags flags
, void *userdata
) {
525 Manager
*m
= ASSERT_PTR(userdata
);
529 log_debug("varlink systemd-oomd client error: %s", error_id
);
531 if (FLAGS_SET(flags
, VARLINK_REPLY_ERROR
) && FLAGS_SET(flags
, VARLINK_REPLY_LOCAL
)) {
532 /* Varlink connection was closed, likely because of systemd-oomd restart. Let's try to
533 * reconnect and send the initial ManagedOOM update again. */
535 m
->managed_oom_varlink
= varlink_unref(link
);
537 log_debug("Reconnecting to %s", VARLINK_ADDR_PATH_MANAGED_OOM_USER
);
539 r
= manager_varlink_init(m
);
547 static int manager_varlink_init_user(Manager
*m
) {
548 _cleanup_(varlink_close_unrefp
) Varlink
*link
= NULL
;
553 if (m
->managed_oom_varlink
)
556 if (MANAGER_IS_TEST_RUN(m
))
559 r
= varlink_connect_address(&link
, VARLINK_ADDR_PATH_MANAGED_OOM_USER
);
560 if (r
== -ENOENT
|| ERRNO_IS_DISCONNECT(r
)) {
561 log_debug("systemd-oomd varlink unix socket not found, skipping user manager varlink setup");
565 return log_error_errno(r
, "Failed to connect to %s: %m", VARLINK_ADDR_PATH_MANAGED_OOM_USER
);
567 varlink_set_userdata(link
, m
);
569 r
= varlink_bind_reply(link
, vl_reply
);
573 r
= varlink_attach_event(link
, m
->event
, SD_EVENT_PRIORITY_NORMAL
);
575 return log_error_errno(r
, "Failed to attach varlink connection to event loop: %m");
577 m
->managed_oom_varlink
= TAKE_PTR(link
);
579 /* Queue the initial ManagedOOM update. */
580 (void) manager_varlink_send_managed_oom_initial(m
);
585 int manager_setup_varlink_server(Manager
*m
, VarlinkServer
**ret
) {
586 _cleanup_(varlink_server_unrefp
) VarlinkServer
*s
= NULL
;
592 r
= varlink_server_new(&s
, VARLINK_SERVER_ACCOUNT_UID
|VARLINK_SERVER_INHERIT_USERDATA
);
594 return log_debug_errno(r
, "Failed to allocate varlink server object: %m");
596 varlink_server_set_userdata(s
, m
);
598 r
= varlink_server_bind_method_many(
600 "io.systemd.UserDatabase.GetUserRecord", vl_method_get_user_record
,
601 "io.systemd.UserDatabase.GetGroupRecord", vl_method_get_group_record
,
602 "io.systemd.UserDatabase.GetMemberships", vl_method_get_memberships
,
603 "io.systemd.ManagedOOM.SubscribeManagedOOMCGroups", vl_method_subscribe_managed_oom_cgroups
);
605 return log_debug_errno(r
, "Failed to register varlink methods: %m");
607 r
= varlink_server_bind_disconnect(s
, vl_disconnect
);
609 return log_debug_errno(r
, "Failed to register varlink disconnect handler: %m");
615 int manager_varlink_init(Manager
*m
) {
616 return MANAGER_IS_SYSTEM(m
) ? manager_varlink_init_system(m
) : manager_varlink_init_user(m
);
619 void manager_varlink_done(Manager
*m
) {
622 /* Explicitly close the varlink connection to oomd. Note we first take the varlink connection out of
623 * the manager, and only then disconnect it — in two steps – so that we don't end up accidentally
624 * unreffing it twice. After all, closing the connection might cause the disconnect handler we
625 * installed (vl_disconnect() above) to be called, where we will unref it too. */
626 varlink_close_unref(TAKE_PTR(m
->managed_oom_varlink
));
628 m
->varlink_server
= varlink_server_unref(m
->varlink_server
);
629 m
->managed_oom_varlink
= varlink_close_unref(m
->managed_oom_varlink
);