chiark / gitweb /
7f0f706763d6be240396b9a67d9b4a2b63e05d4f
[elogind.git] / src / login / elogind-dbus.c
1 /***
2   This file is part of elogind.
3
4   Copyright 2017 Sven Eden
5
6   elogind is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   elogind is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with elogind; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20
21 #include "bus-common-errors.h"
22 #include "bus-error.h"
23 #include "bus-util.h"
24 #include "elogind-dbus.h"
25 #include "fd-util.h"
26 #include "process-util.h"
27 #include "sd-messages.h"
28 #include "sleep.h"
29 #include "sleep-config.h"
30 #include "string-util.h"
31 #include "strv.h"
32 #include "update-utmp.h"
33 #include "user-util.h"
34
35
36 int have_multiple_sessions(
37                 Manager *m,
38                 uid_t uid) {
39
40         Session *session;
41         Iterator i;
42
43         assert(m);
44
45         /* Check for other users' sessions. Greeter sessions do not
46          * count, and non-login sessions do not count either. */
47         HASHMAP_FOREACH(session, m->sessions, i)
48                 if (session->class == SESSION_USER &&
49                     session->user->uid != uid)
50                         return true;
51
52         return false;
53 }
54
55 static int bus_manager_log_shutdown(
56                 Manager *m,
57                 InhibitWhat w,
58                 HandleAction action) {
59
60          const char *p, *q;
61
62          assert(m);
63
64          if (w != INHIBIT_SHUTDOWN)
65                  return 0;
66
67          switch (action) {
68          case HANDLE_POWEROFF:
69                  p = "MESSAGE=System is powering down.";
70                  q = "SHUTDOWN=power-off";
71                  break;
72          case HANDLE_HALT:
73                  p = "MESSAGE=System is halting.";
74                  q = "SHUTDOWN=halt";
75                  break;
76          case HANDLE_REBOOT:
77                  p = "MESSAGE=System is rebooting.";
78                  q = "SHUTDOWN=reboot";
79                  break;
80          case HANDLE_KEXEC:
81                  p = "MESSAGE=System is rebooting with kexec.";
82                  q = "SHUTDOWN=kexec";
83                  break;
84          default:
85                  p = "MESSAGE=System is shutting down.";
86                  q = NULL;
87          }
88
89         if (isempty(m->wall_message))
90                 p = strjoina(p, ".");
91         else
92                 p = strjoina(p, " (", m->wall_message, ").");
93
94         return log_struct(LOG_NOTICE,
95                           "MESSAGE_ID=" SD_MESSAGE_SHUTDOWN_STR,
96                           p,
97                           q,
98                           NULL);
99 }
100
101 static int send_prepare_for(Manager *m, InhibitWhat w, bool _active) {
102
103         static const char * const signal_name[_INHIBIT_WHAT_MAX] = {
104                 [INHIBIT_SHUTDOWN] = "PrepareForShutdown",
105                 [INHIBIT_SLEEP] = "PrepareForSleep"
106         };
107
108         int active = _active;
109
110         assert(m);
111         assert(w >= 0);
112         assert(w < _INHIBIT_WHAT_MAX);
113         assert(signal_name[w]);
114
115         return sd_bus_emit_signal(m->bus,
116                                   "/org/freedesktop/login1",
117                                   "org.freedesktop.login1.Manager",
118                                   signal_name[w],
119                                   "b",
120                                   active);
121 }
122
123 /* elogind specific helper to make HALT and REBOOT possible. */
124 static int run_helper(const char *helper) {
125         int pid = fork();
126         if (pid < 0) {
127                 return log_error_errno(errno, "Failed to fork: %m");
128         }
129
130         if (pid == 0) {
131                 /* Child */
132
133                 close_all_fds(NULL, 0);
134
135                 execlp(helper, helper, NULL);
136                 log_error_errno(errno, "Failed to execute %s: %m", helper);
137                 _exit(EXIT_FAILURE);
138         }
139
140         return wait_for_terminate_and_warn(helper, pid, true);
141 }
142
143 /* elogind specific executor */
144 static int shutdown_or_sleep(Manager *m, HandleAction action) {
145
146         assert(m);
147
148         switch (action) {
149         case HANDLE_POWEROFF:
150                 return run_helper(HALT);
151         case HANDLE_REBOOT:
152                 return run_helper(REBOOT);
153         case HANDLE_HALT:
154                 return run_helper(HALT);
155         case HANDLE_KEXEC:
156                 return run_helper(KEXEC);
157         case HANDLE_SUSPEND:
158                 return do_sleep("suspend", m->suspend_mode, m->suspend_state);
159         case HANDLE_HIBERNATE:
160                 return do_sleep("hibernate", m->hibernate_mode, m->hibernate_state);
161         case HANDLE_HYBRID_SLEEP:
162                 return do_sleep("hybrid-sleep", m->hybrid_sleep_mode, m->hybrid_sleep_state);
163         default:
164                 return -EINVAL;
165         }
166 }
167
168 static int execute_shutdown_or_sleep(
169                 Manager *m,
170                 InhibitWhat w,
171                 HandleAction action,
172                 sd_bus_error *error) {
173
174         char** argv_utmp = NULL;
175         int r;
176
177         assert(m);
178         assert(w >= 0);
179         assert(w < _INHIBIT_WHAT_MAX);
180
181         bus_manager_log_shutdown(m, w, action);
182
183         if (IN_SET(action, HANDLE_HALT, HANDLE_POWEROFF, HANDLE_REBOOT)) {
184
185                 /* As we have no systemd update-utmp daemon running, we have to
186                  * set the relevant utmp/wtmp entries ourselves.
187                  */
188
189                 if (strv_extend(&argv_utmp, "elogind") < 0)
190                         return log_oom();
191
192                 if (HANDLE_REBOOT == action) {
193                         if (strv_extend(&argv_utmp, "reboot") < 0)
194                                 return log_oom();
195                 } else {
196                         if (strv_extend(&argv_utmp, "shutdown") < 0)
197                                 return log_oom();
198                 }
199
200                  /* This comes from our patched update-utmp/update-utmp.c */
201                 update_utmp(2, argv_utmp, m->bus);
202                 strv_free(argv_utmp);
203         }
204
205         /* Now perform the requested action */
206         r = shutdown_or_sleep(m, action);
207
208         /* no more pending actions, whether this failed or not */
209         m->pending_action = HANDLE_IGNORE;
210
211         /* As elogind can not rely on a systemd manager to call all
212          * sleeping processes to wake up, we have to tell them all
213          * by ourselves. */
214         if (w == INHIBIT_SLEEP) {
215                 send_prepare_for(m, w, false);
216                 m->action_what = 0;
217         } else
218                 m->action_what = w;
219
220         if (r < 0)
221                 return r;
222
223         /* Make sure the lid switch is ignored for a while */
224         manager_set_lid_switch_ignore(m, now(CLOCK_MONOTONIC) + m->holdoff_timeout_usec);
225
226         return 0;
227 }
228
229 int manager_dispatch_delayed(Manager *manager, bool timeout) {
230
231         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
232         Inhibitor *offending = NULL;
233         int r;
234
235         assert(manager);
236
237         if ( (0 == manager->action_what) || (HANDLE_IGNORE == manager->pending_action) )
238                 return 0;
239
240         if (manager_is_inhibited(manager, manager->action_what, INHIBIT_DELAY, NULL, false, false, 0, &offending)) {
241                 _cleanup_free_ char *comm = NULL, *u = NULL;
242
243                 if (!timeout)
244                         return 0;
245
246                 (void) get_process_comm(offending->pid, &comm);
247                 u = uid_to_name(offending->uid);
248
249                 log_notice("Delay lock is active (UID "UID_FMT"/%s, PID "PID_FMT"/%s) but inhibitor timeout is reached.",
250                            offending->uid, strna(u),
251                            offending->pid, strna(comm));
252         }
253
254         /* Actually do the operation */
255         r = execute_shutdown_or_sleep(manager, manager->action_what, manager->pending_action, &error);
256         if (r < 0) {
257                 log_warning("Failed to send delayed message: %s", bus_error_message(&error, r));
258
259                 manager->pending_action = HANDLE_IGNORE;
260                 manager->action_what    = 0;
261                 /* It is not a critical error for elogind if suspending fails */
262         }
263
264         return 1;
265 }
266
267 static int manager_inhibit_timeout_handler(
268                         sd_event_source *s,
269                         uint64_t usec,
270                         void *userdata) {
271
272         Manager *manager = userdata;
273         int r;
274
275         assert(manager);
276         assert(manager->inhibit_timeout_source == s);
277
278         r = manager_dispatch_delayed(manager, true);
279         return (r < 0) ? r : 0;
280 }
281
282 static int delay_shutdown_or_sleep(
283                 Manager *m,
284                 InhibitWhat w,
285                 HandleAction action) {
286
287         int r;
288         usec_t timeout_val;
289
290         assert(m);
291         assert(w >= 0);
292         assert(w < _INHIBIT_WHAT_MAX);
293
294         timeout_val = now(CLOCK_MONOTONIC) + m->inhibit_delay_max;
295
296         if (m->inhibit_timeout_source) {
297                 r = sd_event_source_set_time(m->inhibit_timeout_source, timeout_val);
298                 if (r < 0)
299                         return log_error_errno(r, "sd_event_source_set_time() failed: %m");
300
301                 r = sd_event_source_set_enabled(m->inhibit_timeout_source, SD_EVENT_ONESHOT);
302                 if (r < 0)
303                         return log_error_errno(r, "sd_event_source_set_enabled() failed: %m");
304         } else {
305                 r = sd_event_add_time(m->event, &m->inhibit_timeout_source, CLOCK_MONOTONIC,
306                                       timeout_val, 0, manager_inhibit_timeout_handler, m);
307                 if (r < 0)
308                         return r;
309         }
310
311         m->pending_action = action;
312         m->action_what = w;
313
314         return 0;
315 }
316
317 int bus_manager_shutdown_or_sleep_now_or_later(
318                 Manager *m,
319                 HandleAction action,
320                 InhibitWhat w,
321                 sd_bus_error *error) {
322
323         bool delayed;
324         int r;
325
326         assert(m);
327         assert(w >= 0);
328         assert(w <= _INHIBIT_WHAT_MAX);
329
330         /* Tell everybody to prepare for shutdown/sleep */
331         send_prepare_for(m, w, true);
332
333         delayed =
334                 m->inhibit_delay_max > 0 &&
335                 manager_is_inhibited(m, w, INHIBIT_DELAY, NULL, false, false, 0, NULL);
336
337         log_debug_elogind("%s called for %s (%sdelayed)", __FUNCTION__,
338                           handle_action_to_string(action),
339                           delayed ? "" : "NOT ");
340
341         if (delayed)
342                 /* Shutdown is delayed, keep in mind what we
343                  * want to do, and start a timeout */
344                 r = delay_shutdown_or_sleep(m, w, action);
345         else
346                 /* Shutdown is not delayed, execute it
347                  * immediately */
348                 r = execute_shutdown_or_sleep(m, w, action, error);
349
350         return r;
351 }
352
353 int verify_shutdown_creds(
354                 Manager *m,
355                 sd_bus_message *message,
356                 InhibitWhat w,
357                 bool interactive,
358                 const char *action,
359                 const char *action_multiple_sessions,
360                 const char *action_ignore_inhibit,
361                 sd_bus_error *error) {
362
363         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
364         bool multiple_sessions, blocked;
365         uid_t uid;
366         int r;
367
368         assert(m);
369         assert(message);
370         assert(w >= 0);
371         assert(w <= _INHIBIT_WHAT_MAX);
372
373         r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
374         if (r < 0)
375                 return r;
376
377         r = sd_bus_creds_get_euid(creds, &uid);
378         if (r < 0)
379                 return r;
380
381         r = have_multiple_sessions(m, uid);
382         if (r < 0)
383                 return r;
384
385         multiple_sessions = r > 0;
386         blocked = manager_is_inhibited(m, w, INHIBIT_BLOCK, NULL, false, true, uid, NULL);
387
388         if (multiple_sessions && action_multiple_sessions) {
389                 r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action_multiple_sessions, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
390                 if (r < 0)
391                         return r;
392                 if (r == 0)
393                         return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
394         }
395
396         if (blocked && action_ignore_inhibit) {
397                 r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action_ignore_inhibit, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
398                 if (r < 0)
399                         return r;
400                 if (r == 0)
401                         return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
402         }
403
404         if (!multiple_sessions && !blocked && action) {
405                 r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
406                 if (r < 0)
407                         return r;
408                 if (r == 0)
409                         return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
410         }
411
412         return 0;
413 }
414
415 static int method_do_shutdown_or_sleep(
416                 Manager *m,
417                 sd_bus_message *message,
418                 HandleAction sleep_action,
419                 InhibitWhat w,
420                 const char *action,
421                 const char *action_multiple_sessions,
422                 const char *action_ignore_inhibit,
423                 const char *sleep_verb,
424                 sd_bus_error *error) {
425
426         int interactive, r;
427
428         assert(m);
429         assert(message);
430         assert(w >= 0);
431         assert(w <= _INHIBIT_WHAT_MAX);
432
433         r = sd_bus_message_read(message, "b", &interactive);
434         if (r < 0)
435                 return r;
436
437         log_debug_elogind("%s called with action '%s', sleep '%s' (%sinteractive)",
438                           __FUNCTION__, action, sleep_verb,
439                           interactive ? "" : "NOT ");
440
441         /* Don't allow multiple jobs being executed at the same time */
442         if (m->action_what)
443                 return sd_bus_error_setf(error, BUS_ERROR_OPERATION_IN_PROGRESS, "There's already a shutdown or sleep operation in progress");
444
445         if (sleep_verb) {
446                 r = can_sleep(m, sleep_verb);
447                 if (r < 0)
448                         return r;
449
450                 if (r == 0)
451                         return sd_bus_error_setf(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED, "Sleep verb not supported");
452         }
453
454         if (IN_SET(sleep_action, HANDLE_HALT, HANDLE_POWEROFF, HANDLE_REBOOT)) {
455                 r = verify_shutdown_creds(m, message, w, interactive, action, action_multiple_sessions,
456                                           action_ignore_inhibit, error);
457                 log_debug_elogind("verify_shutdown_creds() returned %d", r);
458                 if (r != 0)
459                         return r;
460         }
461
462         r = bus_manager_shutdown_or_sleep_now_or_later(m, sleep_action, w, error);
463         if (r < 0)
464                 return r;
465
466         return sd_bus_reply_method_return(message, NULL);
467 }
468
469 int method_poweroff(sd_bus_message *message, void *userdata, sd_bus_error *error) {
470         Manager *m = userdata;
471
472         log_debug_elogind("%s called", __FUNCTION__);
473
474         return method_do_shutdown_or_sleep(
475                         m, message,
476                         HANDLE_POWEROFF,
477                         INHIBIT_SHUTDOWN,
478                         "org.freedesktop.login1.power-off",
479                         "org.freedesktop.login1.power-off-multiple-sessions",
480                         "org.freedesktop.login1.power-off-ignore-inhibit",
481                         NULL,
482                         error);
483 }
484
485 int method_reboot(sd_bus_message *message, void *userdata, sd_bus_error *error) {
486         Manager *m = userdata;
487
488         log_debug_elogind("%s called", __FUNCTION__);
489
490         return method_do_shutdown_or_sleep(
491                         m, message,
492                         HANDLE_REBOOT,
493                         INHIBIT_SHUTDOWN,
494                         "org.freedesktop.login1.reboot",
495                         "org.freedesktop.login1.reboot-multiple-sessions",
496                         "org.freedesktop.login1.reboot-ignore-inhibit",
497                         NULL,
498                         error);
499 }
500
501 int method_suspend(sd_bus_message *message, void *userdata, sd_bus_error *error) {
502         Manager *m = userdata;
503
504         log_debug_elogind("%s called", __FUNCTION__);
505
506         return method_do_shutdown_or_sleep(
507                         m, message,
508                         HANDLE_SUSPEND,
509                         INHIBIT_SLEEP,
510                         "org.freedesktop.login1.suspend",
511                         "org.freedesktop.login1.suspend-multiple-sessions",
512                         "org.freedesktop.login1.suspend-ignore-inhibit",
513                         "suspend",
514                         error);
515 }
516
517 int manager_scheduled_shutdown_handler(
518                         sd_event_source *s,
519                         uint64_t usec,
520                         void *userdata) {
521
522         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
523         Manager *m = userdata;
524         HandleAction action;
525         int r;
526
527         assert(m);
528
529         if (isempty(m->scheduled_shutdown_type))
530                 return 0;
531
532         if (streq(m->scheduled_shutdown_type, "halt"))
533                 action = HANDLE_HALT;
534         else if (streq(m->scheduled_shutdown_type, "poweroff"))
535                 action = HANDLE_POWEROFF;
536         else
537                 action = HANDLE_REBOOT;
538
539         r = execute_shutdown_or_sleep(m, 0, action, &error);
540         if (r < 0)
541                 return log_error_errno(r, "Unable to execute transition to %s: %m", m->scheduled_shutdown_type);
542
543         return 0;
544 }
545
546 int method_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
547         Manager *m = userdata;
548
549         log_debug_elogind("%s called", __FUNCTION__);
550
551         return method_do_shutdown_or_sleep(
552                         m, message,
553                         HANDLE_HIBERNATE,
554                         INHIBIT_SLEEP,
555                         "org.freedesktop.login1.hibernate",
556                         "org.freedesktop.login1.hibernate-multiple-sessions",
557                         "org.freedesktop.login1.hibernate-ignore-inhibit",
558                         "hibernate",
559                         error);
560 }
561
562 int method_hybrid_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
563         Manager *m = userdata;
564
565         log_debug_elogind("%s called", __FUNCTION__);
566
567         return method_do_shutdown_or_sleep(
568                         m, message,
569                         HANDLE_HYBRID_SLEEP,
570                         INHIBIT_SLEEP,
571                         "org.freedesktop.login1.hibernate",
572                         "org.freedesktop.login1.hibernate-multiple-sessions",
573                         "org.freedesktop.login1.hibernate-ignore-inhibit",
574                         "hybrid-sleep",
575                         error);
576 }