]> git.ipfire.org Git - thirdparty/systemd.git/blame_incremental - src/login/logind-dbus.c
ci: use -p and -f when creating dirs/removing files in mkosi job btrfs setup
[thirdparty/systemd.git] / src / login / logind-dbus.c
... / ...
CommitLineData
1/* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3#include <pwd.h>
4#include <sys/stat.h>
5#include <unistd.h>
6
7#include "sd-bus.h"
8#include "sd-device.h"
9#include "sd-messages.h"
10
11#include "alloc-util.h"
12#include "audit-util.h"
13#include "bitfield.h"
14#include "bootspec.h"
15#include "bus-common-errors.h"
16#include "bus-error.h"
17#include "bus-get-properties.h"
18#include "bus-locator.h"
19#include "bus-object.h"
20#include "bus-polkit.h"
21#include "bus-unit-util.h"
22#include "bus-util.h"
23#include "cgroup-util.h"
24#include "device-util.h"
25#include "dirent-util.h"
26#include "efi-api.h"
27#include "efi-loader.h"
28#include "efivars.h"
29#include "env-file.h"
30#include "env-util.h"
31#include "errno-util.h"
32#include "escape.h"
33#include "event-util.h"
34#include "fd-util.h"
35#include "fileio.h"
36#include "format-util.h"
37#include "fs-util.h"
38#include "hashmap.h"
39#include "login-util.h"
40#include "logind-session.h"
41#include "logind.h"
42#include "logind-action.h"
43#include "logind-dbus.h"
44#include "logind-polkit.h"
45#include "logind-seat.h"
46#include "logind-seat-dbus.h"
47#include "logind-session-dbus.h"
48#include "logind-user.h"
49#include "logind-user-dbus.h"
50#include "logind-utmp.h"
51#include "mkdir-label.h"
52#include "os-util.h"
53#include "parse-util.h"
54#include "path-util.h"
55#include "process-util.h"
56#include "reboot-util.h"
57#include "serialize.h"
58#include "signal-util.h"
59#include "sleep-config.h"
60#include "stdio-util.h"
61#include "strv.h"
62#include "terminal-util.h"
63#include "tmpfile-util.h"
64#include "unit-def.h"
65#include "user-record.h"
66#include "user-util.h"
67#include "virt.h"
68#include "wall.h"
69
70/* As a random fun fact sysvinit had a 252 (256-(strlen(" \r\n")+1))
71 * character limit for the wall message.
72 * https://git.savannah.nongnu.org/cgit/sysvinit.git/tree/src/shutdown.c#n72
73 * There is no real technical need for that but doesn't make sense
74 * to store arbitrary amounts either. As we are not stingy here, we
75 * allow 4k.
76 */
77#define WALL_MESSAGE_MAX 4096U
78
79#define SHUTDOWN_SCHEDULE_FILE "/run/systemd/shutdown/scheduled"
80
81static void reset_scheduled_shutdown(Manager *m);
82
83static int get_sender_session(
84 Manager *m,
85 sd_bus_message *message,
86 bool consult_display,
87 sd_bus_error *error,
88 Session **ret) {
89
90 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
91 Session *session = NULL;
92 const char *name;
93 int r;
94
95 assert(m);
96
97 /* Acquire the sender's session. This first checks if the sending process is inside a session itself,
98 * and returns that. If not and 'consult_display' is true, this returns the display session of the
99 * owning user of the caller. */
100
101 r = sd_bus_query_sender_creds(message,
102 SD_BUS_CREDS_SESSION|SD_BUS_CREDS_AUGMENT|
103 (consult_display ? SD_BUS_CREDS_OWNER_UID : 0), &creds);
104 if (r < 0)
105 return r;
106
107 r = sd_bus_creds_get_session(creds, &name);
108 if (r < 0) {
109 if (r != -ENXIO)
110 return r;
111
112 if (consult_display) {
113 uid_t uid;
114
115 r = sd_bus_creds_get_owner_uid(creds, &uid);
116 if (r < 0) {
117 if (r != -ENXIO)
118 return r;
119 } else {
120 User *user;
121
122 user = hashmap_get(m->users, UID_TO_PTR(uid));
123 if (user)
124 session = user->display;
125 }
126 }
127 } else
128 session = hashmap_get(m->sessions, name);
129
130 if (!session)
131 return sd_bus_error_setf(error, BUS_ERROR_NO_SESSION_FOR_PID,
132 consult_display ?
133 "Caller does not belong to any known session and doesn't own any suitable session." :
134 "Caller does not belong to any known session.");
135
136 *ret = session;
137 return 0;
138}
139
140int manager_get_session_from_creds(
141 Manager *m,
142 sd_bus_message *message,
143 const char *name,
144 sd_bus_error *error,
145 Session **ret) {
146
147 Session *session;
148
149 assert(m);
150 assert(ret);
151
152 if (session_is_self(name)) /* the caller's own session */
153 return get_sender_session(m, message, false, error, ret);
154 if (session_is_auto(name)) /* The caller's own session if they have one, otherwise their user's display session */
155 return get_sender_session(m, message, true, error, ret);
156
157 session = hashmap_get(m->sessions, name);
158 if (!session)
159 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SESSION, "No session '%s' known", name);
160
161 *ret = session;
162 return 0;
163}
164
165static int get_sender_user(Manager *m, sd_bus_message *message, sd_bus_error *error, User **ret) {
166 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
167 uid_t uid;
168 User *user;
169 int r;
170
171 /* Note that we get the owner UID of the session, not the actual client UID here! */
172 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_OWNER_UID|SD_BUS_CREDS_AUGMENT, &creds);
173 if (r < 0)
174 return r;
175
176 r = sd_bus_creds_get_owner_uid(creds, &uid);
177 if (r < 0) {
178 if (r != -ENXIO)
179 return r;
180
181 user = NULL;
182 } else
183 user = hashmap_get(m->users, UID_TO_PTR(uid));
184
185 if (!user)
186 return sd_bus_error_setf(error, BUS_ERROR_NO_USER_FOR_PID,
187 "Caller does not belong to any logged in or lingering user");
188
189 *ret = user;
190 return 0;
191}
192
193int manager_get_user_from_creds(Manager *m, sd_bus_message *message, uid_t uid, sd_bus_error *error, User **ret) {
194 User *user;
195
196 assert(m);
197 assert(ret);
198
199 if (!uid_is_valid(uid))
200 return get_sender_user(m, message, error, ret);
201
202 user = hashmap_get(m->users, UID_TO_PTR(uid));
203 if (!user)
204 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_USER,
205 "User ID "UID_FMT" is not logged in or lingering", uid);
206
207 *ret = user;
208 return 0;
209}
210
211int manager_get_seat_from_creds(
212 Manager *m,
213 sd_bus_message *message,
214 const char *name,
215 sd_bus_error *error,
216 Seat **ret) {
217
218 Seat *seat;
219 int r;
220
221 assert(m);
222 assert(ret);
223
224 if (seat_is_self(name) || seat_is_auto(name)) {
225 Session *session;
226
227 /* Use these special seat names as session names */
228 r = manager_get_session_from_creds(m, message, name, error, &session);
229 if (r < 0)
230 return r;
231
232 seat = session->seat;
233 if (!seat)
234 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT, "Session '%s' has no seat.", session->id);
235 } else {
236 seat = hashmap_get(m->seats, name);
237 if (!seat)
238 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT, "No seat '%s' known", name);
239 }
240
241 *ret = seat;
242 return 0;
243}
244
245static int return_test_polkit(
246 sd_bus_message *message,
247 const char *action,
248 const char **details,
249 uid_t good_user,
250 sd_bus_error *e) {
251
252 const char *result;
253 bool challenge;
254 int r;
255
256 r = bus_test_polkit(message, action, details, good_user, &challenge, e);
257 if (r < 0)
258 return r;
259
260 if (r > 0)
261 result = "yes";
262 else if (challenge)
263 result = "challenge";
264 else
265 result = "no";
266
267 return sd_bus_reply_method_return(message, "s", result);
268}
269
270static int property_get_idle_hint(
271 sd_bus *bus,
272 const char *path,
273 const char *interface,
274 const char *property,
275 sd_bus_message *reply,
276 void *userdata,
277 sd_bus_error *error) {
278
279 Manager *m = ASSERT_PTR(userdata);
280
281 assert(bus);
282 assert(reply);
283
284 return sd_bus_message_append(reply, "b", manager_get_idle_hint(m, NULL) > 0);
285}
286
287static int property_get_idle_since_hint(
288 sd_bus *bus,
289 const char *path,
290 const char *interface,
291 const char *property,
292 sd_bus_message *reply,
293 void *userdata,
294 sd_bus_error *error) {
295
296 Manager *m = ASSERT_PTR(userdata);
297 dual_timestamp t = DUAL_TIMESTAMP_NULL;
298
299 assert(bus);
300 assert(reply);
301
302 manager_get_idle_hint(m, &t);
303
304 return sd_bus_message_append(reply, "t", streq(property, "IdleSinceHint") ? t.realtime : t.monotonic);
305}
306
307static int property_get_inhibited(
308 sd_bus *bus,
309 const char *path,
310 const char *interface,
311 const char *property,
312 sd_bus_message *reply,
313 void *userdata,
314 sd_bus_error *error) {
315
316 Manager *m = ASSERT_PTR(userdata);
317 InhibitWhat w;
318
319 assert(bus);
320 assert(reply);
321
322 if (streq(property, "BlockInhibited"))
323 w = manager_inhibit_what(m, INHIBIT_BLOCK);
324 else if (streq(property, "BlockWeakInhibited"))
325 w = manager_inhibit_what(m, INHIBIT_BLOCK_WEAK);
326 else if (streq(property, "DelayInhibited"))
327 w = manager_inhibit_what(m, INHIBIT_DELAY);
328 else
329 assert_not_reached();
330
331 return sd_bus_message_append(reply, "s", inhibit_what_to_string(w));
332}
333
334static int property_get_preparing(
335 sd_bus *bus,
336 const char *path,
337 const char *interface,
338 const char *property,
339 sd_bus_message *reply,
340 void *userdata,
341 sd_bus_error *error) {
342
343 Manager *m = ASSERT_PTR(userdata);
344 bool b = false;
345
346 assert(bus);
347 assert(reply);
348
349 if (m->delayed_action) {
350 if (streq(property, "PreparingForShutdown"))
351 b = m->delayed_action->inhibit_what & INHIBIT_SHUTDOWN;
352 else
353 b = m->delayed_action->inhibit_what & INHIBIT_SLEEP;
354 }
355
356 return sd_bus_message_append(reply, "b", b);
357}
358
359static int property_get_preparing_shutdown_with_metadata(
360 sd_bus *bus,
361 const char *path,
362 const char *interface,
363 const char *property,
364 sd_bus_message *reply,
365 void *userdata,
366 sd_bus_error *error) {
367
368 Manager *m = ASSERT_PTR(userdata);
369
370 assert(bus);
371 assert(reply);
372
373 if (!m->delayed_action || !(m->delayed_action->inhibit_what & INHIBIT_SHUTDOWN))
374 return sd_bus_message_append(reply, "a{sv}", 1, "preparing", "b", false);
375
376 return sd_bus_message_append(
377 reply,
378 "a{sv}",
379 2,
380 "preparing",
381 "b",
382 true,
383 "type",
384 "s",
385 handle_action_to_string(m->delayed_action->handle));
386}
387
388static int property_get_sleep_operations(
389 sd_bus *bus,
390 const char *path,
391 const char *interface,
392 const char *property,
393 sd_bus_message *reply,
394 void *userdata,
395 sd_bus_error *error) {
396
397 Manager *m = ASSERT_PTR(userdata);
398 _cleanup_strv_free_ char **actions = NULL;
399 int r;
400
401 assert(bus);
402 assert(reply);
403
404 r = handle_action_get_enabled_sleep_actions(m->handle_action_sleep_mask, &actions);
405 if (r < 0)
406 return r;
407
408 return sd_bus_message_append_strv(reply, actions);
409}
410
411static int property_get_scheduled_shutdown(
412 sd_bus *bus,
413 const char *path,
414 const char *interface,
415 const char *property,
416 sd_bus_message *reply,
417 void *userdata,
418 sd_bus_error *error) {
419
420 Manager *m = ASSERT_PTR(userdata);
421 int r;
422
423 assert(bus);
424 assert(reply);
425
426 r = sd_bus_message_open_container(reply, 'r', "st");
427 if (r < 0)
428 return r;
429
430 if (m->delayed_action) {
431 usec_t t = m->scheduled_shutdown_timeout; /* fall back to the schedule time on failure below */
432
433 if (m->inhibit_timeout_source) {
434 r = sd_event_source_get_time(m->inhibit_timeout_source, &t);
435 if (r < 0)
436 log_debug_errno(r, "Failed to get time of inhibit timeout event source, ignoring: %m");
437 }
438
439 r = sd_bus_message_append(
440 reply, "st",
441 handle_action_to_string(m->delayed_action->handle), t);
442 } else
443 r = sd_bus_message_append(
444 reply, "st",
445 handle_action_to_string(m->scheduled_shutdown_action),
446 m->scheduled_shutdown_timeout);
447 if (r < 0)
448 return r;
449
450 return sd_bus_message_close_container(reply);
451}
452
453static int property_get_maintenance_time(
454 sd_bus *bus,
455 const char *path,
456 const char *interface,
457 const char *property,
458 sd_bus_message *reply,
459 void *userdata,
460 sd_bus_error *error) {
461
462 Manager *m = ASSERT_PTR(userdata);
463 _cleanup_free_ char *s = NULL;
464 int r;
465
466 assert(bus);
467 assert(reply);
468
469 if (m->maintenance_time) {
470 r = calendar_spec_to_string(m->maintenance_time, &s);
471 if (r < 0)
472 return log_error_errno(r, "Failed to format calendar specification: %m");
473 }
474
475 return sd_bus_message_append(reply, "s", s);
476}
477
478static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_handle_action, handle_action, HandleAction);
479static BUS_DEFINE_PROPERTY_GET(property_get_docked, "b", Manager, manager_is_docked_or_external_displays);
480static BUS_DEFINE_PROPERTY_GET(property_get_lid_closed, "b", Manager, manager_is_lid_closed);
481static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_on_external_power, "b", manager_is_on_external_power());
482static BUS_DEFINE_PROPERTY_GET_GLOBAL(property_get_compat_user_tasks_max, "t", CGROUP_LIMIT_MAX);
483static BUS_DEFINE_PROPERTY_GET_REF(property_get_hashmap_size, "t", Hashmap *, (uint64_t) hashmap_size);
484
485static int method_get_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
486 _cleanup_free_ char *p = NULL;
487 Manager *m = ASSERT_PTR(userdata);
488 const char *name;
489 Session *session;
490 int r;
491
492 assert(message);
493
494 r = sd_bus_message_read(message, "s", &name);
495 if (r < 0)
496 return r;
497
498 r = manager_get_session_from_creds(m, message, name, error, &session);
499 if (r < 0)
500 return r;
501
502 p = session_bus_path(session);
503 if (!p)
504 return -ENOMEM;
505
506 return sd_bus_reply_method_return(message, "o", p);
507}
508
509/* Get login session of a process. This is not what you are looking for these days,
510 * as apps may instead belong to a user service unit. This includes terminal
511 * emulators and hence command-line apps. */
512static int method_get_session_by_pid(sd_bus_message *message, void *userdata, sd_bus_error *error) {
513 Manager *m = ASSERT_PTR(userdata);
514 _cleanup_free_ char *p = NULL;
515 Session *session = NULL;
516 pid_t pid;
517 int r;
518
519 assert(message);
520
521 assert_cc(sizeof(pid_t) == sizeof(uint32_t));
522
523 r = sd_bus_message_read(message, "u", &pid);
524 if (r < 0)
525 return r;
526 if (pid < 0)
527 return -EINVAL;
528
529 if (pid == 0) {
530 r = manager_get_session_from_creds(m, message, NULL, error, &session);
531 if (r < 0)
532 return r;
533 } else {
534 r = manager_get_session_by_pidref(m, &PIDREF_MAKE_FROM_PID(pid), &session);
535 if (r < 0)
536 return r;
537
538 if (!session)
539 return sd_bus_error_setf(error, BUS_ERROR_NO_SESSION_FOR_PID,
540 "PID "PID_FMT" does not belong to any known session", pid);
541 }
542
543 p = session_bus_path(session);
544 if (!p)
545 return -ENOMEM;
546
547 return sd_bus_reply_method_return(message, "o", p);
548}
549
550static int method_get_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
551 _cleanup_free_ char *p = NULL;
552 Manager *m = ASSERT_PTR(userdata);
553 uint32_t uid;
554 User *user;
555 int r;
556
557 assert(message);
558
559 r = sd_bus_message_read(message, "u", &uid);
560 if (r < 0)
561 return r;
562
563 r = manager_get_user_from_creds(m, message, uid, error, &user);
564 if (r < 0)
565 return r;
566
567 p = user_bus_path(user);
568 if (!p)
569 return -ENOMEM;
570
571 return sd_bus_reply_method_return(message, "o", p);
572}
573
574static int method_get_user_by_pid(sd_bus_message *message, void *userdata, sd_bus_error *error) {
575 _cleanup_free_ char *p = NULL;
576 Manager *m = ASSERT_PTR(userdata);
577 User *user = NULL;
578 pid_t pid;
579 int r;
580
581 assert(message);
582
583 assert_cc(sizeof(pid_t) == sizeof(uint32_t));
584
585 r = sd_bus_message_read(message, "u", &pid);
586 if (r < 0)
587 return r;
588 if (pid < 0)
589 return -EINVAL;
590
591 if (pid == 0) {
592 r = manager_get_user_from_creds(m, message, UID_INVALID, error, &user);
593 if (r < 0)
594 return r;
595 } else {
596 r = manager_get_user_by_pid(m, pid, &user);
597 if (r < 0)
598 return r;
599 if (!user)
600 return sd_bus_error_setf(error, BUS_ERROR_NO_USER_FOR_PID,
601 "PID "PID_FMT" does not belong to any logged in user or lingering user",
602 pid);
603 }
604
605 p = user_bus_path(user);
606 if (!p)
607 return -ENOMEM;
608
609 return sd_bus_reply_method_return(message, "o", p);
610}
611
612static int method_get_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
613 _cleanup_free_ char *p = NULL;
614 Manager *m = ASSERT_PTR(userdata);
615 const char *name;
616 Seat *seat;
617 int r;
618
619 assert(message);
620
621 r = sd_bus_message_read(message, "s", &name);
622 if (r < 0)
623 return r;
624
625 r = manager_get_seat_from_creds(m, message, name, error, &seat);
626 if (r < 0)
627 return r;
628
629 p = seat_bus_path(seat);
630 if (!p)
631 return -ENOMEM;
632
633 return sd_bus_reply_method_return(message, "o", p);
634}
635
636static int method_list_sessions(sd_bus_message *message, void *userdata, sd_bus_error *error) {
637 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
638 Manager *m = ASSERT_PTR(userdata);
639 Session *session;
640 int r;
641
642 assert(message);
643
644 r = sd_bus_message_new_method_return(message, &reply);
645 if (r < 0)
646 return r;
647
648 r = sd_bus_message_open_container(reply, 'a', "(susso)");
649 if (r < 0)
650 return r;
651
652 HASHMAP_FOREACH(session, m->sessions) {
653 _cleanup_free_ char *p = NULL;
654
655 p = session_bus_path(session);
656 if (!p)
657 return -ENOMEM;
658
659 r = sd_bus_message_append(reply, "(susso)",
660 session->id,
661 (uint32_t) session->user->user_record->uid,
662 session->user->user_record->user_name,
663 session->seat ? session->seat->id : "",
664 p);
665 if (r < 0)
666 return r;
667 }
668
669 r = sd_bus_message_close_container(reply);
670 if (r < 0)
671 return r;
672
673 return sd_bus_message_send(reply);
674}
675
676static int method_list_sessions_ex(sd_bus_message *message, void *userdata, sd_bus_error *error) {
677 Manager *m = ASSERT_PTR(userdata);
678 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
679 int r;
680
681 assert(message);
682
683 r = sd_bus_message_new_method_return(message, &reply);
684 if (r < 0)
685 return r;
686
687 r = sd_bus_message_open_container(reply, 'a', "(sussussbto)");
688 if (r < 0)
689 return r;
690
691 Session *s;
692 HASHMAP_FOREACH(s, m->sessions) {
693 _cleanup_free_ char *path = NULL;
694 dual_timestamp idle_ts;
695 bool idle;
696
697 assert(s->user);
698
699 path = session_bus_path(s);
700 if (!path)
701 return -ENOMEM;
702
703 r = session_get_idle_hint(s, &idle_ts);
704 if (r < 0)
705 return r;
706 idle = r > 0;
707
708 r = sd_bus_message_append(reply, "(sussussbto)",
709 s->id,
710 (uint32_t) s->user->user_record->uid,
711 s->user->user_record->user_name,
712 s->seat ? s->seat->id : "",
713 (uint32_t) s->leader.pid,
714 session_class_to_string(s->class),
715 s->tty,
716 idle,
717 idle_ts.monotonic,
718 path);
719 if (r < 0)
720 return r;
721 }
722
723 r = sd_bus_message_close_container(reply);
724 if (r < 0)
725 return r;
726
727 return sd_bus_message_send(reply);
728}
729
730static int method_list_users(sd_bus_message *message, void *userdata, sd_bus_error *error) {
731 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
732 Manager *m = ASSERT_PTR(userdata);
733 User *user;
734 int r;
735
736 assert(message);
737
738 r = sd_bus_message_new_method_return(message, &reply);
739 if (r < 0)
740 return r;
741
742 r = sd_bus_message_open_container(reply, 'a', "(uso)");
743 if (r < 0)
744 return r;
745
746 HASHMAP_FOREACH(user, m->users) {
747 _cleanup_free_ char *p = NULL;
748
749 p = user_bus_path(user);
750 if (!p)
751 return -ENOMEM;
752
753 r = sd_bus_message_append(reply, "(uso)",
754 (uint32_t) user->user_record->uid,
755 user->user_record->user_name,
756 p);
757 if (r < 0)
758 return r;
759 }
760
761 r = sd_bus_message_close_container(reply);
762 if (r < 0)
763 return r;
764
765 return sd_bus_message_send(reply);
766}
767
768static int method_list_seats(sd_bus_message *message, void *userdata, sd_bus_error *error) {
769 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
770 Manager *m = ASSERT_PTR(userdata);
771 Seat *seat;
772 int r;
773
774 assert(message);
775
776 r = sd_bus_message_new_method_return(message, &reply);
777 if (r < 0)
778 return r;
779
780 r = sd_bus_message_open_container(reply, 'a', "(so)");
781 if (r < 0)
782 return r;
783
784 HASHMAP_FOREACH(seat, m->seats) {
785 _cleanup_free_ char *p = NULL;
786
787 p = seat_bus_path(seat);
788 if (!p)
789 return -ENOMEM;
790
791 r = sd_bus_message_append(reply, "(so)", seat->id, p);
792 if (r < 0)
793 return r;
794 }
795
796 r = sd_bus_message_close_container(reply);
797 if (r < 0)
798 return r;
799
800 return sd_bus_message_send(reply);
801}
802
803static int method_list_inhibitors(sd_bus_message *message, void *userdata, sd_bus_error *error) {
804 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
805 Manager *m = ASSERT_PTR(userdata);
806 Inhibitor *inhibitor;
807 int r;
808
809 assert(message);
810
811 r = sd_bus_message_new_method_return(message, &reply);
812 if (r < 0)
813 return r;
814
815 r = sd_bus_message_open_container(reply, 'a', "(ssssuu)");
816 if (r < 0)
817 return r;
818
819 HASHMAP_FOREACH(inhibitor, m->inhibitors) {
820
821 r = sd_bus_message_append(reply, "(ssssuu)",
822 strempty(inhibit_what_to_string(inhibitor->what)),
823 strempty(inhibitor->who),
824 strempty(inhibitor->why),
825 strempty(inhibit_mode_to_string(inhibitor->mode)),
826 (uint32_t) inhibitor->uid,
827 (uint32_t) inhibitor->pid.pid);
828 if (r < 0)
829 return r;
830 }
831
832 r = sd_bus_message_close_container(reply);
833 if (r < 0)
834 return r;
835
836 return sd_bus_message_send(reply);
837}
838
839static int manager_choose_session_id(
840 Manager *m,
841 const PidRef *leader,
842 char **ret_id) {
843
844 int r;
845
846 assert(m);
847 assert(pidref_is_set(leader));
848 assert(ret_id);
849
850 /* Try to keep our session IDs and the audit session IDs in sync */
851 _cleanup_free_ char *id = NULL;
852 uint32_t audit_id = AUDIT_SESSION_INVALID;
853 r = audit_session_from_pid(leader, &audit_id);
854 if (r < 0) {
855 if (r != -ENODATA)
856 log_debug_errno(r, "Failed to read audit session ID of process " PID_FMT ", ignoring: %m", leader->pid);
857 } else {
858 if (asprintf(&id, "%"PRIu32, audit_id) < 0)
859 return -ENOMEM;
860
861 /* Wut? There's already a session by this name and we didn't find it above? Weird, then let's
862 * not trust the audit data and let's better register a new ID */
863 if (hashmap_contains(m->sessions, id)) {
864 log_warning("Existing logind session ID %s used by new audit session, ignoring.", id);
865 id = mfree(id);
866 }
867 }
868
869 if (!id)
870 do {
871 id = mfree(id);
872
873 if (asprintf(&id, "c%" PRIu64, ++m->session_counter) < 0)
874 return -ENOMEM;
875
876 } while (hashmap_contains(m->sessions, id));
877
878 /* The generated names should not clash with 'auto' or 'self' */
879 assert(!session_is_self(id));
880 assert(!session_is_auto(id));
881
882 *ret_id = TAKE_PTR(id);
883 return 0;
884}
885
886int manager_create_session(
887 Manager *m,
888 uid_t uid,
889 PidRef *leader, /* consumed */
890 const char *service,
891 SessionType type,
892 SessionClass class,
893 const char *desktop,
894 Seat *seat,
895 unsigned vtnr,
896 const char *tty,
897 const char *display,
898 bool remote,
899 const char *remote_user,
900 const char *remote_host,
901 Session **ret_session) {
902
903 bool mangle_class = false;
904 int r;
905
906 assert(m);
907 assert(uid_is_valid(uid));
908 assert(pidref_is_set(leader));
909 assert(ret_session);
910
911 /* Returns:
912 * -EBUSY → client is already in a session
913 * -EADDRNOTAVAIL → VT is already taken
914 * -EUSERS → limit of sessions reached
915 */
916
917 if (type == _SESSION_TYPE_INVALID) {
918 if (!isempty(display))
919 type = SESSION_X11;
920 else if (!isempty(tty))
921 type = SESSION_TTY;
922 else
923 type = SESSION_UNSPECIFIED;
924 }
925
926 if (class == _SESSION_CLASS_INVALID) {
927 if (type == SESSION_UNSPECIFIED)
928 class = SESSION_BACKGROUND;
929 else
930 class = SESSION_USER;
931
932 /* If we determined the class automatically, then let's later potentially change it to early
933 * or light flavours, once we learn the disposition of the user */
934 mangle_class = true;
935 }
936
937 /* Check if we are already in a logind session, and if so refuse. */
938 r = manager_get_session_by_pidref(m, leader, /* ret= */ NULL);
939 if (r < 0)
940 return log_debug_errno(
941 r,
942 "Failed to check if process " PID_FMT " is already in a session: %m",
943 leader->pid);
944 if (r > 0)
945 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "Client is already in a session.");
946
947 /* Old gdm and lightdm start the user-session on the same VT as the greeter session. But they destroy
948 * the greeter session after the user-session and want the user-session to take over the VT. We need
949 * to support this for backwards-compatibility, so make sure we allow new sessions on a VT that a
950 * greeter is running on. Furthermore, to allow re-logins, we have to allow a greeter to take over a
951 * used VT for the exact same reasons. */
952 if (class != SESSION_GREETER &&
953 vtnr > 0 &&
954 vtnr < MALLOC_ELEMENTSOF(m->seat0->positions) &&
955 m->seat0->positions[vtnr] &&
956 m->seat0->positions[vtnr]->class != SESSION_GREETER)
957 return log_debug_errno(SYNTHETIC_ERRNO(EADDRNOTAVAIL), "VT already occupied by a session.");
958
959 if (hashmap_size(m->sessions) >= m->sessions_max)
960 return log_debug_errno(SYNTHETIC_ERRNO(EUSERS), "Maximum number of sessions (%" PRIu64 ") reached, refusing further sessions.", m->sessions_max);
961
962 _cleanup_free_ char *id = NULL;
963 r = manager_choose_session_id(m, leader, &id);
964 if (r < 0)
965 return r;
966
967 /* If we are not watching utmp already, try again */
968 manager_reconnect_utmp(m);
969
970 User *user = NULL;
971 Session *session = NULL;
972
973 r = manager_add_user_by_uid(m, uid, &user);
974 if (r < 0)
975 goto fail;
976
977 /* If we picked the session class on our own, and the user is not a regular one, and the session is
978 * not a graphical one then do not pull in session manager by default. For root make a special
979 * exception: for TTY logins leave the service manager on, but relax the /run/nologin
980 * restrictions. */
981 if (mangle_class &&
982 IN_SET(user_record_disposition(user->user_record), USER_INTRINSIC, USER_SYSTEM, USER_DYNAMIC)) {
983
984 if (class == SESSION_USER) {
985 if (user_record_is_root(user->user_record))
986 class = SESSION_USER_EARLY;
987 else if (SESSION_TYPE_IS_GRAPHICAL(type))
988 class = SESSION_USER;
989 else
990 class = SESSION_USER_LIGHT;
991
992 } else if (class == SESSION_BACKGROUND)
993 class = SESSION_BACKGROUND_LIGHT;
994 }
995
996 r = manager_add_session(m, id, &session);
997 if (r < 0)
998 goto fail;
999
1000 session_set_user(session, user);
1001 r = session_set_leader_consume(session, TAKE_PIDREF(*leader));
1002 if (r < 0)
1003 goto fail;
1004
1005 session->original_type = session->type = type;
1006 session->remote = remote;
1007 session->vtnr = vtnr;
1008 session->class = class;
1009
1010 /* Once the first session that is of a pinning class shows up we'll change the GC mode for the user
1011 * from USER_GC_BY_ANY to USER_GC_BY_PIN, so that the user goes away once the last pinning session
1012 * goes away. Background: we want that user@.service – when started manually – remains around (which
1013 * itself is a non-pinning session), but gets stopped when the last pinning session goes away. */
1014
1015 if (SESSION_CLASS_PIN_USER(class))
1016 user->gc_mode = USER_GC_BY_PIN;
1017
1018 if (!isempty(tty)) {
1019 r = strdup_to(&session->tty, tty);
1020 if (r < 0)
1021 goto fail;
1022
1023 session->tty_validity = TTY_FROM_PAM;
1024 }
1025
1026 if (!isempty(display)) {
1027 r = strdup_to(&session->display, display);
1028 if (r < 0)
1029 goto fail;
1030 }
1031
1032 if (!isempty(remote_user)) {
1033 r = strdup_to(&session->remote_user, remote_user);
1034 if (r < 0)
1035 goto fail;
1036 }
1037
1038 if (!isempty(remote_host)) {
1039 r = strdup_to(&session->remote_host, remote_host);
1040 if (r < 0)
1041 goto fail;
1042 }
1043
1044 if (!isempty(service)) {
1045 r = strdup_to(&session->service, service);
1046 if (r < 0)
1047 goto fail;
1048 }
1049
1050 if (!isempty(desktop)) {
1051 r = strdup_to(&session->desktop, desktop);
1052 if (r < 0)
1053 goto fail;
1054 }
1055
1056 if (seat) {
1057 r = seat_attach_session(seat, session);
1058 if (r < 0)
1059 goto fail;
1060 }
1061
1062 *ret_session = session;
1063 return 0;
1064
1065fail:
1066 if (session)
1067 session_add_to_gc_queue(session);
1068
1069 if (user)
1070 user_add_to_gc_queue(user);
1071
1072 return r;
1073}
1074
1075static int manager_create_session_by_bus(
1076 Manager *m,
1077 sd_bus_message *message,
1078 sd_bus_error *error,
1079 uid_t uid,
1080 pid_t leader_pid,
1081 int leader_pidfd,
1082 const char *service,
1083 const char *type,
1084 const char *class,
1085 const char *desktop,
1086 const char *cseat,
1087 uint32_t vtnr,
1088 const char *tty,
1089 const char *display,
1090 int remote,
1091 const char *remote_user,
1092 const char *remote_host,
1093 uint64_t flags) {
1094
1095 int r;
1096
1097 assert(m);
1098 assert(message);
1099
1100 if (!uid_is_valid(uid))
1101 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid UID");
1102
1103 if (flags != 0)
1104 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Flags must be zero.");
1105
1106 _cleanup_(pidref_done) PidRef leader = PIDREF_NULL;
1107 if (leader_pidfd >= 0)
1108 r = pidref_set_pidfd(&leader, leader_pidfd);
1109 else if (leader_pid == 0)
1110 r = bus_query_sender_pidref(message, &leader);
1111 else {
1112 if (leader_pid < 0)
1113 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Leader PID is not valid");
1114
1115 r = pidref_set_pid(&leader, leader_pid);
1116 }
1117 if (r < 0)
1118 return r;
1119
1120 if (leader.pid == 1 || pidref_is_self(&leader))
1121 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid leader PID");
1122
1123 if (leader.fd < 0)
1124 return sd_bus_error_set_errnof(error, EUNATCH, "Leader PIDFD not available");
1125
1126 SessionType t;
1127 if (isempty(type))
1128 t = _SESSION_TYPE_INVALID;
1129 else {
1130 t = session_type_from_string(type);
1131 if (t < 0)
1132 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1133 "Invalid session type %s", type);
1134 }
1135
1136 SessionClass c;
1137 if (isempty(class))
1138 c = _SESSION_CLASS_INVALID;
1139 else {
1140 c = session_class_from_string(class);
1141 if (c < 0)
1142 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1143 "Invalid session class %s", class);
1144 if (c == SESSION_NONE)
1145 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1146 "Refusing session class %s", class);
1147 }
1148
1149 if (isempty(desktop))
1150 desktop = NULL;
1151 else {
1152 if (!string_is_safe(desktop))
1153 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1154 "Invalid desktop string %s", desktop);
1155 }
1156
1157 Seat *seat = NULL;
1158 if (isempty(cseat))
1159 seat = NULL;
1160 else {
1161 seat = hashmap_get(m->seats, cseat);
1162 if (!seat)
1163 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT,
1164 "No seat '%s' known", cseat);
1165 }
1166
1167 if (isempty(tty))
1168 tty = NULL;
1169 else if (tty_is_vc(tty)) {
1170 int v;
1171
1172 if (!seat)
1173 seat = m->seat0;
1174 else if (seat != m->seat0)
1175 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1176 "TTY %s is virtual console but seat %s is not seat0", tty, seat->id);
1177
1178 v = vtnr_from_tty(tty);
1179 if (v <= 0)
1180 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1181 "Cannot determine VT number from virtual console TTY %s", tty);
1182
1183 if (vtnr == 0)
1184 vtnr = (uint32_t) v;
1185 else if (vtnr != (uint32_t) v)
1186 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1187 "Specified TTY and VT number do not match");
1188
1189 } else if (tty_is_console(tty)) {
1190
1191 if (!seat)
1192 seat = m->seat0;
1193 else if (seat != m->seat0)
1194 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1195 "Console TTY specified but seat is not seat0");
1196
1197 if (vtnr != 0)
1198 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1199 "Console TTY specified but VT number is not 0");
1200 }
1201
1202 if (seat) {
1203 if (seat_has_vts(seat)) {
1204 if (!vtnr_is_valid(vtnr))
1205 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1206 "VT number out of range");
1207 } else {
1208 if (vtnr != 0)
1209 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
1210 "Seat has no VTs but VT number not 0");
1211 }
1212 }
1213
1214 Session *session;
1215 r = manager_create_session(
1216 m,
1217 uid,
1218 &leader,
1219 service,
1220 t,
1221 c,
1222 desktop,
1223 seat,
1224 vtnr,
1225 tty,
1226 display,
1227 remote,
1228 remote_user,
1229 remote_host,
1230 &session);
1231 if (r == -EBUSY)
1232 return sd_bus_error_setf(error, BUS_ERROR_SESSION_BUSY, "Already running in a session or user slice");
1233 if (r == -EADDRNOTAVAIL)
1234 return sd_bus_error_set(error, BUS_ERROR_SESSION_BUSY, "Virtual terminal already occupied by a session");
1235 if (r == -EUSERS)
1236 return sd_bus_error_setf(error, SD_BUS_ERROR_LIMITS_EXCEEDED, "Maximum number of sessions (%" PRIu64 ") reached, refusing further sessions.", m->sessions_max);
1237 if (r < 0)
1238 return r;
1239
1240 r = sd_bus_message_enter_container(message, 'a', "(sv)");
1241 if (r < 0)
1242 goto fail;
1243 r = session_start(session, message, error);
1244 if (r < 0)
1245 goto fail;
1246 r = sd_bus_message_exit_container(message);
1247 if (r < 0)
1248 goto fail;
1249
1250 session->create_message = sd_bus_message_ref(message);
1251
1252 /* Now call into session_send_create_reply(), which will reply to this method call for us. Or it
1253 * won't – in case we just spawned a session scope and/or user service manager, and they aren't ready
1254 * yet. We'll call session_create_reply() again once the session scope or the user service manager is
1255 * ready, where the function will check again if a reply is then ready to be sent, and then do so if
1256 * all is complete - or wait again. */
1257 r = session_send_create_reply(session, /* error= */ NULL);
1258 if (r < 0)
1259 goto fail;
1260
1261 return 1;
1262
1263fail:
1264 if (session)
1265 session_add_to_gc_queue(session);
1266
1267 return r;
1268}
1269
1270static int method_create_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1271 const char *service, *type, *class, *cseat, *tty, *display, *remote_user, *remote_host, *desktop;
1272 pid_t leader_pid;
1273 uint32_t vtnr;
1274 uid_t uid;
1275 int remote, r;
1276
1277 assert(message);
1278
1279 assert_cc(sizeof(pid_t) == sizeof(uint32_t));
1280 assert_cc(sizeof(uid_t) == sizeof(uint32_t));
1281
1282 r = sd_bus_message_read(
1283 message,
1284 "uusssssussbss",
1285 &uid,
1286 &leader_pid,
1287 &service,
1288 &type,
1289 &class,
1290 &desktop,
1291 &cseat,
1292 &vtnr,
1293 &tty,
1294 &display,
1295 &remote,
1296 &remote_user,
1297 &remote_host);
1298 if (r < 0)
1299 return r;
1300
1301 return manager_create_session_by_bus(
1302 userdata,
1303 message,
1304 error,
1305 uid,
1306 leader_pid,
1307 /* leader_pidfd = */ -EBADF,
1308 service,
1309 type,
1310 class,
1311 desktop,
1312 cseat,
1313 vtnr,
1314 tty,
1315 display,
1316 remote,
1317 remote_user,
1318 remote_host,
1319 /* flags = */ 0);
1320}
1321
1322static int method_create_session_pidfd(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1323 const char *service, *type, *class, *cseat, *tty, *display, *remote_user, *remote_host, *desktop;
1324 uint64_t flags;
1325 uint32_t vtnr;
1326 uid_t uid;
1327 int leader_fd = -EBADF, remote, r;
1328
1329 r = sd_bus_message_read(
1330 message,
1331 "uhsssssussbsst",
1332 &uid,
1333 &leader_fd,
1334 &service,
1335 &type,
1336 &class,
1337 &desktop,
1338 &cseat,
1339 &vtnr,
1340 &tty,
1341 &display,
1342 &remote,
1343 &remote_user,
1344 &remote_host,
1345 &flags);
1346 if (r < 0)
1347 return r;
1348
1349 return manager_create_session_by_bus(
1350 userdata,
1351 message,
1352 error,
1353 uid,
1354 /* leader_pid = */ 0,
1355 leader_fd,
1356 service,
1357 type,
1358 class,
1359 desktop,
1360 cseat,
1361 vtnr,
1362 tty,
1363 display,
1364 remote,
1365 remote_user,
1366 remote_host,
1367 flags);
1368}
1369
1370static int method_release_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1371 Manager *m = ASSERT_PTR(userdata);
1372 Session *session, *sender_session;
1373 const char *name;
1374 int r;
1375
1376 assert(message);
1377
1378 r = sd_bus_message_read(message, "s", &name);
1379 if (r < 0)
1380 return r;
1381
1382 r = manager_get_session_from_creds(m, message, name, error, &session);
1383 if (r < 0)
1384 return r;
1385
1386 r = get_sender_session(m, message, /* consult_display= */ false, error, &sender_session);
1387 if (r < 0)
1388 return r;
1389
1390 if (session != sender_session)
1391 return sd_bus_error_set(error, SD_BUS_ERROR_ACCESS_DENIED,
1392 "Refused to release session, since it doesn't match the one of the client");
1393
1394 r = session_release(session);
1395 if (r < 0)
1396 return r;
1397
1398 return sd_bus_reply_method_return(message, NULL);
1399}
1400
1401static int method_activate_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1402 Manager *m = ASSERT_PTR(userdata);
1403 Session *session;
1404 const char *name;
1405 int r;
1406
1407 assert(message);
1408
1409 r = sd_bus_message_read(message, "s", &name);
1410 if (r < 0)
1411 return r;
1412
1413 r = manager_get_session_from_creds(m, message, name, error, &session);
1414 if (r < 0)
1415 return r;
1416
1417 /* PolicyKit is done by bus_session_method_activate() */
1418
1419 return bus_session_method_activate(message, session, error);
1420}
1421
1422static int method_activate_session_on_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1423 const char *session_name, *seat_name;
1424 Manager *m = ASSERT_PTR(userdata);
1425 Session *session;
1426 Seat *seat;
1427 int r;
1428
1429 assert(message);
1430
1431 /* Same as ActivateSession() but refuses to work if the seat doesn't match */
1432
1433 r = sd_bus_message_read(message, "ss", &session_name, &seat_name);
1434 if (r < 0)
1435 return r;
1436
1437 r = manager_get_session_from_creds(m, message, session_name, error, &session);
1438 if (r < 0)
1439 return r;
1440
1441 r = manager_get_seat_from_creds(m, message, seat_name, error, &seat);
1442 if (r < 0)
1443 return r;
1444
1445 if (session->seat != seat)
1446 return sd_bus_error_setf(error, BUS_ERROR_SESSION_NOT_ON_SEAT,
1447 "Session %s not on seat %s", session_name, seat_name);
1448
1449 r = check_polkit_chvt(message, m, error);
1450 if (r < 0)
1451 return r;
1452 if (r == 0)
1453 return 1; /* Will call us back */
1454
1455 r = session_activate(session);
1456 if (r < 0)
1457 return r;
1458
1459 return sd_bus_reply_method_return(message, NULL);
1460}
1461
1462static int method_lock_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1463 Manager *m = ASSERT_PTR(userdata);
1464 Session *session;
1465 const char *name;
1466 int r;
1467
1468 assert(message);
1469
1470 r = sd_bus_message_read(message, "s", &name);
1471 if (r < 0)
1472 return r;
1473
1474 r = manager_get_session_from_creds(m, message, name, error, &session);
1475 if (r < 0)
1476 return r;
1477
1478 return bus_session_method_lock(message, session, error);
1479}
1480
1481static int method_lock_sessions(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1482 Manager *m = ASSERT_PTR(userdata);
1483 int r;
1484
1485 assert(message);
1486
1487 r = bus_verify_polkit_async(
1488 message,
1489 "org.freedesktop.login1.lock-sessions",
1490 /* details= */ NULL,
1491 &m->polkit_registry,
1492 error);
1493 if (r < 0)
1494 return r;
1495 if (r == 0)
1496 return 1; /* Will call us back */
1497
1498 r = session_send_lock_all(m, streq(sd_bus_message_get_member(message), "LockSessions"));
1499 if (r < 0)
1500 return r;
1501
1502 return sd_bus_reply_method_return(message, NULL);
1503}
1504
1505static int method_kill_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1506 const char *name;
1507 Manager *m = ASSERT_PTR(userdata);
1508 Session *session;
1509 int r;
1510
1511 assert(message);
1512
1513 r = sd_bus_message_read(message, "s", &name);
1514 if (r < 0)
1515 return r;
1516
1517 r = manager_get_session_from_creds(m, message, name, error, &session);
1518 if (r < 0)
1519 return r;
1520
1521 return bus_session_method_kill(message, session, error);
1522}
1523
1524static int method_kill_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1525 Manager *m = ASSERT_PTR(userdata);
1526 uint32_t uid;
1527 User *user;
1528 int r;
1529
1530 assert(message);
1531
1532 r = sd_bus_message_read(message, "u", &uid);
1533 if (r < 0)
1534 return r;
1535
1536 r = manager_get_user_from_creds(m, message, uid, error, &user);
1537 if (r < 0)
1538 return r;
1539
1540 return bus_user_method_kill(message, user, error);
1541}
1542
1543static int method_terminate_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1544 Manager *m = ASSERT_PTR(userdata);
1545 const char *name;
1546 Session *session;
1547 int r;
1548
1549 assert(message);
1550
1551 r = sd_bus_message_read(message, "s", &name);
1552 if (r < 0)
1553 return r;
1554
1555 r = manager_get_session_from_creds(m, message, name, error, &session);
1556 if (r < 0)
1557 return r;
1558
1559 return bus_session_method_terminate(message, session, error);
1560}
1561
1562static int method_terminate_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1563 Manager *m = ASSERT_PTR(userdata);
1564 uint32_t uid;
1565 User *user;
1566 int r;
1567
1568 assert(message);
1569
1570 r = sd_bus_message_read(message, "u", &uid);
1571 if (r < 0)
1572 return r;
1573
1574 r = manager_get_user_from_creds(m, message, uid, error, &user);
1575 if (r < 0)
1576 return r;
1577
1578 return bus_user_method_terminate(message, user, error);
1579}
1580
1581static int method_terminate_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1582 Manager *m = ASSERT_PTR(userdata);
1583 const char *name;
1584 Seat *seat;
1585 int r;
1586
1587 assert(message);
1588
1589 r = sd_bus_message_read(message, "s", &name);
1590 if (r < 0)
1591 return r;
1592
1593 r = manager_get_seat_from_creds(m, message, name, error, &seat);
1594 if (r < 0)
1595 return r;
1596
1597 return bus_seat_method_terminate(message, seat, error);
1598}
1599
1600static int method_set_user_linger(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1601 Manager *m = ASSERT_PTR(userdata);
1602 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
1603 uint32_t uid, auth_uid;
1604 int r, enable, interactive;
1605
1606 assert(message);
1607
1608 r = sd_bus_message_read(message, "ubb", &uid, &enable, &interactive);
1609 if (r < 0)
1610 return r;
1611
1612 r = sd_bus_query_sender_creds(message,
1613 SD_BUS_CREDS_EUID|SD_BUS_CREDS_OWNER_UID|SD_BUS_CREDS_AUGMENT,
1614 &creds);
1615 if (r < 0)
1616 return r;
1617
1618 if (!uid_is_valid(uid)) {
1619 /* Note that we get the owner UID of the session or user unit, not the actual client UID here! */
1620 r = sd_bus_creds_get_owner_uid(creds, &uid);
1621 if (r < 0)
1622 return r;
1623 }
1624
1625 /* owner_uid is racy, so for authorization we must use euid */
1626 r = sd_bus_creds_get_euid(creds, &auth_uid);
1627 if (r < 0)
1628 return r;
1629
1630 _cleanup_free_ struct passwd *pw = NULL;
1631
1632 r = getpwuid_malloc(uid, &pw);
1633 if (r < 0)
1634 return r;
1635
1636 r = bus_verify_polkit_async_full(
1637 message,
1638 uid == auth_uid ? "org.freedesktop.login1.set-self-linger" :
1639 "org.freedesktop.login1.set-user-linger",
1640 /* details= */ NULL,
1641 /* good_user= */ UID_INVALID,
1642 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
1643 &m->polkit_registry,
1644 error);
1645 if (r < 0)
1646 return r;
1647 if (r == 0)
1648 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1649
1650 (void) mkdir_p_label("/var/lib/systemd", 0755);
1651 r = mkdir_safe_label("/var/lib/systemd/linger", 0755, 0, 0, MKDIR_WARN_MODE);
1652 if (r < 0)
1653 return r;
1654
1655 _cleanup_free_ char *escaped = NULL;
1656 const char *path;
1657 User *u;
1658
1659 escaped = cescape(pw->pw_name);
1660 if (!escaped)
1661 return -ENOMEM;
1662
1663 path = strjoina("/var/lib/systemd/linger/", escaped);
1664
1665 if (enable) {
1666 r = touch(path);
1667 if (r < 0)
1668 return r;
1669
1670 if (manager_add_user_by_uid(m, uid, &u) >= 0) {
1671 r = user_start(u);
1672 if (r < 0) {
1673 user_add_to_gc_queue(u);
1674 return r;
1675 }
1676 }
1677
1678 } else {
1679 r = unlink(path);
1680 if (r < 0 && errno != ENOENT)
1681 return -errno;
1682
1683 u = hashmap_get(m->users, UID_TO_PTR(uid));
1684 if (u) {
1685 /* Make sure that disabling lingering will terminate the user tracking if no sessions pin it. */
1686 u->gc_mode = USER_GC_BY_PIN;
1687 user_add_to_gc_queue(u);
1688 }
1689 }
1690
1691 return sd_bus_reply_method_return(message, NULL);
1692}
1693
1694static int trigger_device(Manager *m, sd_device *parent) {
1695 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
1696 int r;
1697
1698 assert(m);
1699
1700 r = sd_device_enumerator_new(&e);
1701 if (r < 0)
1702 return r;
1703
1704 r = sd_device_enumerator_allow_uninitialized(e);
1705 if (r < 0)
1706 return r;
1707
1708 if (parent) {
1709 r = sd_device_enumerator_add_match_parent(e, parent);
1710 if (r < 0)
1711 return r;
1712 }
1713
1714 FOREACH_DEVICE(e, d) {
1715 r = sd_device_trigger(d, SD_DEVICE_CHANGE);
1716 if (r < 0)
1717 log_device_debug_errno(d, r, "Failed to trigger device, ignoring: %m");
1718 }
1719
1720 return 0;
1721}
1722
1723static int attach_device(Manager *m, const char *seat, const char *sysfs, sd_bus_error *error) {
1724 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
1725 _cleanup_free_ char *file = NULL;
1726 const char *id_for_seat;
1727 int r;
1728
1729 assert(m);
1730 assert(seat);
1731 assert(sysfs);
1732
1733 r = sd_device_new_from_syspath(&d, sysfs);
1734 if (r < 0)
1735 return sd_bus_error_set_errnof(error, r, "Failed to open device '%s': %m", sysfs);
1736
1737 if (sd_device_has_current_tag(d, "seat") <= 0)
1738 return sd_bus_error_set_errnof(error, ENODEV, "Device '%s' lacks 'seat' udev tag.", sysfs);
1739
1740 if (sd_device_get_property_value(d, "ID_FOR_SEAT", &id_for_seat) < 0)
1741 return sd_bus_error_set_errnof(error, ENODEV, "Device '%s' lacks 'ID_FOR_SEAT' udev property.", sysfs);
1742
1743 if (asprintf(&file, "/etc/udev/rules.d/72-seat-%s.rules", id_for_seat) < 0)
1744 return -ENOMEM;
1745
1746 r = write_string_filef(
1747 file,
1748 WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755|WRITE_STRING_FILE_LABEL,
1749 "TAG==\"seat\", ENV{ID_FOR_SEAT}==\"%s\", ENV{ID_SEAT}=\"%s\"", id_for_seat, seat);
1750 if (r < 0)
1751 return r;
1752
1753 return trigger_device(m, d);
1754}
1755
1756static int flush_devices(Manager *m) {
1757 _cleanup_closedir_ DIR *d = NULL;
1758
1759 assert(m);
1760
1761 d = opendir("/etc/udev/rules.d");
1762 if (!d) {
1763 if (errno != ENOENT)
1764 log_warning_errno(errno, "Failed to open %s: %m", "/etc/udev/rules.d");
1765 } else
1766 FOREACH_DIRENT_ALL(de, d, break) {
1767 if (!dirent_is_file(de))
1768 continue;
1769
1770 if (!startswith(de->d_name, "72-seat-"))
1771 continue;
1772
1773 if (!endswith(de->d_name, ".rules"))
1774 continue;
1775
1776 if (unlinkat(dirfd(d), de->d_name, 0) < 0)
1777 log_warning_errno(errno, "Failed to unlink %s: %m", de->d_name);
1778 }
1779
1780 return trigger_device(m, NULL);
1781}
1782
1783static int method_attach_device(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1784 const char *sysfs, *seat;
1785 Manager *m = ASSERT_PTR(userdata);
1786 int interactive, r;
1787
1788 assert(message);
1789
1790 r = sd_bus_message_read(message, "ssb", &seat, &sysfs, &interactive);
1791 if (r < 0)
1792 return r;
1793
1794 if (!path_is_normalized(sysfs))
1795 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not normalized", sysfs);
1796 if (!path_startswith(sysfs, "/sys"))
1797 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not in /sys", sysfs);
1798
1799 if (seat_is_self(seat) || seat_is_auto(seat)) {
1800 Seat *found;
1801
1802 r = manager_get_seat_from_creds(m, message, seat, error, &found);
1803 if (r < 0)
1804 return r;
1805
1806 seat = found->id;
1807
1808 } else if (!seat_name_is_valid(seat)) /* Note that a seat does not have to exist yet for this operation to succeed */
1809 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Seat name %s is not valid", seat);
1810
1811 r = bus_verify_polkit_async_full(
1812 message,
1813 "org.freedesktop.login1.attach-device",
1814 /* details= */ NULL,
1815 /* good_user= */ UID_INVALID,
1816 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
1817 &m->polkit_registry,
1818 error);
1819 if (r < 0)
1820 return r;
1821 if (r == 0)
1822 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1823
1824 r = attach_device(m, seat, sysfs, error);
1825 if (r < 0)
1826 return r;
1827
1828 return sd_bus_reply_method_return(message, NULL);
1829}
1830
1831static int method_flush_devices(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1832 Manager *m = ASSERT_PTR(userdata);
1833 int interactive, r;
1834
1835 assert(message);
1836
1837 r = sd_bus_message_read(message, "b", &interactive);
1838 if (r < 0)
1839 return r;
1840
1841 r = bus_verify_polkit_async_full(
1842 message,
1843 "org.freedesktop.login1.flush-devices",
1844 /* details= */ NULL,
1845 /* good_user= */ UID_INVALID,
1846 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
1847 &m->polkit_registry,
1848 error);
1849 if (r < 0)
1850 return r;
1851 if (r == 0)
1852 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1853
1854 r = flush_devices(m);
1855 if (r < 0)
1856 return r;
1857
1858 return sd_bus_reply_method_return(message, NULL);
1859}
1860
1861static int have_multiple_sessions(
1862 Manager *m,
1863 uid_t uid) {
1864
1865 Session *session;
1866
1867 assert(m);
1868
1869 /* Check for other users' sessions. Greeter sessions do not
1870 * count, and non-login sessions do not count either. */
1871 HASHMAP_FOREACH(session, m->sessions)
1872 if (SESSION_CLASS_IS_INHIBITOR_LIKE(session->class) &&
1873 session->user->user_record->uid != uid)
1874 return true;
1875
1876 return false;
1877}
1878
1879static int bus_manager_log_shutdown(
1880 Manager *m,
1881 const HandleActionData *a) {
1882 assert(m);
1883 assert(a);
1884
1885 const char *message = a->message ?: "System is shutting down";
1886 const char *log_verb = a->log_verb ? strjoina("SHUTDOWN=", a->log_verb) : NULL;
1887
1888 return log_struct(LOG_NOTICE,
1889 LOG_ITEM("MESSAGE_ID=%s", a->message_id ?: SD_MESSAGE_SHUTDOWN_STR),
1890 LOG_MESSAGE("%s%s%s%s.",
1891 message,
1892 m->wall_message ? " (" : "",
1893 strempty(m->wall_message),
1894 m->wall_message ? ")" : ""),
1895 log_verb);
1896}
1897
1898static int lid_switch_ignore_handler(sd_event_source *e, uint64_t usec, void *userdata) {
1899 Manager *m = ASSERT_PTR(userdata);
1900
1901 assert(e);
1902
1903 m->lid_switch_ignore_event_source = sd_event_source_unref(m->lid_switch_ignore_event_source);
1904 return 0;
1905}
1906
1907int manager_set_lid_switch_ignore(Manager *m, usec_t until) {
1908 int r;
1909
1910 assert(m);
1911
1912 if (until <= now(CLOCK_MONOTONIC))
1913 return 0;
1914
1915 /* We want to ignore the lid switch for a while after each
1916 * suspend, and after boot-up. Hence let's install a timer for
1917 * this. As long as the event source exists we ignore the lid
1918 * switch. */
1919
1920 if (m->lid_switch_ignore_event_source) {
1921 usec_t u;
1922
1923 r = sd_event_source_get_time(m->lid_switch_ignore_event_source, &u);
1924 if (r < 0)
1925 return r;
1926
1927 if (until <= u)
1928 return 0;
1929
1930 r = sd_event_source_set_time(m->lid_switch_ignore_event_source, until);
1931 } else
1932 r = sd_event_add_time(
1933 m->event,
1934 &m->lid_switch_ignore_event_source,
1935 CLOCK_MONOTONIC,
1936 until, 0,
1937 lid_switch_ignore_handler, m);
1938
1939 return r;
1940}
1941
1942static int send_prepare_for(Manager *m, const HandleActionData *a, bool _active) {
1943 int k = 0, r, active = _active;
1944
1945 assert(m);
1946 assert(a);
1947 assert(IN_SET(a->inhibit_what, INHIBIT_SHUTDOWN, INHIBIT_SLEEP));
1948
1949 /* We need to send both old and new signal for backward compatibility. The newer one allows clients
1950 * to know which type of reboot is going to happen, as they might be doing different actions (e.g.:
1951 * on soft-reboot), and it is sent first, so that clients know that if they receive the old one
1952 * first then they don't have to wait for the new one, as it means it's not supported. So, do not
1953 * change the order here, as it is an API. */
1954 if (a->inhibit_what == INHIBIT_SHUTDOWN) {
1955 k = sd_bus_emit_signal(m->bus,
1956 "/org/freedesktop/login1",
1957 "org.freedesktop.login1.Manager",
1958 "PrepareForShutdownWithMetadata",
1959 "ba{sv}",
1960 active,
1961 1,
1962 "type",
1963 "s",
1964 handle_action_to_string(a->handle));
1965 if (k < 0)
1966 log_debug_errno(k, "Failed to emit PrepareForShutdownWithMetadata(): %m");
1967 }
1968
1969 r = sd_bus_emit_signal(m->bus,
1970 "/org/freedesktop/login1",
1971 "org.freedesktop.login1.Manager",
1972 a->inhibit_what == INHIBIT_SHUTDOWN ? "PrepareForShutdown" : "PrepareForSleep",
1973 "b",
1974 active);
1975 if (r < 0)
1976 log_debug_errno(r, "Failed to emit PrepareForShutdown(): %m");
1977
1978 return RET_GATHER(k, r);
1979}
1980
1981static int strdup_job(sd_bus_message *reply, char **ret) {
1982 const char *j;
1983 char *job;
1984 int r;
1985
1986 assert(reply);
1987 assert(ret);
1988
1989 r = sd_bus_message_read_basic(reply, 'o', &j);
1990 if (r < 0)
1991 return r;
1992
1993 job = strdup(j);
1994 if (!job)
1995 return -ENOMEM;
1996
1997 *ret = job;
1998 return 0;
1999}
2000
2001static int execute_shutdown_or_sleep(
2002 Manager *m,
2003 const HandleActionData *a,
2004 sd_bus_error *error) {
2005
2006 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2007 int r;
2008
2009 assert(m);
2010 assert(!m->action_job);
2011 assert(a);
2012
2013 if (a->inhibit_what == INHIBIT_SHUTDOWN)
2014 bus_manager_log_shutdown(m, a);
2015
2016 r = bus_call_method(
2017 m->bus,
2018 bus_systemd_mgr,
2019 "StartUnit",
2020 error,
2021 &reply,
2022 "ss", a->target, "replace-irreversibly");
2023 if (r < 0)
2024 goto fail;
2025
2026 r = strdup_job(reply, &m->action_job);
2027 if (r < 0)
2028 goto fail;
2029
2030 /* Save the action to prevent another request of shutdown or friends before the current action being
2031 * finished. See method_do_shutdown_or_sleep(). This is also used in match_job_removed() to log what
2032 * kind of action is finished. */
2033 m->delayed_action = a;
2034
2035 /* Make sure the lid switch is ignored for a while. */
2036 manager_set_lid_switch_ignore(m, usec_add(now(CLOCK_MONOTONIC), m->holdoff_timeout_usec));
2037
2038 return 0;
2039
2040fail:
2041 /* Tell people that they now may take a lock again. */
2042 (void) send_prepare_for(m, a, false);
2043
2044 return r;
2045}
2046
2047int manager_dispatch_delayed(Manager *manager, bool timeout) {
2048 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2049 Inhibitor *offending = NULL;
2050 int r;
2051
2052 assert(manager);
2053
2054 if (!manager->delayed_action || manager->action_job)
2055 return 0;
2056
2057 if (manager_is_inhibited(
2058 manager,
2059 manager->delayed_action->inhibit_what,
2060 /* since= */ NULL,
2061 MANAGER_IS_INHIBITED_CHECK_DELAY,
2062 UID_INVALID,
2063 &offending)) {
2064 if (!timeout)
2065 return 0;
2066
2067 _cleanup_free_ char *comm = NULL, *u = NULL;
2068 (void) pidref_get_comm(&offending->pid, &comm);
2069 u = uid_to_name(offending->uid);
2070
2071 log_notice("Delay lock is active (UID "UID_FMT"/%s, PID "PID_FMT"/%s) but inhibitor timeout is reached.",
2072 offending->uid, strna(u),
2073 offending->pid.pid, strna(comm));
2074 }
2075
2076 /* Actually do the operation */
2077 r = execute_shutdown_or_sleep(manager, manager->delayed_action, &error);
2078 if (r < 0) {
2079 log_warning("Error during inhibitor-delayed operation (already returned success to client): %s",
2080 bus_error_message(&error, r));
2081
2082 manager->delayed_action = NULL;
2083 }
2084
2085 return 1; /* We did some work. */
2086}
2087
2088static int manager_inhibit_timeout_handler(
2089 sd_event_source *s,
2090 uint64_t usec,
2091 void *userdata) {
2092
2093 Manager *manager = ASSERT_PTR(userdata);
2094
2095 assert(manager->inhibit_timeout_source == s);
2096
2097 return manager_dispatch_delayed(manager, true);
2098}
2099
2100static int delay_shutdown_or_sleep(
2101 Manager *m,
2102 const HandleActionData *a) {
2103
2104 int r;
2105
2106 assert(m);
2107 assert(a);
2108
2109 r = event_reset_time_relative(
2110 m->event, &m->inhibit_timeout_source,
2111 CLOCK_MONOTONIC, m->inhibit_delay_max, /* accuracy = */ 0,
2112 manager_inhibit_timeout_handler, m,
2113 /* priority = */ 0, "inhibit-timeout", /* force_reset = */ true);
2114 if (r < 0)
2115 return log_error_errno(r, "Failed to reset timer event source for inhibit timeout: %m");
2116
2117 m->delayed_action = a;
2118
2119 return 0;
2120}
2121
2122static void cancel_delayed_action(Manager *m) {
2123 assert(m);
2124
2125 (void) sd_event_source_set_enabled(m->inhibit_timeout_source, SD_EVENT_OFF);
2126
2127 /* When m->action_job is NULL, the delayed action has not been triggered yet. Let's clear it to
2128 * accept later shutdown and friends.
2129 *
2130 * When m->action_job is non-NULL, the delayed action has been already triggered, and now we are
2131 * waiting for the job being finished. In match_job_removed(), the triggered action will be used.
2132 * Hence, do not clear it. */
2133 if (!m->action_job)
2134 m->delayed_action = NULL;
2135}
2136
2137int bus_manager_shutdown_or_sleep_now_or_later(
2138 Manager *m,
2139 const HandleActionData *a,
2140 sd_bus_error *error) {
2141
2142 _cleanup_free_ char *load_state = NULL;
2143 bool delayed;
2144 int r;
2145
2146 assert(m);
2147 assert(a);
2148 assert(!m->action_job);
2149
2150 r = unit_load_state(m->bus, a->target, &load_state);
2151 if (r < 0)
2152 return r;
2153
2154 if (!streq(load_state, "loaded"))
2155 return log_notice_errno(SYNTHETIC_ERRNO(EACCES),
2156 "Unit %s is %s, refusing operation.",
2157 a->target, load_state);
2158
2159 /* Tell everybody to prepare for shutdown/sleep */
2160 (void) send_prepare_for(m, a, true);
2161
2162 delayed =
2163 m->inhibit_delay_max > 0 &&
2164 manager_is_inhibited(m, a->inhibit_what, NULL, MANAGER_IS_INHIBITED_CHECK_DELAY, UID_INVALID, NULL);
2165
2166 if (delayed)
2167 /* Shutdown is delayed, keep in mind what we
2168 * want to do, and start a timeout */
2169 r = delay_shutdown_or_sleep(m, a);
2170 else
2171 /* Shutdown is not delayed, execute it
2172 * immediately */
2173 r = execute_shutdown_or_sleep(m, a, error);
2174
2175 return r;
2176}
2177
2178static int verify_shutdown_creds(
2179 Manager *m,
2180 sd_bus_message *message,
2181 const HandleActionData *a,
2182 uint64_t flags,
2183 sd_bus_error *error) {
2184
2185 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
2186 bool multiple_sessions, blocked, interactive;
2187 _unused_ bool error_or_denial = false;
2188 Inhibitor *offending = NULL;
2189 uid_t uid;
2190 int r;
2191
2192 assert(m);
2193 assert(a);
2194 assert(message);
2195
2196 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
2197 if (r < 0)
2198 return r;
2199
2200 r = sd_bus_creds_get_euid(creds, &uid);
2201 if (r < 0)
2202 return r;
2203
2204 r = have_multiple_sessions(m, uid);
2205 if (r < 0)
2206 return r;
2207
2208 multiple_sessions = r > 0;
2209 blocked = manager_is_inhibited(m, a->inhibit_what, NULL, /* flags= */ 0, uid, &offending);
2210 interactive = flags & SD_LOGIND_INTERACTIVE;
2211
2212 if (multiple_sessions) {
2213 r = bus_verify_polkit_async_full(
2214 message,
2215 a->polkit_action_multiple_sessions,
2216 /* details= */ NULL,
2217 /* good_user= */ UID_INVALID,
2218 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
2219 &m->polkit_registry,
2220 error);
2221 if (r < 0) {
2222 /* If we get -EBUSY, it means a polkit decision was made, but not for
2223 * this action in particular. Assuming we are blocked on inhibitors,
2224 * ignore that error and allow the decision to be revealed below. */
2225 if (blocked && r == -EBUSY)
2226 error_or_denial = true;
2227 else
2228 return r;
2229 }
2230 if (r == 0)
2231 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
2232 }
2233
2234 if (blocked) {
2235 PolkitFlags polkit_flags = 0;
2236
2237 /* With a strong inhibitor, if the skip flag is not set, reject outright.
2238 * With a weak inhibitor, if root is asking and the root flag is set, reject outright.
2239 * All else, check polkit first. */
2240 if (!FLAGS_SET(flags, SD_LOGIND_SKIP_INHIBITORS) &&
2241 (offending->mode != INHIBIT_BLOCK_WEAK ||
2242 (uid == 0 && FLAGS_SET(flags, SD_LOGIND_ROOT_CHECK_INHIBITORS))))
2243 return sd_bus_error_setf(error, BUS_ERROR_BLOCKED_BY_INHIBITOR_LOCK,
2244 "Operation denied due to active block inhibitor");
2245
2246 /* We want to always ask here, even for root, to only allow bypassing if explicitly allowed
2247 * by polkit, unless a weak blocker is used, in which case it will be authorized. */
2248 if (offending->mode != INHIBIT_BLOCK_WEAK)
2249 polkit_flags |= POLKIT_ALWAYS_QUERY;
2250
2251 if (interactive)
2252 polkit_flags |= POLKIT_ALLOW_INTERACTIVE;
2253
2254 r = bus_verify_polkit_async_full(
2255 message,
2256 a->polkit_action_ignore_inhibit,
2257 /* details= */ NULL,
2258 /* good_user= */ UID_INVALID,
2259 polkit_flags,
2260 &m->polkit_registry,
2261 error);
2262 if (r < 0)
2263 return r;
2264 if (r == 0)
2265 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
2266 }
2267
2268 if (!multiple_sessions && !blocked) {
2269 r = bus_verify_polkit_async_full(
2270 message,
2271 a->polkit_action,
2272 /* details= */ NULL,
2273 /* good_user= */ UID_INVALID,
2274 interactive ? POLKIT_ALLOW_INTERACTIVE : 0,
2275 &m->polkit_registry,
2276 error);
2277 if (r < 0)
2278 return r;
2279 if (r == 0)
2280 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
2281 }
2282
2283 /* If error_or_denial was set above, it means that a polkit denial or
2284 * error was deferred for a future call to bus_verify_polkit_async_full()
2285 * to catch. In any case, it also means that the payload guarded by
2286 * these polkit calls should never be executed, and hence we should
2287 * never reach this point. */
2288 assert(!error_or_denial);
2289
2290 return 0;
2291}
2292
2293static int setup_wall_message_timer(Manager *m, sd_bus_message* message) {
2294 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
2295 int r;
2296
2297 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_AUGMENT|SD_BUS_CREDS_TTY|SD_BUS_CREDS_UID, &creds);
2298 if (r >= 0) {
2299 const char *tty = NULL;
2300
2301 (void) sd_bus_creds_get_uid(creds, &m->scheduled_shutdown_uid);
2302 (void) sd_bus_creds_get_tty(creds, &tty);
2303
2304 r = free_and_strdup(&m->scheduled_shutdown_tty, tty);
2305 if (r < 0)
2306 return log_oom();
2307 }
2308
2309 r = manager_setup_wall_message_timer(m);
2310 if (r < 0)
2311 return r;
2312
2313 return 0;
2314}
2315
2316static int method_do_shutdown_or_sleep(
2317 Manager *m,
2318 sd_bus_message *message,
2319 HandleAction action,
2320 bool with_flags,
2321 sd_bus_error *error) {
2322
2323 uint64_t flags;
2324 int r;
2325
2326 assert(m);
2327 assert(message);
2328 assert(HANDLE_ACTION_IS_SHUTDOWN(action) || HANDLE_ACTION_IS_SLEEP(action));
2329
2330 if (with_flags) {
2331 /* New style method: with flags parameter (and interactive bool in the bus message header) */
2332 r = sd_bus_message_read(message, "t", &flags);
2333 if (r < 0)
2334 return r;
2335 if ((flags & ~SD_LOGIND_SHUTDOWN_AND_SLEEP_FLAGS_PUBLIC) != 0)
2336 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS,
2337 "Invalid flags parameter");
2338
2339 if (FLAGS_SET(flags, (SD_LOGIND_REBOOT_VIA_KEXEC|SD_LOGIND_SOFT_REBOOT)))
2340 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS,
2341 "Both reboot via kexec and soft reboot selected, which is not supported");
2342
2343 if (action != HANDLE_REBOOT) {
2344 if (FLAGS_SET(flags, SD_LOGIND_REBOOT_VIA_KEXEC))
2345 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS,
2346 "Reboot via kexec option is only applicable with reboot operations");
2347 if (flags & (SD_LOGIND_SOFT_REBOOT|SD_LOGIND_SOFT_REBOOT_IF_NEXTROOT_SET_UP))
2348 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS,
2349 "Soft reboot option is only applicable with reboot operations");
2350 }
2351 } else {
2352 /* Old style method: no flags parameter, but interactive bool passed as boolean in
2353 * payload. Let's convert this argument to the new-style flags parameter for our internal
2354 * use. */
2355 int interactive;
2356
2357 r = sd_bus_message_read(message, "b", &interactive);
2358 if (r < 0)
2359 return r;
2360
2361 flags = interactive ? SD_LOGIND_INTERACTIVE : 0;
2362 }
2363
2364 const HandleActionData *a = NULL;
2365
2366 if (FLAGS_SET(flags, SD_LOGIND_SOFT_REBOOT) ||
2367 (FLAGS_SET(flags, SD_LOGIND_SOFT_REBOOT_IF_NEXTROOT_SET_UP) && path_is_os_tree("/run/nextroot") > 0))
2368 a = handle_action_lookup(HANDLE_SOFT_REBOOT);
2369 else if (FLAGS_SET(flags, SD_LOGIND_REBOOT_VIA_KEXEC) && kexec_loaded())
2370 a = handle_action_lookup(HANDLE_KEXEC);
2371
2372 if (action == HANDLE_SLEEP) {
2373 HandleAction selected;
2374
2375 selected = handle_action_sleep_select(m);
2376 if (selected < 0)
2377 return sd_bus_error_set(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED,
2378 "None of the configured sleep operations are supported");
2379
2380 assert_se(a = handle_action_lookup(selected));
2381
2382 } else if (HANDLE_ACTION_IS_SLEEP(action)) {
2383 SleepSupport support;
2384
2385 assert_se(a = handle_action_lookup(action));
2386
2387 assert(a->sleep_operation >= 0);
2388 assert(a->sleep_operation < _SLEEP_OPERATION_MAX);
2389
2390 r = sleep_supported_full(a->sleep_operation, &support);
2391 if (r < 0)
2392 return r;
2393 if (r == 0)
2394 switch (support) {
2395
2396 case SLEEP_DISABLED:
2397 return sd_bus_error_setf(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED,
2398 "Sleep verb '%s' is disabled by config",
2399 sleep_operation_to_string(a->sleep_operation));
2400
2401 case SLEEP_NOT_CONFIGURED:
2402 case SLEEP_STATE_OR_MODE_NOT_SUPPORTED:
2403 case SLEEP_ALARM_NOT_SUPPORTED:
2404 return sd_bus_error_setf(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED,
2405 "Sleep verb '%s' is not configured or configuration is not supported by kernel",
2406 sleep_operation_to_string(a->sleep_operation));
2407
2408 case SLEEP_RESUME_NOT_SUPPORTED:
2409 return sd_bus_error_set(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED,
2410 "Not running on EFI and resume= is not set, or noresume is set. No available method to resume from hibernation");
2411
2412 case SLEEP_RESUME_DEVICE_MISSING:
2413 return sd_bus_error_set(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED,
2414 "Specified resume device is missing or is not an active swap device");
2415
2416 case SLEEP_RESUME_MISCONFIGURED:
2417 return sd_bus_error_set(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED,
2418 "Invalid resume config: resume= is not populated yet resume_offset= is");
2419
2420 case SLEEP_NOT_ENOUGH_SWAP_SPACE:
2421 return sd_bus_error_set(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED,
2422 "Not enough suitable swap space for hibernation available on compatible block devices and file systems");
2423
2424 default:
2425 assert_not_reached();
2426
2427 }
2428 } else if (!a)
2429 assert_se(a = handle_action_lookup(action));
2430
2431 r = verify_shutdown_creds(m, message, a, flags, error);
2432 if (r != 0)
2433 return r;
2434
2435 if (m->delayed_action)
2436 return sd_bus_error_setf(error, BUS_ERROR_OPERATION_IN_PROGRESS,
2437 "Action %s already in progress, refusing requested %s operation.",
2438 handle_action_to_string(m->delayed_action->handle),
2439 handle_action_to_string(a->handle));
2440
2441 /* reset case we're shorting a scheduled shutdown */
2442 m->unlink_nologin = false;
2443 reset_scheduled_shutdown(m);
2444
2445 m->scheduled_shutdown_timeout = 0;
2446 m->scheduled_shutdown_action = action;
2447
2448 (void) setup_wall_message_timer(m, message);
2449
2450 r = bus_manager_shutdown_or_sleep_now_or_later(m, a, error);
2451 if (r < 0)
2452 return r;
2453
2454 return sd_bus_reply_method_return(message, NULL);
2455}
2456
2457static int method_poweroff(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2458 Manager *m = userdata;
2459
2460 return method_do_shutdown_or_sleep(
2461 m, message,
2462 HANDLE_POWEROFF,
2463 sd_bus_message_is_method_call(message, NULL, "PowerOffWithFlags"),
2464 error);
2465}
2466
2467static int method_reboot(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2468 Manager *m = userdata;
2469
2470 return method_do_shutdown_or_sleep(
2471 m, message,
2472 HANDLE_REBOOT,
2473 sd_bus_message_is_method_call(message, NULL, "RebootWithFlags"),
2474 error);
2475}
2476
2477static int method_halt(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2478 Manager *m = userdata;
2479
2480 return method_do_shutdown_or_sleep(
2481 m, message,
2482 HANDLE_HALT,
2483 sd_bus_message_is_method_call(message, NULL, "HaltWithFlags"),
2484 error);
2485}
2486
2487static int method_suspend(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2488 Manager *m = userdata;
2489
2490 return method_do_shutdown_or_sleep(
2491 m, message,
2492 HANDLE_SUSPEND,
2493 sd_bus_message_is_method_call(message, NULL, "SuspendWithFlags"),
2494 error);
2495}
2496
2497static int method_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2498 Manager *m = userdata;
2499
2500 return method_do_shutdown_or_sleep(
2501 m, message,
2502 HANDLE_HIBERNATE,
2503 sd_bus_message_is_method_call(message, NULL, "HibernateWithFlags"),
2504 error);
2505}
2506
2507static int method_hybrid_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2508 Manager *m = userdata;
2509
2510 return method_do_shutdown_or_sleep(
2511 m, message,
2512 HANDLE_HYBRID_SLEEP,
2513 sd_bus_message_is_method_call(message, NULL, "HybridSleepWithFlags"),
2514 error);
2515}
2516
2517static int method_suspend_then_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2518 Manager *m = userdata;
2519
2520 return method_do_shutdown_or_sleep(
2521 m, message,
2522 HANDLE_SUSPEND_THEN_HIBERNATE,
2523 sd_bus_message_is_method_call(message, NULL, "SuspendThenHibernateWithFlags"),
2524 error);
2525}
2526
2527static int method_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2528 Manager *m = userdata;
2529
2530 return method_do_shutdown_or_sleep(
2531 m, message,
2532 HANDLE_SLEEP,
2533 /* with_flags = */ true,
2534 error);
2535}
2536
2537static int nologin_timeout_handler(
2538 sd_event_source *s,
2539 uint64_t usec,
2540 void *userdata) {
2541
2542 Manager *m = ASSERT_PTR(userdata);
2543
2544 log_info("Creating /run/nologin, blocking further logins...");
2545
2546 m->unlink_nologin =
2547 create_shutdown_run_nologin_or_warn() >= 0;
2548
2549 return 0;
2550}
2551
2552static usec_t nologin_timeout_usec(usec_t elapse) {
2553 /* Issue /run/nologin five minutes before shutdown */
2554 return LESS_BY(elapse, 5 * USEC_PER_MINUTE);
2555}
2556
2557static void reset_scheduled_shutdown(Manager *m) {
2558 assert(m);
2559
2560 m->scheduled_shutdown_timeout_source = sd_event_source_disable_unref(m->scheduled_shutdown_timeout_source);
2561 m->wall_message_timeout_source = sd_event_source_disable_unref(m->wall_message_timeout_source);
2562 m->nologin_timeout_source = sd_event_source_disable_unref(m->nologin_timeout_source);
2563
2564 m->scheduled_shutdown_action = _HANDLE_ACTION_INVALID;
2565 m->scheduled_shutdown_timeout = USEC_INFINITY;
2566 m->scheduled_shutdown_uid = UID_INVALID;
2567 m->scheduled_shutdown_tty = mfree(m->scheduled_shutdown_tty);
2568 m->shutdown_dry_run = false;
2569
2570 if (m->unlink_nologin) {
2571 (void) unlink_or_warn("/run/nologin");
2572 m->unlink_nologin = false;
2573 }
2574
2575 (void) unlink(SHUTDOWN_SCHEDULE_FILE);
2576
2577 manager_send_changed(m, "ScheduledShutdown");
2578}
2579
2580static int update_schedule_file(Manager *m) {
2581 _cleanup_(unlink_and_freep) char *temp_path = NULL;
2582 _cleanup_fclose_ FILE *f = NULL;
2583 int r;
2584
2585 assert(m);
2586 assert(handle_action_valid(m->scheduled_shutdown_action));
2587
2588 r = mkdir_parents_label(SHUTDOWN_SCHEDULE_FILE, 0755);
2589 if (r < 0)
2590 return log_error_errno(r, "Failed to create shutdown subdirectory: %m");
2591
2592 r = fopen_temporary(SHUTDOWN_SCHEDULE_FILE, &f, &temp_path);
2593 if (r < 0)
2594 return log_error_errno(r, "Failed to save information about scheduled shutdowns: %m");
2595
2596 (void) fchmod(fileno(f), 0644);
2597
2598 serialize_usec(f, "USEC", m->scheduled_shutdown_timeout);
2599 serialize_item_format(f, "WARN_WALL", "%s", one_zero(m->wall_messages));
2600 serialize_item_format(f, "MODE", "%s", handle_action_to_string(m->scheduled_shutdown_action));
2601 serialize_item_format(f, "UID", UID_FMT, m->scheduled_shutdown_uid);
2602
2603 if (m->scheduled_shutdown_tty)
2604 serialize_item_format(f, "TTY", "%s", m->scheduled_shutdown_tty);
2605
2606 if (!isempty(m->wall_message)) {
2607 r = serialize_item_escaped(f, "WALL_MESSAGE", m->wall_message);
2608 if (r < 0)
2609 goto fail;
2610 }
2611
2612 r = fflush_and_check(f);
2613 if (r < 0)
2614 goto fail;
2615
2616 if (rename(temp_path, SHUTDOWN_SCHEDULE_FILE) < 0) {
2617 r = -errno;
2618 goto fail;
2619 }
2620
2621 temp_path = mfree(temp_path);
2622 return 0;
2623
2624fail:
2625 (void) unlink(SHUTDOWN_SCHEDULE_FILE);
2626
2627 return log_error_errno(r, "Failed to write information about scheduled shutdowns: %m");
2628}
2629
2630static int manager_scheduled_shutdown_handler(
2631 sd_event_source *s,
2632 uint64_t usec,
2633 void *userdata) {
2634
2635 Manager *m = ASSERT_PTR(userdata);
2636 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2637 const HandleActionData *a;
2638 int r;
2639
2640 assert_se(a = handle_action_lookup(m->scheduled_shutdown_action));
2641
2642 /* Don't allow multiple jobs being executed at the same time */
2643 if (m->delayed_action) {
2644 r = log_error_errno(SYNTHETIC_ERRNO(EALREADY),
2645 "Scheduled shutdown to %s failed: shutdown or sleep operation already in progress.",
2646 a->target);
2647 goto error;
2648 }
2649
2650 if (m->shutdown_dry_run) {
2651 /* We do not process delay inhibitors here. Otherwise, we
2652 * would have to be considered "in progress" (like the check
2653 * above) for some seconds after our admin has seen the final
2654 * wall message. */
2655
2656 bus_manager_log_shutdown(m, a);
2657 log_info("Running in dry run, suppressing action.");
2658 reset_scheduled_shutdown(m);
2659
2660 return 0;
2661 }
2662
2663 r = bus_manager_shutdown_or_sleep_now_or_later(m, a, &error);
2664 if (r < 0) {
2665 log_error_errno(r, "Scheduled shutdown to %s failed: %m", a->target);
2666 goto error;
2667 }
2668
2669 return 0;
2670
2671error:
2672 reset_scheduled_shutdown(m);
2673 return r;
2674}
2675
2676static int manager_setup_shutdown_timers(Manager* m) {
2677 int r;
2678
2679 assert(m);
2680
2681 r = event_reset_time(m->event, &m->scheduled_shutdown_timeout_source,
2682 CLOCK_REALTIME,
2683 m->scheduled_shutdown_timeout, 0,
2684 manager_scheduled_shutdown_handler, m,
2685 0, "scheduled-shutdown-timeout", true);
2686 if (r < 0)
2687 goto fail;
2688
2689 r = event_reset_time(m->event, &m->nologin_timeout_source,
2690 CLOCK_REALTIME,
2691 nologin_timeout_usec(m->scheduled_shutdown_timeout), 0,
2692 nologin_timeout_handler, m,
2693 0, "nologin-timeout", true);
2694 if (r < 0)
2695 goto fail;
2696
2697 return 0;
2698
2699fail:
2700 m->scheduled_shutdown_timeout_source = sd_event_source_unref(m->scheduled_shutdown_timeout_source);
2701 m->nologin_timeout_source = sd_event_source_unref(m->nologin_timeout_source);
2702
2703 return r;
2704}
2705
2706void manager_load_scheduled_shutdown(Manager *m) {
2707 _cleanup_fclose_ FILE *f = NULL;
2708 _cleanup_free_ char *usec = NULL,
2709 *warn_wall = NULL,
2710 *mode = NULL,
2711 *wall_message = NULL,
2712 *uid = NULL,
2713 *tty = NULL;
2714 int r;
2715
2716 assert(m);
2717
2718 r = parse_env_file(f, SHUTDOWN_SCHEDULE_FILE,
2719 "USEC", &usec,
2720 "WARN_WALL", &warn_wall,
2721 "MODE", &mode,
2722 "WALL_MESSAGE", &wall_message,
2723 "UID", &uid,
2724 "TTY", &tty);
2725
2726 /* reset will delete the file */
2727 reset_scheduled_shutdown(m);
2728
2729 if (r == -ENOENT)
2730 return;
2731 if (r < 0)
2732 return (void) log_debug_errno(r, "Failed to parse " SHUTDOWN_SCHEDULE_FILE ": %m");
2733
2734 HandleAction handle = handle_action_from_string(mode);
2735 if (handle < 0)
2736 return (void) log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse scheduled shutdown type: %s", mode);
2737
2738 if (!usec)
2739 return (void) log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "USEC is required");
2740 if (deserialize_usec(usec, &m->scheduled_shutdown_timeout) < 0)
2741 return;
2742
2743 /* assign parsed type only after we know usec is also valid */
2744 m->scheduled_shutdown_action = handle;
2745
2746 if (warn_wall) {
2747 r = parse_boolean(warn_wall);
2748 if (r < 0)
2749 log_debug_errno(r, "Failed to parse enabling wall messages");
2750 else
2751 m->wall_messages = r;
2752 }
2753
2754 if (wall_message) {
2755 _cleanup_free_ char *unescaped = NULL;
2756 r = cunescape(wall_message, 0, &unescaped);
2757 if (r < 0)
2758 log_debug_errno(r, "Failed to parse wall message: %s", wall_message);
2759 else
2760 free_and_replace(m->wall_message, unescaped);
2761 }
2762
2763 if (uid) {
2764 r = parse_uid(uid, &m->scheduled_shutdown_uid);
2765 if (r < 0)
2766 log_debug_errno(r, "Failed to parse wall uid: %s", uid);
2767 }
2768
2769 free_and_replace(m->scheduled_shutdown_tty, tty);
2770
2771 r = manager_setup_shutdown_timers(m);
2772 if (r < 0)
2773 return reset_scheduled_shutdown(m);
2774
2775 (void) manager_setup_wall_message_timer(m);
2776 (void) update_schedule_file(m);
2777
2778 return;
2779}
2780
2781static int method_schedule_shutdown(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2782 Manager *m = ASSERT_PTR(userdata);
2783 HandleAction handle;
2784 const HandleActionData *a;
2785 uint64_t elapse;
2786 char *type;
2787 int r;
2788 bool dry_run = false;
2789
2790 assert(message);
2791
2792 r = sd_bus_message_read(message, "st", &type, &elapse);
2793 if (r < 0)
2794 return r;
2795
2796 if (startswith(type, "dry-")) {
2797 type += 4;
2798 dry_run = true;
2799 }
2800
2801 handle = handle_action_from_string(type);
2802 if (!HANDLE_ACTION_IS_SHUTDOWN(handle))
2803 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Unsupported shutdown type: %s", type);
2804
2805 assert_se(a = handle_action_lookup(handle));
2806 assert(a->polkit_action);
2807
2808 r = verify_shutdown_creds(m, message, a, 0, error);
2809 if (r != 0)
2810 return r;
2811
2812 if (elapse == USEC_INFINITY) {
2813 if (m->maintenance_time) {
2814 r = calendar_spec_next_usec(m->maintenance_time, now(CLOCK_REALTIME), &elapse);
2815 if (r < 0) {
2816 if (r == -ENOENT)
2817 return sd_bus_error_set(error,
2818 BUS_ERROR_DESIGNATED_MAINTENANCE_TIME_NOT_SCHEDULED,
2819 "No upcoming maintenance window scheduled");
2820
2821 return sd_bus_error_set_errnof(error, r,
2822 "Failed to determine next maintenance window: %m");
2823 }
2824
2825 log_info("Scheduled %s at maintenance window %s", type, FORMAT_TIMESTAMP(elapse));
2826 } else
2827 /* the good old shutdown command uses one minute by default */
2828 elapse = usec_add(now(CLOCK_REALTIME), USEC_PER_MINUTE);
2829 }
2830
2831 m->scheduled_shutdown_action = handle;
2832 m->shutdown_dry_run = dry_run;
2833 m->scheduled_shutdown_timeout = elapse;
2834
2835 r = manager_setup_shutdown_timers(m);
2836 if (r < 0)
2837 return r;
2838
2839 r = setup_wall_message_timer(m, message);
2840 if (r >= 0)
2841 r = update_schedule_file(m);
2842
2843 if (r < 0) {
2844 reset_scheduled_shutdown(m);
2845 return r;
2846 }
2847
2848 manager_send_changed(m, "ScheduledShutdown");
2849
2850 return sd_bus_reply_method_return(message, NULL);
2851}
2852
2853static int method_cancel_scheduled_shutdown(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2854 Manager *m = ASSERT_PTR(userdata);
2855 const HandleActionData *a;
2856 bool cancelled;
2857 int r;
2858
2859 assert(message);
2860
2861 cancelled = handle_action_valid(m->scheduled_shutdown_action) && m->scheduled_shutdown_action != HANDLE_IGNORE;
2862 if (!cancelled)
2863 return sd_bus_reply_method_return(message, "b", false);
2864
2865 assert_se(a = handle_action_lookup(m->scheduled_shutdown_action));
2866 if (!a->polkit_action)
2867 return sd_bus_error_set(error, SD_BUS_ERROR_AUTH_FAILED, "Unsupported shutdown type");
2868
2869 r = bus_verify_polkit_async(
2870 message,
2871 a->polkit_action,
2872 /* details= */ NULL,
2873 &m->polkit_registry,
2874 error);
2875 if (r < 0)
2876 return r;
2877 if (r == 0)
2878 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
2879
2880 if (m->wall_messages) {
2881 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
2882 const char *tty = NULL;
2883 uid_t uid = 0;
2884
2885 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_AUGMENT|SD_BUS_CREDS_TTY|SD_BUS_CREDS_UID, &creds);
2886 if (r >= 0) {
2887 (void) sd_bus_creds_get_uid(creds, &uid);
2888 (void) sd_bus_creds_get_tty(creds, &tty);
2889 }
2890
2891 _cleanup_free_ char *username = uid_to_name(uid);
2892
2893 log_struct(LOG_INFO,
2894 LOG_MESSAGE("System shutdown has been cancelled"),
2895 LOG_ITEM("ACTION=%s", handle_action_to_string(a->handle)),
2896 LOG_MESSAGE_ID(SD_MESSAGE_SHUTDOWN_CANCELED_STR),
2897 username ? "OPERATOR=%s" : NULL, username);
2898
2899 (void) wall("System shutdown has been cancelled",
2900 username, tty, logind_wall_tty_filter, m);
2901 }
2902
2903 cancel_delayed_action(m);
2904 reset_scheduled_shutdown(m);
2905
2906 return sd_bus_reply_method_return(message, "b", true);
2907}
2908
2909static int method_can_shutdown_or_sleep(
2910 Manager *m,
2911 sd_bus_message *message,
2912 HandleAction action,
2913 sd_bus_error *error) {
2914
2915 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
2916 bool multiple_sessions, challenge, blocked, check_unit_state = true;
2917 const HandleActionData *a;
2918 const char *result = NULL;
2919 uid_t uid;
2920 int r;
2921
2922 assert(m);
2923 assert(message);
2924 assert(HANDLE_ACTION_IS_SHUTDOWN(action) || HANDLE_ACTION_IS_SLEEP(action));
2925
2926 if (action == HANDLE_SLEEP) {
2927 HandleAction selected;
2928
2929 selected = handle_action_sleep_select(m);
2930 if (selected < 0)
2931 return sd_bus_reply_method_return(message, "s", "na");
2932
2933 check_unit_state = false; /* Already handled by handle_action_sleep_select */
2934
2935 assert_se(a = handle_action_lookup(selected));
2936
2937 } else if (HANDLE_ACTION_IS_SLEEP(action)) {
2938 SleepSupport support;
2939
2940 assert_se(a = handle_action_lookup(action));
2941
2942 assert(a->sleep_operation >= 0);
2943 assert(a->sleep_operation < _SLEEP_OPERATION_MAX);
2944
2945 r = sleep_supported_full(a->sleep_operation, &support);
2946 if (r < 0)
2947 return r;
2948 if (r == 0)
2949 return sd_bus_reply_method_return(message, "s", support == SLEEP_DISABLED ? "no" : "na");
2950 } else
2951 assert_se(a = handle_action_lookup(action));
2952
2953 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
2954 if (r < 0)
2955 return r;
2956
2957 r = sd_bus_creds_get_euid(creds, &uid);
2958 if (r < 0)
2959 return r;
2960
2961 r = have_multiple_sessions(m, uid);
2962 if (r < 0)
2963 return r;
2964
2965 multiple_sessions = r > 0;
2966 blocked = manager_is_inhibited(m, a->inhibit_what, NULL, /* flags= */ 0, uid, NULL);
2967
2968 if (check_unit_state && a->target) {
2969 _cleanup_free_ char *load_state = NULL;
2970
2971 r = unit_load_state(m->bus, a->target, &load_state);
2972 if (r < 0)
2973 return r;
2974
2975 if (!streq(load_state, "loaded")) {
2976 result = "no";
2977 goto finish;
2978 }
2979 }
2980
2981 if (multiple_sessions) {
2982 r = bus_test_polkit(
2983 message,
2984 a->polkit_action_multiple_sessions,
2985 /* details= */ NULL,
2986 /* good_user= */ UID_INVALID,
2987 &challenge,
2988 error);
2989 if (r < 0)
2990 return r;
2991
2992 if (r > 0)
2993 result = "yes";
2994 else if (challenge)
2995 result = "challenge";
2996 else
2997 result = "no";
2998 }
2999
3000 if (blocked) {
3001 r = bus_test_polkit(
3002 message,
3003 a->polkit_action_ignore_inhibit,
3004 /* details= */ NULL,
3005 /* good_user= */ UID_INVALID,
3006 &challenge,
3007 error);
3008 if (r < 0)
3009 return r;
3010
3011 if (r > 0) {
3012 if (!result)
3013 result = "yes";
3014 } else if (challenge) {
3015 if (!result || streq(result, "yes"))
3016 result = "challenge";
3017 } else
3018 result = "no";
3019 }
3020
3021 if (!multiple_sessions && !blocked) {
3022 /* If neither inhibit nor multiple sessions
3023 * apply then just check the normal policy */
3024
3025 r = bus_test_polkit(
3026 message,
3027 a->polkit_action,
3028 /* details= */ NULL,
3029 /* good_user= */ UID_INVALID,
3030 &challenge,
3031 error);
3032 if (r < 0)
3033 return r;
3034
3035 if (r > 0)
3036 result = "yes";
3037 else if (challenge)
3038 result = "challenge";
3039 else
3040 result = "no";
3041 }
3042
3043 finish:
3044 return sd_bus_reply_method_return(message, "s", result);
3045}
3046
3047static int method_can_poweroff(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3048 Manager *m = userdata;
3049
3050 return method_can_shutdown_or_sleep(m, message, HANDLE_POWEROFF, error);
3051}
3052
3053static int method_can_reboot(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3054 Manager *m = userdata;
3055
3056 return method_can_shutdown_or_sleep(m, message, HANDLE_REBOOT, error);
3057}
3058
3059static int method_can_halt(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3060 Manager *m = userdata;
3061
3062 return method_can_shutdown_or_sleep(m, message, HANDLE_HALT, error);
3063}
3064
3065static int method_can_suspend(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3066 Manager *m = userdata;
3067
3068 return method_can_shutdown_or_sleep(m, message, HANDLE_SUSPEND, error);
3069}
3070
3071static int method_can_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3072 Manager *m = userdata;
3073
3074 return method_can_shutdown_or_sleep(m, message, HANDLE_HIBERNATE, error);
3075}
3076
3077static int method_can_hybrid_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3078 Manager *m = userdata;
3079
3080 return method_can_shutdown_or_sleep(m, message, HANDLE_HYBRID_SLEEP, error);
3081}
3082
3083static int method_can_suspend_then_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3084 Manager *m = userdata;
3085
3086 return method_can_shutdown_or_sleep(m, message, HANDLE_SUSPEND_THEN_HIBERNATE, error);
3087}
3088
3089static int method_can_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3090 Manager *m = userdata;
3091
3092 return method_can_shutdown_or_sleep(m, message, HANDLE_SLEEP, error);
3093}
3094
3095static int property_get_reboot_parameter(
3096 sd_bus *bus,
3097 const char *path,
3098 const char *interface,
3099 const char *property,
3100 sd_bus_message *reply,
3101 void *userdata,
3102 sd_bus_error *error) {
3103 _cleanup_free_ char *parameter = NULL;
3104 int r;
3105
3106 assert(bus);
3107 assert(reply);
3108 assert(userdata);
3109
3110 r = read_reboot_parameter(&parameter);
3111 if (r < 0)
3112 return r;
3113
3114 return sd_bus_message_append(reply, "s", parameter);
3115}
3116
3117static int method_set_reboot_parameter(
3118 sd_bus_message *message,
3119 void *userdata,
3120 sd_bus_error *error) {
3121
3122 Manager *m = ASSERT_PTR(userdata);
3123 const char *arg;
3124 int r;
3125
3126 assert(message);
3127
3128 r = sd_bus_message_read(message, "s", &arg);
3129 if (r < 0)
3130 return r;
3131
3132 if (!reboot_parameter_is_valid(arg))
3133 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid reboot parameter '%s'.", arg);
3134
3135 r = detect_container();
3136 if (r < 0)
3137 return r;
3138 if (r > 0)
3139 return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
3140 "Reboot parameter not supported in containers, refusing.");
3141
3142 r = bus_verify_polkit_async(
3143 message,
3144 "org.freedesktop.login1.set-reboot-parameter",
3145 /* details= */ NULL,
3146 &m->polkit_registry,
3147 error);
3148 if (r < 0)
3149 return r;
3150 if (r == 0)
3151 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
3152
3153 r = update_reboot_parameter_and_warn(arg, false);
3154 if (r < 0)
3155 return r;
3156
3157 return sd_bus_reply_method_return(message, NULL);
3158}
3159
3160static int method_can_reboot_parameter(
3161 sd_bus_message *message,
3162 void *userdata,
3163 sd_bus_error *error) {
3164
3165 _unused_ Manager *m = ASSERT_PTR(userdata);
3166 int r;
3167
3168 assert(message);
3169
3170 r = detect_container();
3171 if (r < 0)
3172 return r;
3173 if (r > 0) /* Inside containers, specifying a reboot parameter, doesn't make much sense */
3174 return sd_bus_reply_method_return(message, "s", "na");
3175
3176 return return_test_polkit(
3177 message,
3178 "org.freedesktop.login1.set-reboot-parameter",
3179 /* details= */ NULL,
3180 /* good_user= */ UID_INVALID,
3181 error);
3182}
3183
3184static int property_get_reboot_to_firmware_setup(
3185 sd_bus *bus,
3186 const char *path,
3187 const char *interface,
3188 const char *property,
3189 sd_bus_message *reply,
3190 void *userdata,
3191 sd_bus_error *error) {
3192 int r;
3193
3194 assert(bus);
3195 assert(reply);
3196 assert(userdata);
3197
3198 r = getenv_bool("SYSTEMD_REBOOT_TO_FIRMWARE_SETUP");
3199 if (r == -ENXIO) {
3200 /* EFI case: let's see what is currently configured in the EFI variables */
3201 r = efi_get_reboot_to_firmware();
3202 if (r < 0 && r != -EOPNOTSUPP)
3203 log_warning_errno(r, "Failed to determine reboot-to-firmware-setup state: %m");
3204 } else if (r < 0)
3205 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_FIRMWARE_SETUP: %m");
3206 else if (r > 0) {
3207 /* Non-EFI case: let's see whether /run/systemd/reboot-to-firmware-setup exists. */
3208 if (access("/run/systemd/reboot-to-firmware-setup", F_OK) < 0) {
3209 if (errno != ENOENT)
3210 log_warning_errno(errno, "Failed to check whether /run/systemd/reboot-to-firmware-setup exists: %m");
3211
3212 r = false;
3213 } else
3214 r = true;
3215 }
3216
3217 return sd_bus_message_append(reply, "b", r > 0);
3218}
3219
3220static int method_set_reboot_to_firmware_setup(
3221 sd_bus_message *message,
3222 void *userdata,
3223 sd_bus_error *error) {
3224
3225 Manager *m = ASSERT_PTR(userdata);
3226 bool use_efi;
3227 int b, r;
3228
3229 assert(message);
3230
3231 r = sd_bus_message_read(message, "b", &b);
3232 if (r < 0)
3233 return r;
3234
3235 r = getenv_bool("SYSTEMD_REBOOT_TO_FIRMWARE_SETUP");
3236 if (r == -ENXIO) {
3237 /* EFI case: let's see what the firmware supports */
3238
3239 r = efi_reboot_to_firmware_supported();
3240 if (r == -EOPNOTSUPP)
3241 return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Firmware does not support boot into firmware.");
3242 if (r < 0)
3243 return r;
3244
3245 use_efi = true;
3246
3247 } else if (r <= 0) {
3248 /* non-EFI case: $SYSTEMD_REBOOT_TO_FIRMWARE_SETUP is set to off */
3249
3250 if (r < 0)
3251 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_FIRMWARE_SETUP: %m");
3252
3253 return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Firmware does not support boot into firmware.");
3254 } else
3255 /* non-EFI case: $SYSTEMD_REBOOT_TO_FIRMWARE_SETUP is set to on */
3256 use_efi = false;
3257
3258 r = bus_verify_polkit_async(
3259 message,
3260 "org.freedesktop.login1.set-reboot-to-firmware-setup",
3261 /* details= */ NULL,
3262 &m->polkit_registry,
3263 error);
3264 if (r < 0)
3265 return r;
3266 if (r == 0)
3267 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
3268
3269 if (use_efi) {
3270 r = efi_set_reboot_to_firmware(b);
3271 if (r < 0)
3272 return r;
3273 } else {
3274 if (b) {
3275 r = touch("/run/systemd/reboot-to-firmware-setup");
3276 if (r < 0)
3277 return r;
3278 } else {
3279 if (unlink("/run/systemd/reboot-to-firmware-setup") < 0 && errno != ENOENT)
3280 return -errno;
3281 }
3282 }
3283
3284 return sd_bus_reply_method_return(message, NULL);
3285}
3286
3287static int method_can_reboot_to_firmware_setup(
3288 sd_bus_message *message,
3289 void *userdata,
3290 sd_bus_error *error) {
3291
3292 _unused_ Manager *m = ASSERT_PTR(userdata);
3293 int r;
3294
3295 assert(message);
3296
3297 r = getenv_bool("SYSTEMD_REBOOT_TO_FIRMWARE_SETUP");
3298 if (r == -ENXIO) {
3299 /* EFI case: let's see what the firmware supports */
3300
3301 r = efi_reboot_to_firmware_supported();
3302 if (r < 0) {
3303 if (r != -EOPNOTSUPP)
3304 log_warning_errno(r, "Failed to determine whether reboot to firmware is supported: %m");
3305
3306 return sd_bus_reply_method_return(message, "s", "na");
3307 }
3308
3309 } else if (r <= 0) {
3310 /* Non-EFI case: let's trust $SYSTEMD_REBOOT_TO_FIRMWARE_SETUP */
3311
3312 if (r < 0)
3313 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_FIRMWARE_SETUP: %m");
3314
3315 return sd_bus_reply_method_return(message, "s", "na");
3316 }
3317
3318 return return_test_polkit(
3319 message,
3320 "org.freedesktop.login1.set-reboot-to-firmware-setup",
3321 /* details= */ NULL,
3322 /* good_user= */ UID_INVALID,
3323 error);
3324}
3325
3326static int property_get_reboot_to_boot_loader_menu(
3327 sd_bus *bus,
3328 const char *path,
3329 const char *interface,
3330 const char *property,
3331 sd_bus_message *reply,
3332 void *userdata,
3333 sd_bus_error *error) {
3334
3335 uint64_t x = UINT64_MAX;
3336 int r;
3337
3338 assert(bus);
3339 assert(reply);
3340 assert(userdata);
3341
3342 r = getenv_bool("SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU");
3343 if (r == -ENXIO) {
3344 /* EFI case: returns the current value of LoaderConfigTimeoutOneShot. Three cases are distinguished:
3345 *
3346 * 1. Variable not set, boot into boot loader menu is not enabled (we return UINT64_MAX to the user)
3347 * 2. Variable set to "0", boot into boot loader menu is enabled with no timeout (we return 0 to the user)
3348 * 3. Variable set to numeric value formatted in ASCII, boot into boot loader menu with the specified timeout in seconds
3349 */
3350
3351 r = efi_loader_get_config_timeout_one_shot(&x);
3352 if (r < 0) {
3353 if (r != -ENOENT)
3354 log_warning_errno(r, "Failed to read LoaderConfigTimeoutOneShot variable, ignoring: %m");
3355 }
3356
3357 } else if (r < 0)
3358 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU: %m");
3359 else if (r > 0) {
3360 _cleanup_free_ char *v = NULL;
3361
3362 /* Non-EFI case, let's process /run/systemd/reboot-to-boot-loader-menu. */
3363
3364 r = read_one_line_file("/run/systemd/reboot-to-boot-loader-menu", &v);
3365 if (r < 0) {
3366 if (r != -ENOENT)
3367 log_warning_errno(r, "Failed to read /run/systemd/reboot-to-boot-loader-menu: %m");
3368 } else {
3369 r = safe_atou64(v, &x);
3370 if (r < 0)
3371 log_warning_errno(r, "Failed to parse /run/systemd/reboot-to-boot-loader-menu: %m");
3372 }
3373 }
3374
3375 return sd_bus_message_append(reply, "t", x);
3376}
3377
3378static int method_set_reboot_to_boot_loader_menu(
3379 sd_bus_message *message,
3380 void *userdata,
3381 sd_bus_error *error) {
3382
3383 Manager *m = ASSERT_PTR(userdata);
3384 bool use_efi;
3385 uint64_t x;
3386 int r;
3387
3388 assert(message);
3389
3390 r = sd_bus_message_read(message, "t", &x);
3391 if (r < 0)
3392 return r;
3393
3394 r = getenv_bool("SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU");
3395 if (r == -ENXIO) {
3396 uint64_t features;
3397
3398 /* EFI case: let's see if booting into boot loader menu is supported. */
3399
3400 r = efi_loader_get_features(&features);
3401 if (r < 0)
3402 log_warning_errno(r, "Failed to determine whether reboot to boot loader menu is supported: %m");
3403 if (r < 0 || !FLAGS_SET(features, EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT))
3404 return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Boot loader does not support boot into boot loader menu.");
3405
3406 use_efi = true;
3407
3408 } else if (r <= 0) {
3409 /* non-EFI case: $SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU is set to off */
3410
3411 if (r < 0)
3412 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU: %m");
3413
3414 return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Boot loader does not support boot into boot loader menu.");
3415 } else
3416 /* non-EFI case: $SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU is set to on */
3417 use_efi = false;
3418
3419 r = bus_verify_polkit_async(
3420 message,
3421 "org.freedesktop.login1.set-reboot-to-boot-loader-menu",
3422 /* details= */ NULL,
3423 &m->polkit_registry,
3424 error);
3425 if (r < 0)
3426 return r;
3427 if (r == 0)
3428 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
3429
3430 if (use_efi) {
3431 if (x == UINT64_MAX)
3432 r = efi_set_variable(EFI_LOADER_VARIABLE_STR("LoaderConfigTimeoutOneShot"), NULL, 0);
3433 else {
3434 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
3435 xsprintf(buf, "%" PRIu64, DIV_ROUND_UP(x, USEC_PER_SEC)); /* second granularity */
3436
3437 r = efi_set_variable_string(EFI_LOADER_VARIABLE_STR("LoaderConfigTimeoutOneShot"), buf);
3438 }
3439 if (r < 0)
3440 return r;
3441 } else {
3442 if (x == UINT64_MAX) {
3443 if (unlink("/run/systemd/reboot-to-boot-loader-menu") < 0 && errno != ENOENT)
3444 return -errno;
3445 } else {
3446 r = write_string_filef("/run/systemd/reboot-to-boot-loader-menu",
3447 WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_LABEL,
3448 "%" PRIu64, x); /* μs granularity */
3449 if (r < 0)
3450 return r;
3451 }
3452 }
3453
3454 return sd_bus_reply_method_return(message, NULL);
3455}
3456
3457static int method_can_reboot_to_boot_loader_menu(
3458 sd_bus_message *message,
3459 void *userdata,
3460 sd_bus_error *error) {
3461
3462 _unused_ Manager *m = ASSERT_PTR(userdata);
3463 int r;
3464
3465 assert(message);
3466
3467 r = getenv_bool("SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU");
3468 if (r == -ENXIO) {
3469 uint64_t features = 0;
3470
3471 /* EFI case, let's see if booting into boot loader menu is supported. */
3472
3473 r = efi_loader_get_features(&features);
3474 if (r < 0)
3475 log_warning_errno(r, "Failed to determine whether reboot to boot loader menu is supported: %m");
3476 if (r < 0 || !FLAGS_SET(features, EFI_LOADER_FEATURE_CONFIG_TIMEOUT_ONE_SHOT))
3477 return sd_bus_reply_method_return(message, "s", "na");
3478
3479 } else if (r <= 0) {
3480 /* Non-EFI case: let's trust $SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU */
3481
3482 if (r < 0)
3483 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_BOOT_LOADER_MENU: %m");
3484
3485 return sd_bus_reply_method_return(message, "s", "na");
3486 }
3487
3488 return return_test_polkit(
3489 message,
3490 "org.freedesktop.login1.set-reboot-to-boot-loader-menu",
3491 /* details= */ NULL,
3492 /* good_user= */ UID_INVALID,
3493 error);
3494}
3495
3496static int property_get_reboot_to_boot_loader_entry(
3497 sd_bus *bus,
3498 const char *path,
3499 const char *interface,
3500 const char *property,
3501 sd_bus_message *reply,
3502 void *userdata,
3503 sd_bus_error *error) {
3504
3505 _cleanup_free_ char *v = NULL;
3506 Manager *m = ASSERT_PTR(userdata);
3507 const char *x = NULL;
3508 int r;
3509
3510 assert(bus);
3511 assert(reply);
3512
3513 r = getenv_bool("SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY");
3514 if (r == -ENXIO) {
3515 /* EFI case: let's read the LoaderEntryOneShot variable */
3516
3517 r = efi_loader_update_entry_one_shot_cache(&m->efi_loader_entry_one_shot, &m->efi_loader_entry_one_shot_stat);
3518 if (r < 0) {
3519 if (r != -ENOENT)
3520 log_warning_errno(r, "Failed to read LoaderEntryOneShot variable, ignoring: %m");
3521 } else
3522 x = m->efi_loader_entry_one_shot;
3523
3524 } else if (r < 0)
3525 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY: %m");
3526 else if (r > 0) {
3527
3528 /* Non-EFI case, let's process /run/systemd/reboot-to-boot-loader-entry. */
3529
3530 r = read_one_line_file("/run/systemd/reboot-to-boot-loader-entry", &v);
3531 if (r < 0) {
3532 if (r != -ENOENT)
3533 log_warning_errno(r, "Failed to read /run/systemd/reboot-to-boot-loader-entry, ignoring: %m");
3534 } else if (!efi_loader_entry_name_valid(v))
3535 log_warning("/run/systemd/reboot-to-boot-loader-entry is not valid, ignoring.");
3536 else
3537 x = v;
3538 }
3539
3540 return sd_bus_message_append(reply, "s", x);
3541}
3542
3543static int boot_loader_entry_exists(Manager *m, const char *id) {
3544 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
3545 int r;
3546
3547 assert(m);
3548 assert(id);
3549
3550 r = boot_config_load_auto(&config, NULL, NULL);
3551 if (r < 0 && r != -ENOKEY) /* don't complain if no GPT is found, hence skip ENOKEY */
3552 return r;
3553
3554 r = manager_read_efi_boot_loader_entries(m);
3555 if (r >= 0)
3556 (void) boot_config_augment_from_loader(&config, m->efi_boot_loader_entries, /* auto_only= */ true);
3557
3558 return !!boot_config_find_entry(&config, id);
3559}
3560
3561static int method_set_reboot_to_boot_loader_entry(
3562 sd_bus_message *message,
3563 void *userdata,
3564 sd_bus_error *error) {
3565
3566 Manager *m = ASSERT_PTR(userdata);
3567 bool use_efi;
3568 const char *v;
3569 int r;
3570
3571 assert(message);
3572
3573 r = sd_bus_message_read(message, "s", &v);
3574 if (r < 0)
3575 return r;
3576
3577 if (isempty(v))
3578 v = NULL;
3579 else if (efi_loader_entry_name_valid(v)) {
3580 r = boot_loader_entry_exists(m, v);
3581 if (r < 0)
3582 return r;
3583 if (r == 0)
3584 return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED, "Boot loader entry '%s' is not known.", v);
3585 } else
3586 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Boot loader entry name '%s' is not valid, refusing.", v);
3587
3588 r = getenv_bool("SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY");
3589 if (r == -ENXIO) {
3590 uint64_t features;
3591
3592 /* EFI case: let's see if booting into boot loader entry is supported. */
3593
3594 r = efi_loader_get_features(&features);
3595 if (r < 0)
3596 log_warning_errno(r, "Failed to determine whether reboot into boot loader entry is supported: %m");
3597 if (r < 0 || !FLAGS_SET(features, EFI_LOADER_FEATURE_ENTRY_ONESHOT))
3598 return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Loader does not support boot into boot loader entry.");
3599
3600 use_efi = true;
3601
3602 } else if (r <= 0) {
3603 /* non-EFI case: $SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY is set to off */
3604
3605 if (r < 0)
3606 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY: %m");
3607
3608 return sd_bus_error_set(error, SD_BUS_ERROR_NOT_SUPPORTED, "Loader does not support boot into boot loader entry.");
3609 } else
3610 /* non-EFI case: $SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY is set to on */
3611 use_efi = false;
3612
3613 r = bus_verify_polkit_async(
3614 message,
3615 "org.freedesktop.login1.set-reboot-to-boot-loader-entry",
3616 /* details= */ NULL,
3617 &m->polkit_registry,
3618 error);
3619 if (r < 0)
3620 return r;
3621 if (r == 0)
3622 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
3623
3624 if (use_efi) {
3625 if (isempty(v))
3626 /* Delete item */
3627 r = efi_set_variable(EFI_LOADER_VARIABLE_STR("LoaderEntryOneShot"), NULL, 0);
3628 else
3629 r = efi_set_variable_string(EFI_LOADER_VARIABLE_STR("LoaderEntryOneShot"), v);
3630 if (r < 0)
3631 return r;
3632 } else {
3633 if (isempty(v)) {
3634 if (unlink("/run/systemd/reboot-to-boot-loader-entry") < 0 && errno != ENOENT)
3635 return -errno;
3636 } else {
3637 r = write_string_file("/run/systemd/reboot-boot-to-loader-entry", v, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_LABEL);
3638 if (r < 0)
3639 return r;
3640 }
3641 }
3642
3643 return sd_bus_reply_method_return(message, NULL);
3644}
3645
3646static int method_can_reboot_to_boot_loader_entry(
3647 sd_bus_message *message,
3648 void *userdata,
3649 sd_bus_error *error) {
3650
3651 _unused_ Manager *m = ASSERT_PTR(userdata);
3652 int r;
3653
3654 assert(message);
3655
3656 r = getenv_bool("SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY");
3657 if (r == -ENXIO) {
3658 uint64_t features = 0;
3659
3660 /* EFI case, let's see if booting into boot loader entry is supported. */
3661
3662 r = efi_loader_get_features(&features);
3663 if (r < 0)
3664 log_warning_errno(r, "Failed to determine whether reboot to boot loader entry is supported: %m");
3665 if (r < 0 || !FLAGS_SET(features, EFI_LOADER_FEATURE_ENTRY_ONESHOT))
3666 return sd_bus_reply_method_return(message, "s", "na");
3667
3668 } else if (r <= 0) {
3669 /* Non-EFI case: let's trust $SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY */
3670
3671 if (r < 0)
3672 log_warning_errno(r, "Failed to parse $SYSTEMD_REBOOT_TO_BOOT_LOADER_ENTRY: %m");
3673
3674 return sd_bus_reply_method_return(message, "s", "na");
3675 }
3676
3677 return return_test_polkit(
3678 message,
3679 "org.freedesktop.login1.set-reboot-to-boot-loader-entry",
3680 /* details= */ NULL,
3681 /* good_user= */ UID_INVALID,
3682 error);
3683}
3684
3685static int property_get_boot_loader_entries(
3686 sd_bus *bus,
3687 const char *path,
3688 const char *interface,
3689 const char *property,
3690 sd_bus_message *reply,
3691 void *userdata,
3692 sd_bus_error *error) {
3693
3694 _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL;
3695 Manager *m = ASSERT_PTR(userdata);
3696 size_t i;
3697 int r;
3698
3699 assert(bus);
3700 assert(reply);
3701
3702 r = boot_config_load_auto(&config, NULL, NULL);
3703 if (r < 0 && r != -ENOKEY) /* don't complain if there's no GPT found */
3704 return r;
3705
3706 r = manager_read_efi_boot_loader_entries(m);
3707 if (r >= 0)
3708 (void) boot_config_augment_from_loader(&config, m->efi_boot_loader_entries, /* auto_only= */ true);
3709
3710 r = sd_bus_message_open_container(reply, 'a', "s");
3711 if (r < 0)
3712 return r;
3713
3714 for (i = 0; i < config.n_entries; i++) {
3715 BootEntry *e = config.entries + i;
3716
3717 r = sd_bus_message_append(reply, "s", e->id);
3718 if (r < 0)
3719 return r;
3720 }
3721
3722 return sd_bus_message_close_container(reply);
3723}
3724
3725static int method_set_wall_message(
3726 sd_bus_message *message,
3727 void *userdata,
3728 sd_bus_error *error) {
3729
3730 int r;
3731 Manager *m = ASSERT_PTR(userdata);
3732 char *wall_message;
3733 int enable_wall_messages;
3734
3735 assert(message);
3736
3737 r = sd_bus_message_read(message, "sb", &wall_message, &enable_wall_messages);
3738 if (r < 0)
3739 return r;
3740
3741 if (strlen(wall_message) > WALL_MESSAGE_MAX)
3742 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
3743 "Wall message too long, maximum permitted length is %u characters.",
3744 WALL_MESSAGE_MAX);
3745
3746 /* Short-circuit the operation if the desired state is already in place, to
3747 * avoid an unnecessary polkit permission check. */
3748 if (streq_ptr(m->wall_message, empty_to_null(wall_message)) &&
3749 m->wall_messages == enable_wall_messages)
3750 goto done;
3751
3752 r = bus_verify_polkit_async(
3753 message,
3754 "org.freedesktop.login1.set-wall-message",
3755 /* details= */ NULL,
3756 &m->polkit_registry,
3757 error);
3758 if (r < 0)
3759 return r;
3760 if (r == 0)
3761 return 1; /* Will call us back */
3762
3763 r = free_and_strdup(&m->wall_message, empty_to_null(wall_message));
3764 if (r < 0)
3765 return log_oom();
3766
3767 m->wall_messages = enable_wall_messages;
3768
3769 done:
3770 return sd_bus_reply_method_return(message, NULL);
3771}
3772
3773static int method_inhibit(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3774 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
3775 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
3776 const char *who, *why, *what, *mode;
3777 _cleanup_free_ char *id = NULL;
3778 _cleanup_close_ int fifo_fd = -EBADF;
3779 Manager *m = ASSERT_PTR(userdata);
3780 InhibitMode mm;
3781 InhibitWhat w;
3782 uid_t uid;
3783 _unused_ bool error_or_denial = false;
3784 int r;
3785
3786 assert(message);
3787
3788 r = sd_bus_message_read(message, "ssss", &what, &who, &why, &mode);
3789 if (r < 0)
3790 return r;
3791
3792 w = inhibit_what_from_string(what);
3793 if (w <= 0)
3794 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
3795 "Invalid what specification %s", what);
3796
3797 mm = inhibit_mode_from_string(mode);
3798 if (mm < 0)
3799 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
3800 "Invalid mode specification %s", mode);
3801
3802 /* Delay is only supported for shutdown/sleep */
3803 if (mm == INHIBIT_DELAY && (w & ~(INHIBIT_SHUTDOWN|INHIBIT_SLEEP)))
3804 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS,
3805 "Delay inhibitors only supported for shutdown and sleep");
3806
3807 /* Don't allow taking delay locks while we are already
3808 * executing the operation. We shouldn't create the impression
3809 * that the lock was successful if the machine is about to go
3810 * down/suspend any moment. */
3811 if (m->delayed_action && m->delayed_action->inhibit_what & w)
3812 return sd_bus_error_setf(error, BUS_ERROR_OPERATION_IN_PROGRESS,
3813 "The operation inhibition has been requested for is already running");
3814
3815 BIT_FOREACH(i, w) {
3816 const InhibitWhat v = 1U << i;
3817
3818 r = bus_verify_polkit_async(
3819 message,
3820 v == INHIBIT_SHUTDOWN ? (IN_SET(mm, INHIBIT_BLOCK, INHIBIT_BLOCK_WEAK) ? "org.freedesktop.login1.inhibit-block-shutdown" : "org.freedesktop.login1.inhibit-delay-shutdown") :
3821 v == INHIBIT_SLEEP ? (IN_SET(mm, INHIBIT_BLOCK, INHIBIT_BLOCK_WEAK) ? "org.freedesktop.login1.inhibit-block-sleep" : "org.freedesktop.login1.inhibit-delay-sleep") :
3822 v == INHIBIT_IDLE ? "org.freedesktop.login1.inhibit-block-idle" :
3823 v == INHIBIT_HANDLE_POWER_KEY ? "org.freedesktop.login1.inhibit-handle-power-key" :
3824 v == INHIBIT_HANDLE_SUSPEND_KEY ? "org.freedesktop.login1.inhibit-handle-suspend-key" :
3825 v == INHIBIT_HANDLE_REBOOT_KEY ? "org.freedesktop.login1.inhibit-handle-reboot-key" :
3826 v == INHIBIT_HANDLE_HIBERNATE_KEY ? "org.freedesktop.login1.inhibit-handle-hibernate-key" :
3827 "org.freedesktop.login1.inhibit-handle-lid-switch",
3828 /* details= */ NULL,
3829 &m->polkit_registry,
3830 error);
3831 if (r < 0) {
3832 /* If we get -EBUSY, it means a polkit decision was made, but not for
3833 * this action in particular. Assuming there are more actions requested,
3834 * ignore that error and allow the decision to be revealed later. */
3835 if ((~v & w) && r == -EBUSY)
3836 error_or_denial = true;
3837 else
3838 return r;
3839 }
3840 if (r == 0)
3841 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
3842 }
3843
3844 /* If error_or_denial was set above, it means that a polkit denial or
3845 * error was deferred for a future call to bus_verify_polkit_async()
3846 * to catch. In any case, it also means that the payload guarded by
3847 * these polkit calls should never be executed, and hence we should
3848 * never reach this point. */
3849 assert(!error_or_denial);
3850
3851 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID|SD_BUS_CREDS_PID|SD_BUS_CREDS_PIDFD, &creds);
3852 if (r < 0)
3853 return r;
3854
3855 r = sd_bus_creds_get_euid(creds, &uid);
3856 if (r < 0)
3857 return r;
3858
3859 r = bus_creds_get_pidref(creds, &pidref);
3860 if (r < 0)
3861 return r;
3862
3863 if (hashmap_size(m->inhibitors) >= m->inhibitors_max)
3864 return sd_bus_error_setf(error, SD_BUS_ERROR_LIMITS_EXCEEDED,
3865 "Maximum number of inhibitors (%" PRIu64 ") reached, refusing further inhibitors.",
3866 m->inhibitors_max);
3867
3868 do {
3869 id = mfree(id);
3870
3871 if (asprintf(&id, "%" PRIu64, ++m->inhibit_counter) < 0)
3872 return -ENOMEM;
3873
3874 } while (hashmap_get(m->inhibitors, id));
3875
3876 _cleanup_(inhibitor_freep) Inhibitor *i = NULL;
3877 r = manager_add_inhibitor(m, id, &i);
3878 if (r < 0)
3879 return r;
3880
3881 i->what = w;
3882 i->mode = mm;
3883 i->pid = TAKE_PIDREF(pidref);
3884 i->uid = uid;
3885 i->why = strdup(why);
3886 i->who = strdup(who);
3887
3888 if (!i->why || !i->who)
3889 return -ENOMEM;
3890
3891 fifo_fd = inhibitor_create_fifo(i);
3892 if (fifo_fd < 0)
3893 return fifo_fd;
3894
3895 r = inhibitor_start(i);
3896 if (r < 0)
3897 return r;
3898 TAKE_PTR(i);
3899
3900 return sd_bus_reply_method_return(message, "h", fifo_fd);
3901}
3902
3903static const sd_bus_vtable manager_vtable[] = {
3904 SD_BUS_VTABLE_START(0),
3905
3906 SD_BUS_WRITABLE_PROPERTY("EnableWallMessages", "b", bus_property_get_bool, bus_property_set_bool, offsetof(Manager, wall_messages), 0),
3907 SD_BUS_WRITABLE_PROPERTY("WallMessage", "s", NULL, NULL, offsetof(Manager, wall_message), 0),
3908
3909 SD_BUS_PROPERTY("NAutoVTs", "u", NULL, offsetof(Manager, n_autovts), SD_BUS_VTABLE_PROPERTY_CONST),
3910 SD_BUS_PROPERTY("KillOnlyUsers", "as", NULL, offsetof(Manager, kill_only_users), SD_BUS_VTABLE_PROPERTY_CONST),
3911 SD_BUS_PROPERTY("KillExcludeUsers", "as", NULL, offsetof(Manager, kill_exclude_users), SD_BUS_VTABLE_PROPERTY_CONST),
3912 SD_BUS_PROPERTY("KillUserProcesses", "b", bus_property_get_bool, offsetof(Manager, kill_user_processes), SD_BUS_VTABLE_PROPERTY_CONST),
3913 SD_BUS_PROPERTY("RebootParameter", "s", property_get_reboot_parameter, 0, 0),
3914 SD_BUS_PROPERTY("RebootToFirmwareSetup", "b", property_get_reboot_to_firmware_setup, 0, 0),
3915 SD_BUS_PROPERTY("RebootToBootLoaderMenu", "t", property_get_reboot_to_boot_loader_menu, 0, 0),
3916 SD_BUS_PROPERTY("RebootToBootLoaderEntry", "s", property_get_reboot_to_boot_loader_entry, 0, 0),
3917 SD_BUS_PROPERTY("BootLoaderEntries", "as", property_get_boot_loader_entries, 0, SD_BUS_VTABLE_PROPERTY_CONST),
3918 SD_BUS_PROPERTY("IdleHint", "b", property_get_idle_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
3919 SD_BUS_PROPERTY("IdleSinceHint", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
3920 SD_BUS_PROPERTY("IdleSinceHintMonotonic", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
3921 SD_BUS_PROPERTY("BlockInhibited", "s", property_get_inhibited, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
3922 SD_BUS_PROPERTY("BlockWeakInhibited", "s", property_get_inhibited, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
3923 SD_BUS_PROPERTY("DelayInhibited", "s", property_get_inhibited, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
3924 SD_BUS_PROPERTY("InhibitDelayMaxUSec", "t", NULL, offsetof(Manager, inhibit_delay_max), SD_BUS_VTABLE_PROPERTY_CONST),
3925 SD_BUS_PROPERTY("UserStopDelayUSec", "t", NULL, offsetof(Manager, user_stop_delay), SD_BUS_VTABLE_PROPERTY_CONST),
3926 SD_BUS_PROPERTY("SleepOperation", "as", property_get_sleep_operations, 0, SD_BUS_VTABLE_PROPERTY_CONST),
3927 SD_BUS_PROPERTY("HandlePowerKey", "s", property_get_handle_action, offsetof(Manager, handle_power_key), SD_BUS_VTABLE_PROPERTY_CONST),
3928 SD_BUS_PROPERTY("HandlePowerKeyLongPress", "s", property_get_handle_action, offsetof(Manager, handle_power_key_long_press), SD_BUS_VTABLE_PROPERTY_CONST),
3929 SD_BUS_PROPERTY("HandleRebootKey", "s", property_get_handle_action, offsetof(Manager, handle_reboot_key), SD_BUS_VTABLE_PROPERTY_CONST),
3930 SD_BUS_PROPERTY("HandleRebootKeyLongPress", "s", property_get_handle_action, offsetof(Manager, handle_reboot_key_long_press), SD_BUS_VTABLE_PROPERTY_CONST),
3931 SD_BUS_PROPERTY("HandleSuspendKey", "s", property_get_handle_action, offsetof(Manager, handle_suspend_key), SD_BUS_VTABLE_PROPERTY_CONST),
3932 SD_BUS_PROPERTY("HandleSuspendKeyLongPress", "s", property_get_handle_action, offsetof(Manager, handle_suspend_key_long_press), SD_BUS_VTABLE_PROPERTY_CONST),
3933 SD_BUS_PROPERTY("HandleHibernateKey", "s", property_get_handle_action, offsetof(Manager, handle_hibernate_key), SD_BUS_VTABLE_PROPERTY_CONST),
3934 SD_BUS_PROPERTY("HandleHibernateKeyLongPress", "s", property_get_handle_action, offsetof(Manager, handle_hibernate_key_long_press), SD_BUS_VTABLE_PROPERTY_CONST),
3935 SD_BUS_PROPERTY("HandleLidSwitch", "s", property_get_handle_action, offsetof(Manager, handle_lid_switch), SD_BUS_VTABLE_PROPERTY_CONST),
3936 SD_BUS_PROPERTY("HandleLidSwitchExternalPower", "s", property_get_handle_action, offsetof(Manager, handle_lid_switch_ep), SD_BUS_VTABLE_PROPERTY_CONST),
3937 SD_BUS_PROPERTY("HandleLidSwitchDocked", "s", property_get_handle_action, offsetof(Manager, handle_lid_switch_docked), SD_BUS_VTABLE_PROPERTY_CONST),
3938 SD_BUS_PROPERTY("HandleSecureAttentionKey", "s", property_get_handle_action, offsetof(Manager, handle_secure_attention_key), SD_BUS_VTABLE_PROPERTY_CONST),
3939 SD_BUS_PROPERTY("HoldoffTimeoutUSec", "t", NULL, offsetof(Manager, holdoff_timeout_usec), SD_BUS_VTABLE_PROPERTY_CONST),
3940 SD_BUS_PROPERTY("IdleAction", "s", property_get_handle_action, offsetof(Manager, idle_action), SD_BUS_VTABLE_PROPERTY_CONST),
3941 SD_BUS_PROPERTY("IdleActionUSec", "t", NULL, offsetof(Manager, idle_action_usec), SD_BUS_VTABLE_PROPERTY_CONST),
3942 SD_BUS_PROPERTY("PreparingForShutdown", "b", property_get_preparing, 0, 0),
3943 SD_BUS_PROPERTY("PreparingForShutdownWithMetadata", "a{sv}", property_get_preparing_shutdown_with_metadata, 0, 0),
3944 SD_BUS_PROPERTY("PreparingForSleep", "b", property_get_preparing, 0, 0),
3945 SD_BUS_PROPERTY("ScheduledShutdown", "(st)", property_get_scheduled_shutdown, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
3946 SD_BUS_PROPERTY("DesignatedMaintenanceTime", "s", property_get_maintenance_time, 0, SD_BUS_VTABLE_PROPERTY_CONST),
3947 SD_BUS_PROPERTY("Docked", "b", property_get_docked, 0, 0),
3948 SD_BUS_PROPERTY("LidClosed", "b", property_get_lid_closed, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
3949 SD_BUS_PROPERTY("OnExternalPower", "b", property_get_on_external_power, 0, 0),
3950 SD_BUS_PROPERTY("RemoveIPC", "b", bus_property_get_bool, offsetof(Manager, remove_ipc), SD_BUS_VTABLE_PROPERTY_CONST),
3951 SD_BUS_PROPERTY("RuntimeDirectorySize", "t", NULL, offsetof(Manager, runtime_dir_size), SD_BUS_VTABLE_PROPERTY_CONST),
3952 SD_BUS_PROPERTY("RuntimeDirectoryInodesMax", "t", NULL, offsetof(Manager, runtime_dir_inodes), SD_BUS_VTABLE_PROPERTY_CONST),
3953 SD_BUS_PROPERTY("InhibitorsMax", "t", NULL, offsetof(Manager, inhibitors_max), SD_BUS_VTABLE_PROPERTY_CONST),
3954 SD_BUS_PROPERTY("NCurrentInhibitors", "t", property_get_hashmap_size, offsetof(Manager, inhibitors), 0),
3955 SD_BUS_PROPERTY("SessionsMax", "t", NULL, offsetof(Manager, sessions_max), SD_BUS_VTABLE_PROPERTY_CONST),
3956 SD_BUS_PROPERTY("NCurrentSessions", "t", property_get_hashmap_size, offsetof(Manager, sessions), 0),
3957 SD_BUS_PROPERTY("UserTasksMax", "t", property_get_compat_user_tasks_max, 0, SD_BUS_VTABLE_PROPERTY_CONST|SD_BUS_VTABLE_HIDDEN),
3958 SD_BUS_PROPERTY("StopIdleSessionUSec", "t", NULL, offsetof(Manager, stop_idle_session_usec), SD_BUS_VTABLE_PROPERTY_CONST),
3959
3960 SD_BUS_METHOD_WITH_ARGS("GetSession",
3961 SD_BUS_ARGS("s", session_id),
3962 SD_BUS_RESULT("o", object_path),
3963 method_get_session,
3964 SD_BUS_VTABLE_UNPRIVILEGED),
3965 SD_BUS_METHOD_WITH_ARGS("GetSessionByPID",
3966 SD_BUS_ARGS("u", pid),
3967 SD_BUS_RESULT("o", object_path),
3968 method_get_session_by_pid,
3969 SD_BUS_VTABLE_UNPRIVILEGED),
3970 SD_BUS_METHOD_WITH_ARGS("GetUser",
3971 SD_BUS_ARGS("u", uid),
3972 SD_BUS_RESULT("o", object_path),
3973 method_get_user,
3974 SD_BUS_VTABLE_UNPRIVILEGED),
3975 SD_BUS_METHOD_WITH_ARGS("GetUserByPID",
3976 SD_BUS_ARGS("u", pid),
3977 SD_BUS_RESULT("o", object_path),
3978 method_get_user_by_pid,
3979 SD_BUS_VTABLE_UNPRIVILEGED),
3980 SD_BUS_METHOD_WITH_ARGS("GetSeat",
3981 SD_BUS_ARGS("s", seat_id),
3982 SD_BUS_RESULT("o", object_path),
3983 method_get_seat,
3984 SD_BUS_VTABLE_UNPRIVILEGED),
3985 SD_BUS_METHOD_WITH_ARGS("ListSessions",
3986 SD_BUS_NO_ARGS,
3987 SD_BUS_RESULT("a(susso)", sessions),
3988 method_list_sessions,
3989 SD_BUS_VTABLE_UNPRIVILEGED),
3990 SD_BUS_METHOD_WITH_ARGS("ListSessionsEx",
3991 SD_BUS_NO_ARGS,
3992 SD_BUS_RESULT("a(sussussbto)", sessions),
3993 method_list_sessions_ex,
3994 SD_BUS_VTABLE_UNPRIVILEGED),
3995 SD_BUS_METHOD_WITH_ARGS("ListUsers",
3996 SD_BUS_NO_ARGS,
3997 SD_BUS_RESULT("a(uso)", users),
3998 method_list_users,
3999 SD_BUS_VTABLE_UNPRIVILEGED),
4000 SD_BUS_METHOD_WITH_ARGS("ListSeats",
4001 SD_BUS_NO_ARGS,
4002 SD_BUS_RESULT("a(so)", seats),
4003 method_list_seats,
4004 SD_BUS_VTABLE_UNPRIVILEGED),
4005 SD_BUS_METHOD_WITH_ARGS("ListInhibitors",
4006 SD_BUS_NO_ARGS,
4007 SD_BUS_RESULT("a(ssssuu)", inhibitors),
4008 method_list_inhibitors,
4009 SD_BUS_VTABLE_UNPRIVILEGED),
4010 SD_BUS_METHOD_WITH_ARGS("CreateSession",
4011 SD_BUS_ARGS("u", uid,
4012 "u", pid,
4013 "s", service,
4014 "s", type,
4015 "s", class,
4016 "s", desktop,
4017 "s", seat_id,
4018 "u", vtnr,
4019 "s", tty,
4020 "s", display,
4021 "b", remote,
4022 "s", remote_user,
4023 "s", remote_host,
4024 "a(sv)", properties),
4025 SD_BUS_RESULT("s", session_id,
4026 "o", object_path,
4027 "s", runtime_path,
4028 "h", fifo_fd,
4029 "u", uid,
4030 "s", seat_id,
4031 "u", vtnr,
4032 "b", existing),
4033 method_create_session,
4034 0),
4035 SD_BUS_METHOD_WITH_ARGS("CreateSessionWithPIDFD",
4036 SD_BUS_ARGS("u", uid,
4037 "h", pidfd,
4038 "s", service,
4039 "s", type,
4040 "s", class,
4041 "s", desktop,
4042 "s", seat_id,
4043 "u", vtnr,
4044 "s", tty,
4045 "s", display,
4046 "b", remote,
4047 "s", remote_user,
4048 "s", remote_host,
4049 "t", flags,
4050 "a(sv)", properties),
4051 SD_BUS_RESULT("s", session_id,
4052 "o", object_path,
4053 "s", runtime_path,
4054 "h", fifo_fd,
4055 "u", uid,
4056 "s", seat_id,
4057 "u", vtnr,
4058 "b", existing),
4059 method_create_session_pidfd,
4060 0),
4061 SD_BUS_METHOD_WITH_ARGS("ReleaseSession",
4062 SD_BUS_ARGS("s", session_id),
4063 SD_BUS_NO_RESULT,
4064 method_release_session,
4065 SD_BUS_VTABLE_UNPRIVILEGED),
4066 SD_BUS_METHOD_WITH_ARGS("ActivateSession",
4067 SD_BUS_ARGS("s", session_id),
4068 SD_BUS_NO_RESULT,
4069 method_activate_session,
4070 SD_BUS_VTABLE_UNPRIVILEGED),
4071 SD_BUS_METHOD_WITH_ARGS("ActivateSessionOnSeat",
4072 SD_BUS_ARGS("s", session_id, "s", seat_id),
4073 SD_BUS_NO_RESULT,
4074 method_activate_session_on_seat,
4075 SD_BUS_VTABLE_UNPRIVILEGED),
4076 SD_BUS_METHOD_WITH_ARGS("LockSession",
4077 SD_BUS_ARGS("s", session_id),
4078 SD_BUS_NO_RESULT,
4079 method_lock_session,
4080 SD_BUS_VTABLE_UNPRIVILEGED),
4081 SD_BUS_METHOD_WITH_ARGS("UnlockSession",
4082 SD_BUS_ARGS("s", session_id),
4083 SD_BUS_NO_RESULT,
4084 method_lock_session,
4085 SD_BUS_VTABLE_UNPRIVILEGED),
4086 SD_BUS_METHOD("LockSessions",
4087 NULL,
4088 NULL,
4089 method_lock_sessions,
4090 SD_BUS_VTABLE_UNPRIVILEGED),
4091 SD_BUS_METHOD("UnlockSessions",
4092 NULL,
4093 NULL,
4094 method_lock_sessions,
4095 SD_BUS_VTABLE_UNPRIVILEGED),
4096 SD_BUS_METHOD_WITH_ARGS("KillSession",
4097 SD_BUS_ARGS("s", session_id, "s", whom, "i", signal_number),
4098 SD_BUS_NO_RESULT,
4099 method_kill_session,
4100 SD_BUS_VTABLE_UNPRIVILEGED),
4101 SD_BUS_METHOD_WITH_ARGS("KillUser",
4102 SD_BUS_ARGS("u", uid, "i", signal_number),
4103 SD_BUS_NO_RESULT,
4104 method_kill_user,
4105 SD_BUS_VTABLE_UNPRIVILEGED),
4106 SD_BUS_METHOD_WITH_ARGS("TerminateSession",
4107 SD_BUS_ARGS("s", session_id),
4108 SD_BUS_NO_RESULT,
4109 method_terminate_session,
4110 SD_BUS_VTABLE_UNPRIVILEGED),
4111 SD_BUS_METHOD_WITH_ARGS("TerminateUser",
4112 SD_BUS_ARGS("u", uid),
4113 SD_BUS_NO_RESULT,
4114 method_terminate_user,
4115 SD_BUS_VTABLE_UNPRIVILEGED),
4116 SD_BUS_METHOD_WITH_ARGS("TerminateSeat",
4117 SD_BUS_ARGS("s", seat_id),
4118 SD_BUS_NO_RESULT,
4119 method_terminate_seat,
4120 SD_BUS_VTABLE_UNPRIVILEGED),
4121 SD_BUS_METHOD_WITH_ARGS("SetUserLinger",
4122 SD_BUS_ARGS("u", uid, "b", enable, "b", interactive),
4123 SD_BUS_NO_RESULT,
4124 method_set_user_linger,
4125 SD_BUS_VTABLE_UNPRIVILEGED),
4126 SD_BUS_METHOD_WITH_ARGS("AttachDevice",
4127 SD_BUS_ARGS("s", seat_id, "s", sysfs_path, "b", interactive),
4128 SD_BUS_NO_RESULT,
4129 method_attach_device,
4130 SD_BUS_VTABLE_UNPRIVILEGED),
4131 SD_BUS_METHOD_WITH_ARGS("FlushDevices",
4132 SD_BUS_ARGS("b", interactive),
4133 SD_BUS_NO_RESULT,
4134 method_flush_devices,
4135 SD_BUS_VTABLE_UNPRIVILEGED),
4136 SD_BUS_METHOD_WITH_ARGS("PowerOff",
4137 SD_BUS_ARGS("b", interactive),
4138 SD_BUS_NO_RESULT,
4139 method_poweroff,
4140 SD_BUS_VTABLE_UNPRIVILEGED),
4141 SD_BUS_METHOD_WITH_ARGS("PowerOffWithFlags",
4142 SD_BUS_ARGS("t", flags),
4143 SD_BUS_NO_RESULT,
4144 method_poweroff,
4145 SD_BUS_VTABLE_UNPRIVILEGED),
4146 SD_BUS_METHOD_WITH_ARGS("Reboot",
4147 SD_BUS_ARGS("b", interactive),
4148 SD_BUS_NO_RESULT,
4149 method_reboot,
4150 SD_BUS_VTABLE_UNPRIVILEGED),
4151 SD_BUS_METHOD_WITH_ARGS("RebootWithFlags",
4152 SD_BUS_ARGS("t", flags),
4153 SD_BUS_NO_RESULT,
4154 method_reboot,
4155 SD_BUS_VTABLE_UNPRIVILEGED),
4156 SD_BUS_METHOD_WITH_ARGS("Halt",
4157 SD_BUS_ARGS("b", interactive),
4158 SD_BUS_NO_RESULT,
4159 method_halt,
4160 SD_BUS_VTABLE_UNPRIVILEGED),
4161 SD_BUS_METHOD_WITH_ARGS("HaltWithFlags",
4162 SD_BUS_ARGS("t", flags),
4163 SD_BUS_NO_RESULT,
4164 method_halt,
4165 SD_BUS_VTABLE_UNPRIVILEGED),
4166 SD_BUS_METHOD_WITH_ARGS("Suspend",
4167 SD_BUS_ARGS("b", interactive),
4168 SD_BUS_NO_RESULT,
4169 method_suspend,
4170 SD_BUS_VTABLE_UNPRIVILEGED),
4171 SD_BUS_METHOD_WITH_ARGS("SuspendWithFlags",
4172 SD_BUS_ARGS("t", flags),
4173 SD_BUS_NO_RESULT,
4174 method_suspend,
4175 SD_BUS_VTABLE_UNPRIVILEGED),
4176 SD_BUS_METHOD_WITH_ARGS("Hibernate",
4177 SD_BUS_ARGS("b", interactive),
4178 SD_BUS_NO_RESULT,
4179 method_hibernate,
4180 SD_BUS_VTABLE_UNPRIVILEGED),
4181 SD_BUS_METHOD_WITH_ARGS("HibernateWithFlags",
4182 SD_BUS_ARGS("t", flags),
4183 SD_BUS_NO_RESULT,
4184 method_hibernate,
4185 SD_BUS_VTABLE_UNPRIVILEGED),
4186 SD_BUS_METHOD_WITH_ARGS("HybridSleep",
4187 SD_BUS_ARGS("b", interactive),
4188 SD_BUS_NO_RESULT,
4189 method_hybrid_sleep,
4190 SD_BUS_VTABLE_UNPRIVILEGED),
4191 SD_BUS_METHOD_WITH_ARGS("HybridSleepWithFlags",
4192 SD_BUS_ARGS("t", flags),
4193 SD_BUS_NO_RESULT,
4194 method_hybrid_sleep,
4195 SD_BUS_VTABLE_UNPRIVILEGED),
4196 SD_BUS_METHOD_WITH_ARGS("SuspendThenHibernate",
4197 SD_BUS_ARGS("b", interactive),
4198 SD_BUS_NO_RESULT,
4199 method_suspend_then_hibernate,
4200 SD_BUS_VTABLE_UNPRIVILEGED),
4201 SD_BUS_METHOD_WITH_ARGS("SuspendThenHibernateWithFlags",
4202 SD_BUS_ARGS("t", flags),
4203 SD_BUS_NO_RESULT,
4204 method_suspend_then_hibernate,
4205 SD_BUS_VTABLE_UNPRIVILEGED),
4206 SD_BUS_METHOD_WITH_ARGS("Sleep",
4207 SD_BUS_ARGS("t", flags),
4208 SD_BUS_NO_RESULT,
4209 method_sleep,
4210 SD_BUS_VTABLE_UNPRIVILEGED),
4211 SD_BUS_METHOD_WITH_ARGS("CanPowerOff",
4212 SD_BUS_NO_ARGS,
4213 SD_BUS_RESULT("s", result),
4214 method_can_poweroff,
4215 SD_BUS_VTABLE_UNPRIVILEGED),
4216 SD_BUS_METHOD_WITH_ARGS("CanReboot",
4217 SD_BUS_NO_ARGS,
4218 SD_BUS_RESULT("s", result),
4219 method_can_reboot,
4220 SD_BUS_VTABLE_UNPRIVILEGED),
4221 SD_BUS_METHOD_WITH_ARGS("CanHalt",
4222 SD_BUS_NO_ARGS,
4223 SD_BUS_RESULT("s", result),
4224 method_can_halt,
4225 SD_BUS_VTABLE_UNPRIVILEGED),
4226 SD_BUS_METHOD_WITH_ARGS("CanSuspend",
4227 SD_BUS_NO_ARGS,
4228 SD_BUS_RESULT("s", result),
4229 method_can_suspend,
4230 SD_BUS_VTABLE_UNPRIVILEGED),
4231 SD_BUS_METHOD_WITH_ARGS("CanHibernate",
4232 SD_BUS_NO_ARGS,
4233 SD_BUS_RESULT("s", result),
4234 method_can_hibernate,
4235 SD_BUS_VTABLE_UNPRIVILEGED),
4236 SD_BUS_METHOD_WITH_ARGS("CanHybridSleep",
4237 SD_BUS_NO_ARGS,
4238 SD_BUS_RESULT("s", result),
4239 method_can_hybrid_sleep,
4240 SD_BUS_VTABLE_UNPRIVILEGED),
4241 SD_BUS_METHOD_WITH_ARGS("CanSuspendThenHibernate",
4242 SD_BUS_NO_ARGS,
4243 SD_BUS_RESULT("s", result),
4244 method_can_suspend_then_hibernate,
4245 SD_BUS_VTABLE_UNPRIVILEGED),
4246 SD_BUS_METHOD_WITH_ARGS("CanSleep",
4247 SD_BUS_NO_ARGS,
4248 SD_BUS_RESULT("s", result),
4249 method_can_sleep,
4250 SD_BUS_VTABLE_UNPRIVILEGED),
4251 SD_BUS_METHOD_WITH_ARGS("ScheduleShutdown",
4252 SD_BUS_ARGS("s", type, "t", usec),
4253 SD_BUS_NO_RESULT,
4254 method_schedule_shutdown,
4255 SD_BUS_VTABLE_UNPRIVILEGED),
4256 SD_BUS_METHOD_WITH_ARGS("CancelScheduledShutdown",
4257 SD_BUS_NO_ARGS,
4258 SD_BUS_RESULT("b", cancelled),
4259 method_cancel_scheduled_shutdown,
4260 SD_BUS_VTABLE_UNPRIVILEGED),
4261 SD_BUS_METHOD_WITH_ARGS("Inhibit",
4262 SD_BUS_ARGS("s", what, "s", who, "s", why, "s", mode),
4263 SD_BUS_RESULT("h", pipe_fd),
4264 method_inhibit,
4265 SD_BUS_VTABLE_UNPRIVILEGED),
4266 SD_BUS_METHOD_WITH_ARGS("CanRebootParameter",
4267 SD_BUS_NO_ARGS,
4268 SD_BUS_RESULT("s", result),
4269 method_can_reboot_parameter,
4270 SD_BUS_VTABLE_UNPRIVILEGED),
4271 SD_BUS_METHOD_WITH_ARGS("SetRebootParameter",
4272 SD_BUS_ARGS("s", parameter),
4273 SD_BUS_NO_RESULT,
4274 method_set_reboot_parameter,
4275 SD_BUS_VTABLE_UNPRIVILEGED),
4276 SD_BUS_METHOD_WITH_ARGS("CanRebootToFirmwareSetup",
4277 SD_BUS_NO_ARGS,
4278 SD_BUS_RESULT("s", result),
4279 method_can_reboot_to_firmware_setup,
4280 SD_BUS_VTABLE_UNPRIVILEGED),
4281 SD_BUS_METHOD_WITH_ARGS("SetRebootToFirmwareSetup",
4282 SD_BUS_ARGS("b", enable),
4283 SD_BUS_NO_RESULT,
4284 method_set_reboot_to_firmware_setup,
4285 SD_BUS_VTABLE_UNPRIVILEGED),
4286 SD_BUS_METHOD_WITH_ARGS("CanRebootToBootLoaderMenu",
4287 SD_BUS_NO_ARGS,
4288 SD_BUS_RESULT("s", result),
4289 method_can_reboot_to_boot_loader_menu,
4290 SD_BUS_VTABLE_UNPRIVILEGED),
4291 SD_BUS_METHOD_WITH_ARGS("SetRebootToBootLoaderMenu",
4292 SD_BUS_ARGS("t", timeout),
4293 SD_BUS_NO_RESULT,
4294 method_set_reboot_to_boot_loader_menu,
4295 SD_BUS_VTABLE_UNPRIVILEGED),
4296 SD_BUS_METHOD_WITH_ARGS("CanRebootToBootLoaderEntry",
4297 SD_BUS_NO_ARGS,
4298 SD_BUS_RESULT("s", result),
4299 method_can_reboot_to_boot_loader_entry,
4300 SD_BUS_VTABLE_UNPRIVILEGED),
4301 SD_BUS_METHOD_WITH_ARGS("SetRebootToBootLoaderEntry",
4302 SD_BUS_ARGS("s", boot_loader_entry),
4303 SD_BUS_NO_RESULT,
4304 method_set_reboot_to_boot_loader_entry,
4305 SD_BUS_VTABLE_UNPRIVILEGED),
4306 SD_BUS_METHOD_WITH_ARGS("SetWallMessage",
4307 SD_BUS_ARGS("s", wall_message, "b", enable),
4308 SD_BUS_NO_RESULT,
4309 method_set_wall_message,
4310 SD_BUS_VTABLE_UNPRIVILEGED),
4311
4312 SD_BUS_SIGNAL_WITH_ARGS("SecureAttentionKey",
4313 SD_BUS_ARGS("s", seat_id, "o", object_path),
4314 0),
4315 SD_BUS_SIGNAL_WITH_ARGS("SessionNew",
4316 SD_BUS_ARGS("s", session_id, "o", object_path),
4317 0),
4318 SD_BUS_SIGNAL_WITH_ARGS("SessionRemoved",
4319 SD_BUS_ARGS("s", session_id, "o", object_path),
4320 0),
4321 SD_BUS_SIGNAL_WITH_ARGS("UserNew",
4322 SD_BUS_ARGS("u", uid, "o", object_path),
4323 0),
4324 SD_BUS_SIGNAL_WITH_ARGS("UserRemoved",
4325 SD_BUS_ARGS("u", uid, "o", object_path),
4326 0),
4327 SD_BUS_SIGNAL_WITH_ARGS("SeatNew",
4328 SD_BUS_ARGS("s", seat_id, "o", object_path),
4329 0),
4330 SD_BUS_SIGNAL_WITH_ARGS("SeatRemoved",
4331 SD_BUS_ARGS("s", seat_id, "o", object_path),
4332 0),
4333 SD_BUS_SIGNAL_WITH_ARGS("PrepareForShutdown",
4334 SD_BUS_ARGS("b", start),
4335 0),
4336 SD_BUS_SIGNAL_WITH_ARGS("PrepareForShutdownWithMetadata",
4337 SD_BUS_ARGS("b", start, "a{sv}", metadata),
4338 0),
4339 SD_BUS_SIGNAL_WITH_ARGS("PrepareForSleep",
4340 SD_BUS_ARGS("b", start),
4341 0),
4342
4343 SD_BUS_VTABLE_END
4344};
4345
4346const BusObjectImplementation manager_object = {
4347 "/org/freedesktop/login1",
4348 "org.freedesktop.login1.Manager",
4349 .vtables = BUS_VTABLES(manager_vtable),
4350 .children = BUS_IMPLEMENTATIONS(&seat_object,
4351 &session_object,
4352 &user_object),
4353};
4354
4355static void session_jobs_reply(Session *s, uint32_t jid, const char *unit, const char *result) {
4356 assert(s);
4357 assert(unit);
4358
4359 if (!s->started)
4360 return;
4361
4362 if (result && !streq(result, "done")) {
4363 _cleanup_(sd_bus_error_free) sd_bus_error e = SD_BUS_ERROR_NULL;
4364
4365 sd_bus_error_setf(&e, BUS_ERROR_JOB_FAILED,
4366 "Job %u for unit '%s' failed with '%s'", jid, unit, result);
4367
4368 (void) session_send_create_reply(s, &e);
4369 (void) session_send_upgrade_reply(s, &e);
4370 return;
4371 }
4372
4373 (void) session_send_create_reply(s, /* error= */ NULL);
4374 (void) session_send_upgrade_reply(s, /* error= */ NULL);
4375}
4376
4377int match_job_removed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
4378 Manager *m = ASSERT_PTR(userdata);
4379 const char *path, *result, *unit;
4380 uint32_t id;
4381 int r;
4382
4383 assert(message);
4384
4385 r = sd_bus_message_read(message, "uoss", &id, &path, &unit, &result);
4386 if (r < 0) {
4387 bus_log_parse_error(r);
4388 return 0;
4389 }
4390
4391 if (m->action_job && streq(m->action_job, path)) {
4392 assert(m->delayed_action);
4393 log_info("Operation '%s' finished.", handle_action_to_string(m->delayed_action->handle));
4394
4395 /* Tell people that they now may take a lock again */
4396 (void) send_prepare_for(m, m->delayed_action, false);
4397
4398 m->action_job = mfree(m->action_job);
4399 m->delayed_action = NULL;
4400 return 0;
4401 }
4402
4403 Session *session;
4404 User *user;
4405
4406 session = hashmap_get(m->session_units, unit);
4407 if (session) {
4408 if (streq_ptr(path, session->scope_job)) {
4409 session->scope_job = mfree(session->scope_job);
4410 session_jobs_reply(session, id, unit, result);
4411
4412 session_save(session);
4413 user_save(session->user);
4414 }
4415
4416 session_add_to_gc_queue(session);
4417 }
4418
4419 user = hashmap_get(m->user_units, unit);
4420 if (user) {
4421 /* If the user is stopping, we're tracking stop jobs here. So don't send reply. */
4422 if (!user->stopping) {
4423 char **user_job;
4424 FOREACH_ARGUMENT(user_job, &user->runtime_dir_job, &user->service_manager_job)
4425 if (streq_ptr(path, *user_job)) {
4426 *user_job = mfree(*user_job);
4427
4428 LIST_FOREACH(sessions_by_user, s, user->sessions)
4429 /* Don't propagate user service failures to the client */
4430 session_jobs_reply(s, id, unit, /* result = */ NULL);
4431
4432 user_save(user);
4433 break;
4434 }
4435 }
4436
4437 user_add_to_gc_queue(user);
4438 }
4439
4440 return 0;
4441}
4442
4443int match_unit_removed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
4444 const char *path, *unit;
4445 Manager *m = ASSERT_PTR(userdata);
4446 Session *session;
4447 User *user;
4448 int r;
4449
4450 assert(message);
4451
4452 r = sd_bus_message_read(message, "so", &unit, &path);
4453 if (r < 0) {
4454 bus_log_parse_error(r);
4455 return 0;
4456 }
4457
4458 session = hashmap_get(m->session_units, unit);
4459 if (session)
4460 session_add_to_gc_queue(session);
4461
4462 user = hashmap_get(m->user_units, unit);
4463 if (user)
4464 user_add_to_gc_queue(user);
4465
4466 return 0;
4467}
4468
4469int match_properties_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
4470 _cleanup_free_ char *unit = NULL;
4471 Manager *m = ASSERT_PTR(userdata);
4472 const char *path;
4473 Session *session;
4474 User *user;
4475 int r;
4476
4477 assert(message);
4478
4479 path = sd_bus_message_get_path(message);
4480 if (!path)
4481 return 0;
4482
4483 r = unit_name_from_dbus_path(path, &unit);
4484 if (r == -EINVAL) /* not a unit */
4485 return 0;
4486 if (r < 0) {
4487 log_oom();
4488 return 0;
4489 }
4490
4491 session = hashmap_get(m->session_units, unit);
4492 if (session)
4493 session_add_to_gc_queue(session);
4494
4495 user = hashmap_get(m->user_units, unit);
4496 if (user)
4497 user_add_to_gc_queue(user);
4498
4499 return 0;
4500}
4501
4502int match_reloading(sd_bus_message *message, void *userdata, sd_bus_error *error) {
4503 Manager *m = ASSERT_PTR(userdata);
4504 Session *session;
4505 int b, r;
4506
4507 assert(message);
4508
4509 r = sd_bus_message_read(message, "b", &b);
4510 if (r < 0) {
4511 bus_log_parse_error(r);
4512 return 0;
4513 }
4514
4515 if (b)
4516 return 0;
4517
4518 /* systemd finished reloading, let's recheck all our sessions */
4519 log_debug("System manager has been reloaded, rechecking sessions...");
4520
4521 HASHMAP_FOREACH(session, m->sessions)
4522 session_add_to_gc_queue(session);
4523
4524 return 0;
4525}
4526
4527int manager_send_changed_strv(Manager *manager, char **properties) {
4528 assert(manager);
4529
4530 return sd_bus_emit_properties_changed_strv(
4531 manager->bus,
4532 "/org/freedesktop/login1",
4533 "org.freedesktop.login1.Manager",
4534 properties);
4535}
4536
4537int manager_start_scope(
4538 Manager *manager,
4539 const char *scope,
4540 const PidRef *pidref,
4541 bool allow_pidfd,
4542 const char *slice,
4543 const char *description,
4544 const char * const *requires,
4545 const char * const *wants,
4546 const char * const *extra_after,
4547 const char *requires_mounts_for,
4548 sd_bus_message *more_properties,
4549 sd_bus_error *error,
4550 char **ret_job) {
4551
4552 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
4553 _cleanup_(sd_bus_error_free) sd_bus_error e = SD_BUS_ERROR_NULL;
4554 int r;
4555
4556 assert(manager);
4557 assert(scope);
4558 assert(pidref_is_set(pidref));
4559 assert(ret_job);
4560
4561 r = bus_message_new_method_call(manager->bus, &m, bus_systemd_mgr, "StartTransientUnit");
4562 if (r < 0)
4563 return r;
4564
4565 r = sd_bus_message_append(m, "ss", scope, "fail");
4566 if (r < 0)
4567 return r;
4568
4569 r = sd_bus_message_open_container(m, 'a', "(sv)");
4570 if (r < 0)
4571 return r;
4572
4573 if (!isempty(slice)) {
4574 r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
4575 if (r < 0)
4576 return r;
4577 }
4578
4579 if (!isempty(description)) {
4580 r = sd_bus_message_append(m, "(sv)", "Description", "s", description);
4581 if (r < 0)
4582 return r;
4583 }
4584
4585 STRV_FOREACH(i, requires) {
4586 r = sd_bus_message_append(m, "(sv)", "Requires", "as", 1, *i);
4587 if (r < 0)
4588 return r;
4589
4590 r = sd_bus_message_append(m, "(sv)", "After", "as", 1, *i);
4591 if (r < 0)
4592 return r;
4593 }
4594
4595 STRV_FOREACH(i, wants) {
4596 r = sd_bus_message_append(m, "(sv)", "Wants", "as", 1, *i);
4597 if (r < 0)
4598 return r;
4599
4600 r = sd_bus_message_append(m, "(sv)", "After", "as", 1, *i);
4601 if (r < 0)
4602 return r;
4603 }
4604
4605 STRV_FOREACH(i, extra_after) {
4606 r = sd_bus_message_append(m, "(sv)", "After", "as", 1, *i);
4607 if (r < 0)
4608 return r;
4609 }
4610
4611 if (!empty_or_root(requires_mounts_for)) {
4612 r = sd_bus_message_append(m, "(sv)", "RequiresMountsFor", "as", 1, requires_mounts_for);
4613 if (r < 0)
4614 return r;
4615 }
4616
4617 /* Make sure that the session shells are terminated with SIGHUP since bash and friends tend to ignore
4618 * SIGTERM */
4619 r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", true);
4620 if (r < 0)
4621 return r;
4622
4623 r = bus_append_scope_pidref(m, pidref, allow_pidfd);
4624 if (r < 0)
4625 return r;
4626
4627 /* For login session scopes, if a process is OOM killed by the kernel, *don't* terminate the rest of
4628 the scope */
4629 r = sd_bus_message_append(m, "(sv)", "OOMPolicy", "s", "continue");
4630 if (r < 0)
4631 return r;
4632
4633 /* disable TasksMax= for the session scope, rely on the slice setting for it */
4634 r = sd_bus_message_append(m, "(sv)", "TasksMax", "t", UINT64_MAX);
4635 if (r < 0)
4636 return bus_log_create_error(r);
4637
4638 if (more_properties) {
4639 /* If TasksMax also appears here, it will overwrite the default value set above */
4640 r = sd_bus_message_copy(m, more_properties, true);
4641 if (r < 0)
4642 return r;
4643 }
4644
4645 r = sd_bus_message_close_container(m);
4646 if (r < 0)
4647 return r;
4648
4649 r = sd_bus_message_append(m, "a(sa(sv))", 0);
4650 if (r < 0)
4651 return r;
4652
4653 r = sd_bus_call(manager->bus, m, 0, &e, &reply);
4654 if (r < 0) {
4655 /* If this failed with a property we couldn't write, this is quite likely because the server
4656 * doesn't support PIDFDs yet, let's try without. */
4657 if (allow_pidfd &&
4658 sd_bus_error_has_names(&e, SD_BUS_ERROR_UNKNOWN_PROPERTY, SD_BUS_ERROR_PROPERTY_READ_ONLY))
4659 return manager_start_scope(
4660 manager,
4661 scope,
4662 pidref,
4663 /* allow_pidfd = */ false,
4664 slice,
4665 description,
4666 requires,
4667 wants,
4668 extra_after,
4669 requires_mounts_for,
4670 more_properties,
4671 error,
4672 ret_job);
4673
4674 return sd_bus_error_move(error, &e);
4675 }
4676
4677 return strdup_job(reply, ret_job);
4678}
4679
4680int manager_start_unit(Manager *manager, const char *unit, sd_bus_error *error, char **ret_job) {
4681 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4682 int r;
4683
4684 assert(manager);
4685 assert(unit);
4686 assert(ret_job);
4687
4688 r = bus_call_method(
4689 manager->bus,
4690 bus_systemd_mgr,
4691 "StartUnit",
4692 error,
4693 &reply,
4694 "ss", unit, "replace");
4695 if (r < 0)
4696 return r;
4697
4698 return strdup_job(reply, ret_job);
4699}
4700
4701int manager_stop_unit(
4702 Manager *manager,
4703 const char *unit,
4704 const char *job_mode,
4705 sd_bus_error *ret_error,
4706 char **ret_job) {
4707
4708 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4709 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4710 int r;
4711
4712 assert(manager);
4713 assert(unit);
4714 assert(ret_job);
4715
4716 r = bus_call_method(
4717 manager->bus,
4718 bus_systemd_mgr,
4719 "StopUnit",
4720 &error,
4721 &reply,
4722 "ss", unit, job_mode ?: "fail");
4723 if (r < 0) {
4724 if (sd_bus_error_has_names(&error, BUS_ERROR_NO_SUCH_UNIT, BUS_ERROR_LOAD_FAILED)) {
4725 *ret_job = NULL;
4726 return 0;
4727 }
4728
4729 sd_bus_error_move(ret_error, &error);
4730 return r;
4731 }
4732
4733 r = strdup_job(reply, ret_job);
4734 if (r < 0)
4735 return r;
4736
4737 return 1;
4738}
4739
4740int manager_abandon_scope(Manager *manager, const char *scope, sd_bus_error *ret_error) {
4741 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4742 _cleanup_free_ char *path = NULL;
4743 int r;
4744
4745 assert(manager);
4746 assert(scope);
4747
4748 path = unit_dbus_path_from_name(scope);
4749 if (!path)
4750 return -ENOMEM;
4751
4752 r = sd_bus_call_method(
4753 manager->bus,
4754 "org.freedesktop.systemd1",
4755 path,
4756 "org.freedesktop.systemd1.Scope",
4757 "Abandon",
4758 &error,
4759 NULL,
4760 NULL);
4761 if (r < 0) {
4762 if (sd_bus_error_has_names(&error, BUS_ERROR_NO_SUCH_UNIT,
4763 BUS_ERROR_LOAD_FAILED,
4764 BUS_ERROR_SCOPE_NOT_RUNNING))
4765 return 0;
4766
4767 sd_bus_error_move(ret_error, &error);
4768 return r;
4769 }
4770
4771 return 1;
4772}
4773
4774int manager_kill_unit(Manager *manager, const char *unit, KillWhom whom, int signo, sd_bus_error *error) {
4775 assert(manager);
4776 assert(unit);
4777 assert(SIGNAL_VALID(signo));
4778
4779 return bus_call_method(
4780 manager->bus,
4781 bus_systemd_mgr,
4782 "KillUnit",
4783 error,
4784 NULL,
4785 "ssi",
4786 unit,
4787 whom == KILL_LEADER ? "main" : "all",
4788 signo);
4789}
4790
4791int manager_unit_is_active(Manager *manager, const char *unit, sd_bus_error *ret_error) {
4792 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4793 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4794 _cleanup_free_ char *path = NULL;
4795 const char *state;
4796 int r;
4797
4798 assert(manager);
4799 assert(unit);
4800
4801 path = unit_dbus_path_from_name(unit);
4802 if (!path)
4803 return -ENOMEM;
4804
4805 r = sd_bus_get_property(
4806 manager->bus,
4807 "org.freedesktop.systemd1",
4808 path,
4809 "org.freedesktop.systemd1.Unit",
4810 "ActiveState",
4811 &error,
4812 &reply,
4813 "s");
4814 if (r < 0) {
4815 /* systemd might have dropped off momentarily, let's
4816 * not make this an error */
4817 if (bus_error_is_connection(&error))
4818 return true;
4819
4820 /* If the unit is already unloaded then it's not
4821 * active */
4822 if (sd_bus_error_has_names(&error, BUS_ERROR_NO_SUCH_UNIT,
4823 BUS_ERROR_LOAD_FAILED))
4824 return false;
4825
4826 sd_bus_error_move(ret_error, &error);
4827 return r;
4828 }
4829
4830 r = sd_bus_message_read(reply, "s", &state);
4831 if (r < 0)
4832 return r;
4833
4834 return !STR_IN_SET(state, "inactive", "failed");
4835}
4836
4837int manager_job_is_active(Manager *manager, const char *path, sd_bus_error *ret_error) {
4838 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4839 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
4840 int r;
4841
4842 assert(manager);
4843 assert(path);
4844
4845 r = sd_bus_get_property(
4846 manager->bus,
4847 "org.freedesktop.systemd1",
4848 path,
4849 "org.freedesktop.systemd1.Job",
4850 "State",
4851 &error,
4852 &reply,
4853 "s");
4854 if (r < 0) {
4855 if (bus_error_is_connection(&error))
4856 return true;
4857
4858 if (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_OBJECT))
4859 return false;
4860
4861 sd_bus_error_move(ret_error, &error);
4862 return r;
4863 }
4864
4865 /* We don't actually care about the state really. The fact
4866 * that we could read the job state is enough for us */
4867
4868 return true;
4869}