]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/core-varlink.c
Merge pull request #20806 from fbuihuu/test-make-debug-tools-optional
[thirdparty/systemd.git] / src / core / core-varlink.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "core-varlink.h"
4 #include "mkdir.h"
5 #include "strv.h"
6 #include "user-util.h"
7 #include "varlink.h"
8
9 typedef struct LookupParameters {
10 const char *user_name;
11 const char *group_name;
12 union {
13 uid_t uid;
14 gid_t gid;
15 };
16 const char *service;
17 } LookupParameters;
18
19 static const char* const managed_oom_mode_properties[] = {
20 "ManagedOOMSwap",
21 "ManagedOOMMemoryPressure",
22 };
23
24 static int build_user_json(const char *user_name, uid_t uid, JsonVariant **ret) {
25 assert(user_name);
26 assert(uid_is_valid(uid));
27 assert(ret);
28
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_STRING("Dynamic User")),
35 JSON_BUILD_PAIR("homeDirectory", JSON_BUILD_STRING("/")),
36 JSON_BUILD_PAIR("shell", JSON_BUILD_STRING(NOLOGIN)),
37 JSON_BUILD_PAIR("locked", JSON_BUILD_BOOLEAN(true)),
38 JSON_BUILD_PAIR("service", JSON_BUILD_STRING("io.systemd.DynamicUser")),
39 JSON_BUILD_PAIR("disposition", JSON_BUILD_STRING("dynamic"))))));
40 }
41
42 static bool user_match_lookup_parameters(LookupParameters *p, const char *name, uid_t uid) {
43 assert(p);
44
45 if (p->user_name && !streq(name, p->user_name))
46 return false;
47
48 if (uid_is_valid(p->uid) && uid != p->uid)
49 return false;
50
51 return true;
52 }
53
54 static int build_managed_oom_json_array_element(Unit *u, const char *property, JsonVariant **ret_v) {
55 bool use_limit = false;
56 CGroupContext *c;
57 const char *mode;
58
59 assert(u);
60 assert(property);
61 assert(ret_v);
62
63 if (!UNIT_VTABLE(u)->can_set_managed_oom)
64 return -EOPNOTSUPP;
65
66 c = unit_get_cgroup_context(u);
67 if (!c)
68 return -EINVAL;
69
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);
78 use_limit = true;
79 } else
80 return -EINVAL;
81
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))));
87 }
88
89 int manager_varlink_send_managed_oom_update(Unit *u) {
90 _cleanup_(json_variant_unrefp) JsonVariant *arr = NULL, *v = NULL;
91 CGroupContext *c;
92 int r;
93
94 assert(u);
95
96 if (!UNIT_VTABLE(u)->can_set_managed_oom || !u->manager || !u->cgroup_path)
97 return 0;
98
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)
103 return 0;
104 } else {
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);
108 if (r <= 0)
109 return r;
110 }
111
112 c = unit_get_cgroup_context(u);
113 if (!c)
114 return 0;
115
116 r = json_build(&arr, JSON_BUILD_EMPTY_ARRAY);
117 if (r < 0)
118 return r;
119
120 for (size_t i = 0; i < ELEMENTSOF(managed_oom_mode_properties); i++) {
121 _cleanup_(json_variant_unrefp) JsonVariant *e = NULL;
122
123 r = build_managed_oom_json_array_element(u, managed_oom_mode_properties[i], &e);
124 if (r < 0)
125 return r;
126
127 r = json_variant_append_array(&arr, e);
128 if (r < 0)
129 return r;
130 }
131
132 r = json_build(&v, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("cgroups", JSON_BUILD_VARIANT(arr))));
133 if (r < 0)
134 return r;
135
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);
140 else
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);
144
145 return r;
146 }
147
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;
151 int r;
152
153 assert(m);
154 assert(ret);
155
156 r = json_build(&arr, JSON_BUILD_EMPTY_ARRAY);
157 if (r < 0)
158 return r;
159
160 for (size_t i = 0; i < ELEMENTSOF(supported_unit_types); i++) {
161 Unit *u;
162
163 LIST_FOREACH(units_by_type, u, m->units_by_type[supported_unit_types[i]]) {
164 CGroupContext *c;
165
166 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)))
167 continue;
168
169 c = unit_get_cgroup_context(u);
170 if (!c)
171 continue;
172
173 for (size_t j = 0; j < ELEMENTSOF(managed_oom_mode_properties); j++) {
174 _cleanup_(json_variant_unrefp) JsonVariant *e = NULL;
175
176 /* For the initial varlink call we only care about units that enabled (i.e. mode is not
177 * set to "auto") oomd properties. */
178 if (!(streq(managed_oom_mode_properties[j], "ManagedOOMSwap") && c->moom_swap == MANAGED_OOM_KILL) &&
179 !(streq(managed_oom_mode_properties[j], "ManagedOOMMemoryPressure") && c->moom_mem_pressure == MANAGED_OOM_KILL))
180 continue;
181
182 r = build_managed_oom_json_array_element(u, managed_oom_mode_properties[j], &e);
183 if (r < 0)
184 return r;
185
186 r = json_variant_append_array(&arr, e);
187 if (r < 0)
188 return r;
189 }
190 }
191 }
192
193 r = json_build(&v, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("cgroups", JSON_BUILD_VARIANT(arr))));
194 if (r < 0)
195 return r;
196
197 *ret = TAKE_PTR(v);
198 return 0;
199 }
200
201 static int vl_method_subscribe_managed_oom_cgroups(
202 Varlink *link,
203 JsonVariant *parameters,
204 VarlinkMethodFlags flags,
205 void *userdata) {
206
207 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
208 Manager *m = userdata;
209 int r;
210
211 assert(link);
212 assert(m);
213
214 if (json_variant_elements(parameters) > 0)
215 return varlink_error_invalid_parameter(link, parameters);
216
217 /* We only take one subscriber for this method so return an error if there's already an existing one.
218 * This shouldn't happen since systemd-oomd is the only client of this method. */
219 if (FLAGS_SET(flags, VARLINK_METHOD_MORE) && m->managed_oom_varlink)
220 return varlink_error(link, VARLINK_ERROR_SUBSCRIPTION_TAKEN, NULL);
221
222 r = build_managed_oom_cgroups_json(m, &v);
223 if (r < 0)
224 return r;
225
226 if (!FLAGS_SET(flags, VARLINK_METHOD_MORE))
227 return varlink_reply(link, v);
228
229 assert(!m->managed_oom_varlink);
230 m->managed_oom_varlink = varlink_ref(link);
231 return varlink_notify(m->managed_oom_varlink, v);
232 }
233
234 static int manager_varlink_send_managed_oom_initial(Manager *m) {
235 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
236 int r;
237
238 assert(m);
239
240 if (MANAGER_IS_SYSTEM(m))
241 return 0;
242
243 assert(m->managed_oom_varlink);
244
245 r = build_managed_oom_cgroups_json(m, &v);
246 if (r < 0)
247 return r;
248
249 return varlink_send(m->managed_oom_varlink, "io.systemd.oom.ReportManagedOOMCGroups", v);
250 }
251
252 static int vl_method_get_user_record(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
253
254 static const JsonDispatch dispatch_table[] = {
255 { "uid", JSON_VARIANT_UNSIGNED, json_dispatch_uid_gid, offsetof(LookupParameters, uid), 0 },
256 { "userName", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, user_name), JSON_SAFE },
257 { "service", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
258 {}
259 };
260
261 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
262 LookupParameters p = {
263 .uid = UID_INVALID,
264 };
265 _cleanup_free_ char *found_name = NULL;
266 uid_t found_uid = UID_INVALID, uid;
267 Manager *m = userdata;
268 const char *un;
269 int r;
270
271 assert(parameters);
272 assert(m);
273
274 r = json_dispatch(parameters, dispatch_table, NULL, 0, &p);
275 if (r < 0)
276 return r;
277
278 if (!streq_ptr(p.service, "io.systemd.DynamicUser"))
279 return varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
280
281 if (uid_is_valid(p.uid))
282 r = dynamic_user_lookup_uid(m, p.uid, &found_name);
283 else if (p.user_name)
284 r = dynamic_user_lookup_name(m, p.user_name, &found_uid);
285 else {
286 DynamicUser *d;
287
288 HASHMAP_FOREACH(d, m->dynamic_users) {
289 r = dynamic_user_current(d, &uid);
290 if (r == -EAGAIN) /* not realized yet? */
291 continue;
292 if (r < 0)
293 return r;
294
295 if (!user_match_lookup_parameters(&p, d->name, uid))
296 continue;
297
298 if (v) {
299 r = varlink_notify(link, v);
300 if (r < 0)
301 return r;
302
303 v = json_variant_unref(v);
304 }
305
306 r = build_user_json(d->name, uid, &v);
307 if (r < 0)
308 return r;
309 }
310
311 if (!v)
312 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
313
314 return varlink_reply(link, v);
315 }
316 if (r == -ESRCH)
317 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
318 if (r < 0)
319 return r;
320
321 uid = uid_is_valid(found_uid) ? found_uid : p.uid;
322 un = found_name ?: p.user_name;
323
324 if (!user_match_lookup_parameters(&p, un, uid))
325 return varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
326
327 r = build_user_json(un, uid, &v);
328 if (r < 0)
329 return r;
330
331 return varlink_reply(link, v);
332 }
333
334 static int build_group_json(const char *group_name, gid_t gid, JsonVariant **ret) {
335 assert(group_name);
336 assert(gid_is_valid(gid));
337 assert(ret);
338
339 return json_build(ret, JSON_BUILD_OBJECT(
340 JSON_BUILD_PAIR("record", JSON_BUILD_OBJECT(
341 JSON_BUILD_PAIR("groupName", JSON_BUILD_STRING(group_name)),
342 JSON_BUILD_PAIR("description", JSON_BUILD_STRING("Dynamic Group")),
343 JSON_BUILD_PAIR("gid", JSON_BUILD_UNSIGNED(gid)),
344 JSON_BUILD_PAIR("service", JSON_BUILD_STRING("io.systemd.DynamicUser")),
345 JSON_BUILD_PAIR("disposition", JSON_BUILD_STRING("dynamic"))))));
346 }
347
348 static bool group_match_lookup_parameters(LookupParameters *p, const char *name, gid_t gid) {
349 assert(p);
350
351 if (p->group_name && !streq(name, p->group_name))
352 return false;
353
354 if (gid_is_valid(p->gid) && gid != p->gid)
355 return false;
356
357 return true;
358 }
359
360 static int vl_method_get_group_record(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
361
362 static const JsonDispatch dispatch_table[] = {
363 { "gid", JSON_VARIANT_UNSIGNED, json_dispatch_uid_gid, offsetof(LookupParameters, gid), 0 },
364 { "groupName", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, group_name), JSON_SAFE },
365 { "service", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
366 {}
367 };
368
369 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
370 LookupParameters p = {
371 .gid = GID_INVALID,
372 };
373 _cleanup_free_ char *found_name = NULL;
374 uid_t found_gid = GID_INVALID, gid;
375 Manager *m = userdata;
376 const char *gn;
377 int r;
378
379 assert(parameters);
380 assert(m);
381
382 r = json_dispatch(parameters, dispatch_table, NULL, 0, &p);
383 if (r < 0)
384 return r;
385
386 if (!streq_ptr(p.service, "io.systemd.DynamicUser"))
387 return varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
388
389 if (gid_is_valid(p.gid))
390 r = dynamic_user_lookup_uid(m, (uid_t) p.gid, &found_name);
391 else if (p.group_name)
392 r = dynamic_user_lookup_name(m, p.group_name, (uid_t*) &found_gid);
393 else {
394 DynamicUser *d;
395
396 HASHMAP_FOREACH(d, m->dynamic_users) {
397 uid_t uid;
398
399 r = dynamic_user_current(d, &uid);
400 if (r == -EAGAIN)
401 continue;
402 if (r < 0)
403 return r;
404
405 if (!group_match_lookup_parameters(&p, d->name, (gid_t) uid))
406 continue;
407
408 if (v) {
409 r = varlink_notify(link, v);
410 if (r < 0)
411 return r;
412
413 v = json_variant_unref(v);
414 }
415
416 r = build_group_json(d->name, (gid_t) uid, &v);
417 if (r < 0)
418 return r;
419 }
420
421 if (!v)
422 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
423
424 return varlink_reply(link, v);
425 }
426 if (r == -ESRCH)
427 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
428 if (r < 0)
429 return r;
430
431 gid = gid_is_valid(found_gid) ? found_gid : p.gid;
432 gn = found_name ?: p.group_name;
433
434 if (!group_match_lookup_parameters(&p, gn, gid))
435 return varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
436
437 r = build_group_json(gn, gid, &v);
438 if (r < 0)
439 return r;
440
441 return varlink_reply(link, v);
442 }
443
444 static int vl_method_get_memberships(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
445
446 static const JsonDispatch dispatch_table[] = {
447 { "userName", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, user_name), JSON_SAFE },
448 { "groupName", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, group_name), JSON_SAFE },
449 { "service", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
450 {}
451 };
452
453 LookupParameters p = {};
454 int r;
455
456 assert(parameters);
457
458 r = json_dispatch(parameters, dispatch_table, NULL, 0, &p);
459 if (r < 0)
460 return r;
461
462 if (!streq_ptr(p.service, "io.systemd.DynamicUser"))
463 return varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
464
465 /* We don't support auxiliary groups with dynamic users. */
466 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
467 }
468
469 static void vl_disconnect(VarlinkServer *s, Varlink *link, void *userdata) {
470 Manager *m = userdata;
471
472 assert(m);
473 assert(s);
474 assert(link);
475
476 if (link == m->managed_oom_varlink)
477 m->managed_oom_varlink = varlink_unref(link);
478 }
479
480 static int manager_varlink_init_system(Manager *m) {
481 _cleanup_(varlink_server_unrefp) VarlinkServer *s = NULL;
482 int r;
483
484 assert(m);
485
486 if (m->varlink_server)
487 return 1;
488
489 if (!MANAGER_IS_SYSTEM(m))
490 return 0;
491
492 r = varlink_server_new(&s, VARLINK_SERVER_ACCOUNT_UID|VARLINK_SERVER_INHERIT_USERDATA);
493 if (r < 0)
494 return log_error_errno(r, "Failed to allocate varlink server object: %m");
495
496 varlink_server_set_userdata(s, m);
497
498 r = varlink_server_bind_method_many(
499 s,
500 "io.systemd.UserDatabase.GetUserRecord", vl_method_get_user_record,
501 "io.systemd.UserDatabase.GetGroupRecord", vl_method_get_group_record,
502 "io.systemd.UserDatabase.GetMemberships", vl_method_get_memberships,
503 "io.systemd.ManagedOOM.SubscribeManagedOOMCGroups", vl_method_subscribe_managed_oom_cgroups);
504 if (r < 0)
505 return log_error_errno(r, "Failed to register varlink methods: %m");
506
507 r = varlink_server_bind_disconnect(s, vl_disconnect);
508 if (r < 0)
509 return log_error_errno(r, "Failed to register varlink disconnect handler: %m");
510
511 if (!MANAGER_IS_TEST_RUN(m)) {
512 (void) mkdir_p_label("/run/systemd/userdb", 0755);
513
514 r = varlink_server_listen_address(s, "/run/systemd/userdb/io.systemd.DynamicUser", 0666);
515 if (r < 0)
516 return log_error_errno(r, "Failed to bind to varlink socket: %m");
517
518 r = varlink_server_listen_address(s, VARLINK_ADDR_PATH_MANAGED_OOM_SYSTEM, 0666);
519 if (r < 0)
520 return log_error_errno(r, "Failed to bind to varlink socket: %m");
521 }
522
523 r = varlink_server_attach_event(s, m->event, SD_EVENT_PRIORITY_NORMAL);
524 if (r < 0)
525 return log_error_errno(r, "Failed to attach varlink connection to event loop: %m");
526
527 m->varlink_server = TAKE_PTR(s);
528 return 1;
529 }
530
531 static int vl_reply(Varlink *link, JsonVariant *parameters, const char *error_id, VarlinkReplyFlags flags, void *userdata) {
532 Manager *m = userdata;
533 int r;
534
535 assert(m);
536
537 if (error_id)
538 log_debug("varlink systemd-oomd client error: %s", error_id);
539
540 if (FLAGS_SET(flags, VARLINK_REPLY_ERROR) && FLAGS_SET(flags, VARLINK_REPLY_LOCAL)) {
541 /* Varlink connection was closed, likely because of systemd-oomd restart. Let's try to
542 * reconnect and send the initial ManagedOOM update again. */
543
544 m->managed_oom_varlink = varlink_unref(link);
545
546 log_debug("Reconnecting to %s", VARLINK_ADDR_PATH_MANAGED_OOM_USER);
547
548 r = manager_varlink_init(m);
549 if (r <= 0)
550 return r;
551 }
552
553 return 0;
554 }
555
556 static int manager_varlink_init_user(Manager *m) {
557 _cleanup_(varlink_close_unrefp) Varlink *link = NULL;
558 int r;
559
560 assert(m);
561
562 if (m->managed_oom_varlink)
563 return 1;
564
565 r = varlink_connect_address(&link, VARLINK_ADDR_PATH_MANAGED_OOM_USER);
566 if (r == -ENOENT || ERRNO_IS_DISCONNECT(r)) {
567 log_debug("systemd-oomd varlink unix socket not found, skipping user manager varlink setup");
568 return 0;
569 }
570 if (r < 0)
571 return log_error_errno(r, "Failed to connect to %s: %m", VARLINK_ADDR_PATH_MANAGED_OOM_USER);
572
573 varlink_set_userdata(link, m);
574
575 r = varlink_bind_reply(link, vl_reply);
576 if (r < 0)
577 return r;
578
579 r = varlink_attach_event(link, m->event, SD_EVENT_PRIORITY_NORMAL);
580 if (r < 0)
581 return log_error_errno(r, "Failed to attach varlink connection to event loop: %m");
582
583 m->managed_oom_varlink = TAKE_PTR(link);
584
585 /* Queue the initial ManagedOOM update. */
586 (void) manager_varlink_send_managed_oom_initial(m);
587
588 return 1;
589 }
590
591 int manager_varlink_init(Manager *m) {
592 return MANAGER_IS_SYSTEM(m) ? manager_varlink_init_system(m) : manager_varlink_init_user(m);
593 }
594
595 void manager_varlink_done(Manager *m) {
596 assert(m);
597
598 /* Explicitly close the varlink connection to oomd. Note we first take the varlink connection out of
599 * the manager, and only then disconnect it — in two steps – so that we don't end up accidentally
600 * unreffing it twice. After all, closing the connection might cause the disconnect handler we
601 * installed (vl_disconnect() above) to be called, where we will unref it too. */
602 varlink_close_unref(TAKE_PTR(m->managed_oom_varlink));
603
604 m->varlink_server = varlink_server_unref(m->varlink_server);
605 m->managed_oom_varlink = varlink_close_unref(m->managed_oom_varlink);
606 }