]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/core-varlink.c
Merge pull request #24272 from dtardon/asserts
[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-label.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_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"))))));
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 LIST_FOREACH(units_by_type, u, m->units_by_type[supported_unit_types[i]]) {
162 CGroupContext *c;
163
164 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)))
165 continue;
166
167 c = unit_get_cgroup_context(u);
168 if (!c)
169 continue;
170
171 for (size_t j = 0; j < ELEMENTSOF(managed_oom_mode_properties); j++) {
172 _cleanup_(json_variant_unrefp) JsonVariant *e = NULL;
173
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))
178 continue;
179
180 r = build_managed_oom_json_array_element(u, managed_oom_mode_properties[j], &e);
181 if (r < 0)
182 return r;
183
184 r = json_variant_append_array(&arr, e);
185 if (r < 0)
186 return r;
187 }
188 }
189
190 r = json_build(&v, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("cgroups", JSON_BUILD_VARIANT(arr))));
191 if (r < 0)
192 return r;
193
194 *ret = TAKE_PTR(v);
195 return 0;
196 }
197
198 static int vl_method_subscribe_managed_oom_cgroups(
199 Varlink *link,
200 JsonVariant *parameters,
201 VarlinkMethodFlags flags,
202 void *userdata) {
203
204 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
205 Manager *m = ASSERT_PTR(userdata);
206 int r;
207
208 assert(link);
209
210 if (json_variant_elements(parameters) > 0)
211 return varlink_error_invalid_parameter(link, parameters);
212
213 /* We only take one subscriber for this method so return an error if there's already an existing one.
214 * This shouldn't happen since systemd-oomd is the only client of this method. */
215 if (FLAGS_SET(flags, VARLINK_METHOD_MORE) && m->managed_oom_varlink)
216 return varlink_error(link, VARLINK_ERROR_SUBSCRIPTION_TAKEN, NULL);
217
218 r = build_managed_oom_cgroups_json(m, &v);
219 if (r < 0)
220 return r;
221
222 if (!FLAGS_SET(flags, VARLINK_METHOD_MORE))
223 return varlink_reply(link, v);
224
225 assert(!m->managed_oom_varlink);
226 m->managed_oom_varlink = varlink_ref(link);
227 return varlink_notify(m->managed_oom_varlink, v);
228 }
229
230 static int manager_varlink_send_managed_oom_initial(Manager *m) {
231 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
232 int r;
233
234 assert(m);
235
236 if (MANAGER_IS_SYSTEM(m))
237 return 0;
238
239 assert(m->managed_oom_varlink);
240
241 r = build_managed_oom_cgroups_json(m, &v);
242 if (r < 0)
243 return r;
244
245 return varlink_send(m->managed_oom_varlink, "io.systemd.oom.ReportManagedOOMCGroups", v);
246 }
247
248 static int vl_method_get_user_record(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
249
250 static const JsonDispatch dispatch_table[] = {
251 { "uid", JSON_VARIANT_UNSIGNED, json_dispatch_uid_gid, offsetof(LookupParameters, uid), 0 },
252 { "userName", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, user_name), JSON_SAFE },
253 { "service", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
254 {}
255 };
256
257 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
258 LookupParameters p = {
259 .uid = UID_INVALID,
260 };
261 _cleanup_free_ char *found_name = NULL;
262 uid_t found_uid = UID_INVALID, uid;
263 Manager *m = ASSERT_PTR(userdata);
264 const char *un;
265 int r;
266
267 assert(parameters);
268
269 r = json_dispatch(parameters, dispatch_table, NULL, 0, &p);
270 if (r < 0)
271 return r;
272
273 if (!streq_ptr(p.service, "io.systemd.DynamicUser"))
274 return varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
275
276 if (uid_is_valid(p.uid))
277 r = dynamic_user_lookup_uid(m, p.uid, &found_name);
278 else if (p.user_name)
279 r = dynamic_user_lookup_name(m, p.user_name, &found_uid);
280 else {
281 DynamicUser *d;
282
283 HASHMAP_FOREACH(d, m->dynamic_users) {
284 r = dynamic_user_current(d, &uid);
285 if (r == -EAGAIN) /* not realized yet? */
286 continue;
287 if (r < 0)
288 return r;
289
290 if (!user_match_lookup_parameters(&p, d->name, uid))
291 continue;
292
293 if (v) {
294 r = varlink_notify(link, v);
295 if (r < 0)
296 return r;
297
298 v = json_variant_unref(v);
299 }
300
301 r = build_user_json(d->name, uid, &v);
302 if (r < 0)
303 return r;
304 }
305
306 if (!v)
307 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
308
309 return varlink_reply(link, v);
310 }
311 if (r == -ESRCH)
312 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
313 if (r < 0)
314 return r;
315
316 uid = uid_is_valid(found_uid) ? found_uid : p.uid;
317 un = found_name ?: p.user_name;
318
319 if (!user_match_lookup_parameters(&p, un, uid))
320 return varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
321
322 r = build_user_json(un, uid, &v);
323 if (r < 0)
324 return r;
325
326 return varlink_reply(link, v);
327 }
328
329 static int build_group_json(const char *group_name, gid_t gid, JsonVariant **ret) {
330 assert(group_name);
331 assert(gid_is_valid(gid));
332 assert(ret);
333
334 return json_build(ret, JSON_BUILD_OBJECT(
335 JSON_BUILD_PAIR("record", JSON_BUILD_OBJECT(
336 JSON_BUILD_PAIR("groupName", JSON_BUILD_STRING(group_name)),
337 JSON_BUILD_PAIR("description", JSON_BUILD_CONST_STRING("Dynamic Group")),
338 JSON_BUILD_PAIR("gid", JSON_BUILD_UNSIGNED(gid)),
339 JSON_BUILD_PAIR("service", JSON_BUILD_CONST_STRING("io.systemd.DynamicUser")),
340 JSON_BUILD_PAIR("disposition", JSON_BUILD_CONST_STRING("dynamic"))))));
341 }
342
343 static bool group_match_lookup_parameters(LookupParameters *p, const char *name, gid_t gid) {
344 assert(p);
345
346 if (p->group_name && !streq(name, p->group_name))
347 return false;
348
349 if (gid_is_valid(p->gid) && gid != p->gid)
350 return false;
351
352 return true;
353 }
354
355 static int vl_method_get_group_record(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
356
357 static const JsonDispatch dispatch_table[] = {
358 { "gid", JSON_VARIANT_UNSIGNED, json_dispatch_uid_gid, offsetof(LookupParameters, gid), 0 },
359 { "groupName", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, group_name), JSON_SAFE },
360 { "service", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
361 {}
362 };
363
364 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
365 LookupParameters p = {
366 .gid = GID_INVALID,
367 };
368 _cleanup_free_ char *found_name = NULL;
369 uid_t found_gid = GID_INVALID, gid;
370 Manager *m = ASSERT_PTR(userdata);
371 const char *gn;
372 int r;
373
374 assert(parameters);
375
376 r = json_dispatch(parameters, dispatch_table, NULL, 0, &p);
377 if (r < 0)
378 return r;
379
380 if (!streq_ptr(p.service, "io.systemd.DynamicUser"))
381 return varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
382
383 if (gid_is_valid(p.gid))
384 r = dynamic_user_lookup_uid(m, (uid_t) p.gid, &found_name);
385 else if (p.group_name)
386 r = dynamic_user_lookup_name(m, p.group_name, (uid_t*) &found_gid);
387 else {
388 DynamicUser *d;
389
390 HASHMAP_FOREACH(d, m->dynamic_users) {
391 uid_t uid;
392
393 r = dynamic_user_current(d, &uid);
394 if (r == -EAGAIN)
395 continue;
396 if (r < 0)
397 return r;
398
399 if (!group_match_lookup_parameters(&p, d->name, (gid_t) uid))
400 continue;
401
402 if (v) {
403 r = varlink_notify(link, v);
404 if (r < 0)
405 return r;
406
407 v = json_variant_unref(v);
408 }
409
410 r = build_group_json(d->name, (gid_t) uid, &v);
411 if (r < 0)
412 return r;
413 }
414
415 if (!v)
416 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
417
418 return varlink_reply(link, v);
419 }
420 if (r == -ESRCH)
421 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
422 if (r < 0)
423 return r;
424
425 gid = gid_is_valid(found_gid) ? found_gid : p.gid;
426 gn = found_name ?: p.group_name;
427
428 if (!group_match_lookup_parameters(&p, gn, gid))
429 return varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
430
431 r = build_group_json(gn, gid, &v);
432 if (r < 0)
433 return r;
434
435 return varlink_reply(link, v);
436 }
437
438 static int vl_method_get_memberships(Varlink *link, JsonVariant *parameters, VarlinkMethodFlags flags, void *userdata) {
439
440 static const JsonDispatch dispatch_table[] = {
441 { "userName", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, user_name), JSON_SAFE },
442 { "groupName", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, group_name), JSON_SAFE },
443 { "service", JSON_VARIANT_STRING, json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
444 {}
445 };
446
447 LookupParameters p = {};
448 int r;
449
450 assert(parameters);
451
452 r = json_dispatch(parameters, dispatch_table, NULL, 0, &p);
453 if (r < 0)
454 return r;
455
456 if (!streq_ptr(p.service, "io.systemd.DynamicUser"))
457 return varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
458
459 /* We don't support auxiliary groups with dynamic users. */
460 return varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
461 }
462
463 static void vl_disconnect(VarlinkServer *s, Varlink *link, void *userdata) {
464 Manager *m = ASSERT_PTR(userdata);
465
466 assert(s);
467 assert(link);
468
469 if (link == m->managed_oom_varlink)
470 m->managed_oom_varlink = varlink_unref(link);
471 }
472
473 static int manager_varlink_init_system(Manager *m) {
474 _cleanup_(varlink_server_unrefp) VarlinkServer *s = NULL;
475 int r;
476
477 assert(m);
478
479 if (m->varlink_server)
480 return 1;
481
482 if (!MANAGER_IS_SYSTEM(m))
483 return 0;
484
485 r = varlink_server_new(&s, VARLINK_SERVER_ACCOUNT_UID|VARLINK_SERVER_INHERIT_USERDATA);
486 if (r < 0)
487 return log_error_errno(r, "Failed to allocate varlink server object: %m");
488
489 varlink_server_set_userdata(s, m);
490
491 r = varlink_server_bind_method_many(
492 s,
493 "io.systemd.UserDatabase.GetUserRecord", vl_method_get_user_record,
494 "io.systemd.UserDatabase.GetGroupRecord", vl_method_get_group_record,
495 "io.systemd.UserDatabase.GetMemberships", vl_method_get_memberships,
496 "io.systemd.ManagedOOM.SubscribeManagedOOMCGroups", vl_method_subscribe_managed_oom_cgroups);
497 if (r < 0)
498 return log_error_errno(r, "Failed to register varlink methods: %m");
499
500 r = varlink_server_bind_disconnect(s, vl_disconnect);
501 if (r < 0)
502 return log_error_errno(r, "Failed to register varlink disconnect handler: %m");
503
504 if (!MANAGER_IS_TEST_RUN(m)) {
505 (void) mkdir_p_label("/run/systemd/userdb", 0755);
506
507 r = varlink_server_listen_address(s, "/run/systemd/userdb/io.systemd.DynamicUser", 0666);
508 if (r < 0)
509 return log_error_errno(r, "Failed to bind to varlink socket: %m");
510
511 r = varlink_server_listen_address(s, VARLINK_ADDR_PATH_MANAGED_OOM_SYSTEM, 0666);
512 if (r < 0)
513 return log_error_errno(r, "Failed to bind to varlink socket: %m");
514 }
515
516 r = varlink_server_attach_event(s, m->event, SD_EVENT_PRIORITY_NORMAL);
517 if (r < 0)
518 return log_error_errno(r, "Failed to attach varlink connection to event loop: %m");
519
520 m->varlink_server = TAKE_PTR(s);
521 return 1;
522 }
523
524 static int vl_reply(Varlink *link, JsonVariant *parameters, const char *error_id, VarlinkReplyFlags flags, void *userdata) {
525 Manager *m = ASSERT_PTR(userdata);
526 int r;
527
528 if (error_id)
529 log_debug("varlink systemd-oomd client error: %s", error_id);
530
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. */
534
535 m->managed_oom_varlink = varlink_unref(link);
536
537 log_debug("Reconnecting to %s", VARLINK_ADDR_PATH_MANAGED_OOM_USER);
538
539 r = manager_varlink_init(m);
540 if (r <= 0)
541 return r;
542 }
543
544 return 0;
545 }
546
547 static int manager_varlink_init_user(Manager *m) {
548 _cleanup_(varlink_close_unrefp) Varlink *link = NULL;
549 int r;
550
551 assert(m);
552
553 if (m->managed_oom_varlink)
554 return 1;
555
556 if (MANAGER_IS_TEST_RUN(m))
557 return 0;
558
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");
562 return 0;
563 }
564 if (r < 0)
565 return log_error_errno(r, "Failed to connect to %s: %m", VARLINK_ADDR_PATH_MANAGED_OOM_USER);
566
567 varlink_set_userdata(link, m);
568
569 r = varlink_bind_reply(link, vl_reply);
570 if (r < 0)
571 return r;
572
573 r = varlink_attach_event(link, m->event, SD_EVENT_PRIORITY_NORMAL);
574 if (r < 0)
575 return log_error_errno(r, "Failed to attach varlink connection to event loop: %m");
576
577 m->managed_oom_varlink = TAKE_PTR(link);
578
579 /* Queue the initial ManagedOOM update. */
580 (void) manager_varlink_send_managed_oom_initial(m);
581
582 return 1;
583 }
584
585 int manager_varlink_init(Manager *m) {
586 return MANAGER_IS_SYSTEM(m) ? manager_varlink_init_system(m) : manager_varlink_init_user(m);
587 }
588
589 void manager_varlink_done(Manager *m) {
590 assert(m);
591
592 /* Explicitly close the varlink connection to oomd. Note we first take the varlink connection out of
593 * the manager, and only then disconnect it — in two steps – so that we don't end up accidentally
594 * unreffing it twice. After all, closing the connection might cause the disconnect handler we
595 * installed (vl_disconnect() above) to be called, where we will unref it too. */
596 varlink_close_unref(TAKE_PTR(m->managed_oom_varlink));
597
598 m->varlink_server = varlink_server_unref(m->varlink_server);
599 m->managed_oom_varlink = varlink_close_unref(m->managed_oom_varlink);
600 }