chiark / gitweb /
Prep v230: Apply missing upstream fixes and updates (6/8) src/login.
[elogind.git] / src / login / logind-dbus.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2011 Lennart Poettering
5
6   systemd 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   systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <pwd.h>
22 #include <string.h>
23 #include <unistd.h>
24
25 #include "sd-messages.h"
26
27 #include "alloc-util.h"
28 #include "audit-util.h"
29 #include "bus-common-errors.h"
30 #include "bus-error.h"
31 #include "bus-util.h"
32 #include "dirent-util.h"
33 //#include "efivars.h"
34 #include "escape.h"
35 #include "fd-util.h"
36 #include "fileio-label.h"
37 #include "formats-util.h"
38 #include "fs-util.h"
39 #include "logind.h"
40 #include "mkdir.h"
41 #include "path-util.h"
42 #include "process-util.h"
43 #include "selinux-util.h"
44 //#include "sleep-config.h"
45 //#include "special.h"
46 #include "strv.h"
47 #include "terminal-util.h"
48 #include "udev-util.h"
49 #include "unit-name.h"
50 #include "user-util.h"
51 //#include "utmp-wtmp.h"
52
53 int manager_get_session_from_creds(Manager *m, sd_bus_message *message, const char *name, sd_bus_error *error, Session **ret) {
54         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
55         Session *session;
56         int r;
57
58         assert(m);
59         assert(message);
60         assert(ret);
61
62         if (isempty(name)) {
63                 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_SESSION|SD_BUS_CREDS_AUGMENT, &creds);
64                 if (r < 0)
65                         return r;
66
67                 r = sd_bus_creds_get_session(creds, &name);
68                 if (r < 0)
69                         return r;
70         }
71
72         session = hashmap_get(m->sessions, name);
73         if (!session)
74                 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SESSION, "No session '%s' known", name);
75
76         *ret = session;
77         return 0;
78 }
79
80 int manager_get_user_from_creds(Manager *m, sd_bus_message *message, uid_t uid, sd_bus_error *error, User **ret) {
81         User *user;
82         int r;
83
84         assert(m);
85         assert(message);
86         assert(ret);
87
88         if (uid == UID_INVALID) {
89                 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
90
91                 /* Note that we get the owner UID of the session, not the actual client UID here! */
92                 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_OWNER_UID|SD_BUS_CREDS_AUGMENT, &creds);
93                 if (r < 0)
94                         return r;
95
96                 r = sd_bus_creds_get_owner_uid(creds, &uid);
97                 if (r < 0)
98                         return r;
99         }
100
101         user = hashmap_get(m->users, UID_TO_PTR(uid));
102         if (!user)
103                 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_USER, "No user "UID_FMT" known or logged in", uid);
104
105         *ret = user;
106         return 0;
107 }
108
109 int manager_get_seat_from_creds(Manager *m, sd_bus_message *message, const char *name, sd_bus_error *error, Seat **ret) {
110         Seat *seat;
111         int r;
112
113         assert(m);
114         assert(message);
115         assert(ret);
116
117         if (isempty(name)) {
118                 Session *session;
119
120                 r = manager_get_session_from_creds(m, message, NULL, error, &session);
121                 if (r < 0)
122                         return r;
123
124                 seat = session->seat;
125                 if (!seat)
126                         return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT, "Session has no seat.");
127         } else {
128                 seat = hashmap_get(m->seats, name);
129                 if (!seat)
130                         return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT, "No seat '%s' known", name);
131         }
132
133         *ret = seat;
134         return 0;
135 }
136
137 static int property_get_idle_hint(
138                 sd_bus *bus,
139                 const char *path,
140                 const char *interface,
141                 const char *property,
142                 sd_bus_message *reply,
143                 void *userdata,
144                 sd_bus_error *error) {
145
146         Manager *m = userdata;
147
148         assert(bus);
149         assert(reply);
150         assert(m);
151
152         return sd_bus_message_append(reply, "b", manager_get_idle_hint(m, NULL) > 0);
153 }
154
155 static int property_get_idle_since_hint(
156                 sd_bus *bus,
157                 const char *path,
158                 const char *interface,
159                 const char *property,
160                 sd_bus_message *reply,
161                 void *userdata,
162                 sd_bus_error *error) {
163
164         Manager *m = userdata;
165         dual_timestamp t = DUAL_TIMESTAMP_NULL;
166
167         assert(bus);
168         assert(reply);
169         assert(m);
170
171         manager_get_idle_hint(m, &t);
172
173         return sd_bus_message_append(reply, "t", streq(property, "IdleSinceHint") ? t.realtime : t.monotonic);
174 }
175
176 static int property_get_inhibited(
177                 sd_bus *bus,
178                 const char *path,
179                 const char *interface,
180                 const char *property,
181                 sd_bus_message *reply,
182                 void *userdata,
183                 sd_bus_error *error) {
184
185         Manager *m = userdata;
186         InhibitWhat w;
187
188         assert(bus);
189         assert(reply);
190         assert(m);
191
192         w = manager_inhibit_what(m, streq(property, "BlockInhibited") ? INHIBIT_BLOCK : INHIBIT_DELAY);
193
194         return sd_bus_message_append(reply, "s", inhibit_what_to_string(w));
195 }
196
197 static int property_get_preparing(
198                 sd_bus *bus,
199                 const char *path,
200                 const char *interface,
201                 const char *property,
202                 sd_bus_message *reply,
203                 void *userdata,
204                 sd_bus_error *error) {
205
206         Manager *m = userdata;
207         bool b;
208
209         assert(bus);
210         assert(reply);
211         assert(m);
212
213         if (streq(property, "PreparingForShutdown"))
214                 b = !!(m->action_what & INHIBIT_SHUTDOWN);
215         else
216                 b = !!(m->action_what & INHIBIT_SLEEP);
217
218         return sd_bus_message_append(reply, "b", b);
219 }
220
221 static int property_get_scheduled_shutdown(
222                 sd_bus *bus,
223                 const char *path,
224                 const char *interface,
225                 const char *property,
226                 sd_bus_message *reply,
227                 void *userdata,
228                 sd_bus_error *error) {
229
230         Manager *m = userdata;
231         int r;
232
233         assert(bus);
234         assert(reply);
235         assert(m);
236
237         r = sd_bus_message_open_container(reply, 'r', "st");
238         if (r < 0)
239                 return r;
240
241         r = sd_bus_message_append(reply, "st", m->scheduled_shutdown_type, m->scheduled_shutdown_timeout);
242         if (r < 0)
243                 return r;
244
245         return sd_bus_message_close_container(reply);
246 }
247
248 static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_handle_action, handle_action, HandleAction);
249
250 static int property_get_docked(
251                 sd_bus *bus,
252                 const char *path,
253                 const char *interface,
254                 const char *property,
255                 sd_bus_message *reply,
256                 void *userdata,
257                 sd_bus_error *error) {
258
259         Manager *m = userdata;
260
261         assert(bus);
262         assert(reply);
263         assert(m);
264
265         return sd_bus_message_append(reply, "b", manager_is_docked_or_external_displays(m));
266 }
267
268 static int property_get_current_sessions(
269                 sd_bus *bus,
270                 const char *path,
271                 const char *interface,
272                 const char *property,
273                 sd_bus_message *reply,
274                 void *userdata,
275                 sd_bus_error *error) {
276
277         Manager *m = userdata;
278
279         assert(bus);
280         assert(reply);
281         assert(m);
282
283         return sd_bus_message_append(reply, "t", (uint64_t) hashmap_size(m->sessions));
284 }
285
286 static int property_get_current_inhibitors(
287                 sd_bus *bus,
288                 const char *path,
289                 const char *interface,
290                 const char *property,
291                 sd_bus_message *reply,
292                 void *userdata,
293                 sd_bus_error *error) {
294
295         Manager *m = userdata;
296
297         assert(bus);
298         assert(reply);
299         assert(m);
300
301         return sd_bus_message_append(reply, "t", (uint64_t) hashmap_size(m->inhibitors));
302 }
303
304 static int method_get_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
305         _cleanup_free_ char *p = NULL;
306         Manager *m = userdata;
307         const char *name;
308         Session *session;
309         int r;
310
311         assert(message);
312         assert(m);
313
314         r = sd_bus_message_read(message, "s", &name);
315         if (r < 0)
316                 return r;
317
318         r = manager_get_session_from_creds(m, message, name, error, &session);
319         if (r < 0)
320                 return r;
321
322         p = session_bus_path(session);
323         if (!p)
324                 return -ENOMEM;
325
326         return sd_bus_reply_method_return(message, "o", p);
327 }
328
329 static int method_get_session_by_pid(sd_bus_message *message, void *userdata, sd_bus_error *error) {
330         _cleanup_free_ char *p = NULL;
331         Session *session = NULL;
332         Manager *m = userdata;
333         pid_t pid;
334         int r;
335
336         assert(message);
337         assert(m);
338
339         assert_cc(sizeof(pid_t) == sizeof(uint32_t));
340
341         r = sd_bus_message_read(message, "u", &pid);
342         if (r < 0)
343                 return r;
344         if (pid < 0)
345                 return -EINVAL;
346
347         if (pid == 0) {
348                 r = manager_get_session_from_creds(m, message, NULL, error, &session);
349                 if (r < 0)
350                         return r;
351         } else {
352                 r = manager_get_session_by_pid(m, pid, &session);
353                 if (r < 0)
354                         return r;
355
356                 if (!session)
357                         return sd_bus_error_setf(error, BUS_ERROR_NO_SESSION_FOR_PID, "PID "PID_FMT" does not belong to any known session", pid);
358         }
359
360         p = session_bus_path(session);
361         if (!p)
362                 return -ENOMEM;
363
364         return sd_bus_reply_method_return(message, "o", p);
365 }
366
367 static int method_get_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
368         _cleanup_free_ char *p = NULL;
369         Manager *m = userdata;
370         uint32_t uid;
371         User *user;
372         int r;
373
374         assert(message);
375         assert(m);
376
377         r = sd_bus_message_read(message, "u", &uid);
378         if (r < 0)
379                 return r;
380
381         r = manager_get_user_from_creds(m, message, uid, error, &user);
382         if (r < 0)
383                 return r;
384
385         p = user_bus_path(user);
386         if (!p)
387                 return -ENOMEM;
388
389         return sd_bus_reply_method_return(message, "o", p);
390 }
391
392 static int method_get_user_by_pid(sd_bus_message *message, void *userdata, sd_bus_error *error) {
393         _cleanup_free_ char *p = NULL;
394         Manager *m = userdata;
395         User *user = NULL;
396         pid_t pid;
397         int r;
398
399         assert(message);
400         assert(m);
401
402         assert_cc(sizeof(pid_t) == sizeof(uint32_t));
403
404         r = sd_bus_message_read(message, "u", &pid);
405         if (r < 0)
406                 return r;
407         if (pid < 0)
408                 return -EINVAL;
409
410         if (pid == 0) {
411                 r = manager_get_user_from_creds(m, message, UID_INVALID, error, &user);
412                 if (r < 0)
413                         return r;
414         } else {
415                 r = manager_get_user_by_pid(m, pid, &user);
416                 if (r < 0)
417                         return r;
418                 if (!user)
419                         return sd_bus_error_setf(error, BUS_ERROR_NO_USER_FOR_PID, "PID "PID_FMT" does not belong to any known or logged in user", pid);
420         }
421
422         p = user_bus_path(user);
423         if (!p)
424                 return -ENOMEM;
425
426         return sd_bus_reply_method_return(message, "o", p);
427 }
428
429 static int method_get_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
430         _cleanup_free_ char *p = NULL;
431         Manager *m = userdata;
432         const char *name;
433         Seat *seat;
434         int r;
435
436         assert(message);
437         assert(m);
438
439         r = sd_bus_message_read(message, "s", &name);
440         if (r < 0)
441                 return r;
442
443         r = manager_get_seat_from_creds(m, message, name, error, &seat);
444         if (r < 0)
445                 return r;
446
447         p = seat_bus_path(seat);
448         if (!p)
449                 return -ENOMEM;
450
451         return sd_bus_reply_method_return(message, "o", p);
452 }
453
454 static int method_list_sessions(sd_bus_message *message, void *userdata, sd_bus_error *error) {
455         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
456         Manager *m = userdata;
457         Session *session;
458         Iterator i;
459         int r;
460
461         assert(message);
462         assert(m);
463
464         r = sd_bus_message_new_method_return(message, &reply);
465         if (r < 0)
466                 return r;
467
468         r = sd_bus_message_open_container(reply, 'a', "(susso)");
469         if (r < 0)
470                 return r;
471
472         HASHMAP_FOREACH(session, m->sessions, i) {
473                 _cleanup_free_ char *p = NULL;
474
475                 p = session_bus_path(session);
476                 if (!p)
477                         return -ENOMEM;
478
479                 r = sd_bus_message_append(reply, "(susso)",
480                                           session->id,
481                                           (uint32_t) session->user->uid,
482                                           session->user->name,
483                                           session->seat ? session->seat->id : "",
484                                           p);
485                 if (r < 0)
486                         return r;
487         }
488
489         r = sd_bus_message_close_container(reply);
490         if (r < 0)
491                 return r;
492
493         return sd_bus_send(NULL, reply, NULL);
494 }
495
496 static int method_list_users(sd_bus_message *message, void *userdata, sd_bus_error *error) {
497         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
498         Manager *m = userdata;
499         User *user;
500         Iterator i;
501         int r;
502
503         assert(message);
504         assert(m);
505
506         r = sd_bus_message_new_method_return(message, &reply);
507         if (r < 0)
508                 return r;
509
510         r = sd_bus_message_open_container(reply, 'a', "(uso)");
511         if (r < 0)
512                 return r;
513
514         HASHMAP_FOREACH(user, m->users, i) {
515                 _cleanup_free_ char *p = NULL;
516
517                 p = user_bus_path(user);
518                 if (!p)
519                         return -ENOMEM;
520
521                 r = sd_bus_message_append(reply, "(uso)",
522                                           (uint32_t) user->uid,
523                                           user->name,
524                                           p);
525                 if (r < 0)
526                         return r;
527         }
528
529         r = sd_bus_message_close_container(reply);
530         if (r < 0)
531                 return r;
532
533         return sd_bus_send(NULL, reply, NULL);
534 }
535
536 static int method_list_seats(sd_bus_message *message, void *userdata, sd_bus_error *error) {
537         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
538         Manager *m = userdata;
539         Seat *seat;
540         Iterator i;
541         int r;
542
543         assert(message);
544         assert(m);
545
546         r = sd_bus_message_new_method_return(message, &reply);
547         if (r < 0)
548                 return r;
549
550         r = sd_bus_message_open_container(reply, 'a', "(so)");
551         if (r < 0)
552                 return r;
553
554         HASHMAP_FOREACH(seat, m->seats, i) {
555                 _cleanup_free_ char *p = NULL;
556
557                 p = seat_bus_path(seat);
558                 if (!p)
559                         return -ENOMEM;
560
561                 r = sd_bus_message_append(reply, "(so)", seat->id, p);
562                 if (r < 0)
563                         return r;
564         }
565
566         r = sd_bus_message_close_container(reply);
567         if (r < 0)
568                 return r;
569
570         return sd_bus_send(NULL, reply, NULL);
571 }
572
573 static int method_list_inhibitors(sd_bus_message *message, void *userdata, sd_bus_error *error) {
574         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
575         Manager *m = userdata;
576         Inhibitor *inhibitor;
577         Iterator i;
578         int r;
579
580         assert(message);
581         assert(m);
582
583         r = sd_bus_message_new_method_return(message, &reply);
584         if (r < 0)
585                 return r;
586
587         r = sd_bus_message_open_container(reply, 'a', "(ssssuu)");
588         if (r < 0)
589                 return r;
590
591         HASHMAP_FOREACH(inhibitor, m->inhibitors, i) {
592
593                 r = sd_bus_message_append(reply, "(ssssuu)",
594                                           strempty(inhibit_what_to_string(inhibitor->what)),
595                                           strempty(inhibitor->who),
596                                           strempty(inhibitor->why),
597                                           strempty(inhibit_mode_to_string(inhibitor->mode)),
598                                           (uint32_t) inhibitor->uid,
599                                           (uint32_t) inhibitor->pid);
600                 if (r < 0)
601                         return r;
602         }
603
604         r = sd_bus_message_close_container(reply);
605         if (r < 0)
606                 return r;
607
608         return sd_bus_send(NULL, reply, NULL);
609 }
610
611 static int method_create_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
612         const char *service, *type, *class, *cseat, *tty, *display, *remote_user, *remote_host, *desktop;
613         uint32_t audit_id = 0;
614         _cleanup_free_ char *id = NULL;
615         Session *session = NULL;
616         Manager *m = userdata;
617         User *user = NULL;
618         Seat *seat = NULL;
619         pid_t leader;
620         uid_t uid;
621         int remote;
622         uint32_t vtnr = 0;
623         SessionType t;
624         SessionClass c;
625         int r;
626
627         assert(message);
628         assert(m);
629
630         assert_cc(sizeof(pid_t) == sizeof(uint32_t));
631         assert_cc(sizeof(uid_t) == sizeof(uint32_t));
632
633         r = sd_bus_message_read(message, "uusssssussbss", &uid, &leader, &service, &type, &class, &desktop, &cseat, &vtnr, &tty, &display, &remote, &remote_user, &remote_host);
634         if (r < 0)
635                 return r;
636
637         if (!uid_is_valid(uid))
638                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid UID");
639         if (leader < 0 || leader == 1)
640                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid leader PID");
641
642         if (isempty(type))
643                 t = _SESSION_TYPE_INVALID;
644         else {
645                 t = session_type_from_string(type);
646                 if (t < 0)
647                         return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid session type %s", type);
648         }
649
650         if (isempty(class))
651                 c = _SESSION_CLASS_INVALID;
652         else {
653                 c = session_class_from_string(class);
654                 if (c < 0)
655                         return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid session class %s", class);
656         }
657
658         if (isempty(desktop))
659                 desktop = NULL;
660         else {
661                 if (!string_is_safe(desktop))
662                         return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid desktop string %s", desktop);
663         }
664
665         if (isempty(cseat))
666                 seat = NULL;
667         else {
668                 seat = hashmap_get(m->seats, cseat);
669                 if (!seat)
670                         return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_SEAT, "No seat '%s' known", cseat);
671         }
672
673         if (tty_is_vc(tty)) {
674                 int v;
675
676                 if (!seat)
677                         seat = m->seat0;
678                 else if (seat != m->seat0)
679                         return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "TTY %s is virtual console but seat %s is not seat0", tty, seat->id);
680
681                 v = vtnr_from_tty(tty);
682                 if (v <= 0)
683                         return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Cannot determine VT number from virtual console TTY %s", tty);
684
685                 if (!vtnr)
686                         vtnr = (uint32_t) v;
687                 else if (vtnr != (uint32_t) v)
688                         return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Specified TTY and VT number do not match");
689
690         } else if (tty_is_console(tty)) {
691
692                 if (!seat)
693                         seat = m->seat0;
694                 else if (seat != m->seat0)
695                         return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Console TTY specified but seat is not seat0");
696
697                 if (vtnr != 0)
698                         return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Console TTY specified but VT number is not 0");
699         }
700
701         if (seat) {
702                 if (seat_has_vts(seat)) {
703                         if (!vtnr || vtnr > 63)
704                                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "VT number out of range");
705                 } else {
706                         if (vtnr != 0)
707                                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Seat has no VTs but VT number not 0");
708                 }
709         }
710
711         r = sd_bus_message_enter_container(message, 'a', "(sv)");
712         if (r < 0)
713                 return r;
714
715         if (t == _SESSION_TYPE_INVALID) {
716                 if (!isempty(display))
717                         t = SESSION_X11;
718                 else if (!isempty(tty))
719                         t = SESSION_TTY;
720                 else
721                         t = SESSION_UNSPECIFIED;
722         }
723
724         if (c == _SESSION_CLASS_INVALID) {
725                 if (t == SESSION_UNSPECIFIED)
726                         c = SESSION_BACKGROUND;
727                 else
728                         c = SESSION_USER;
729         }
730
731         if (leader == 0) {
732                 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
733
734                 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_PID, &creds);
735                 if (r < 0)
736                         return r;
737
738                 r = sd_bus_creds_get_pid(creds, (pid_t*) &leader);
739                 if (r < 0)
740                         return r;
741         }
742
743         r = manager_get_session_by_pid(m, leader, NULL);
744         if (r > 0)
745                 return sd_bus_error_setf(error, BUS_ERROR_SESSION_BUSY, "Already running in a session");
746
747         /*
748          * Old gdm and lightdm start the user-session on the same VT as
749          * the greeter session. But they destroy the greeter session
750          * after the user-session and want the user-session to take
751          * over the VT. We need to support this for
752          * backwards-compatibility, so make sure we allow new sessions
753          * on a VT that a greeter is running on. Furthermore, to allow
754          * re-logins, we have to allow a greeter to take over a used VT for
755          * the exact same reasons.
756          */
757         if (c != SESSION_GREETER &&
758             vtnr > 0 &&
759             vtnr < m->seat0->position_count &&
760             m->seat0->positions[vtnr] &&
761             m->seat0->positions[vtnr]->class != SESSION_GREETER)
762                 return sd_bus_error_setf(error, BUS_ERROR_SESSION_BUSY, "Already occupied by a session");
763
764         if (hashmap_size(m->sessions) >= m->sessions_max)
765                 return sd_bus_error_setf(error, SD_BUS_ERROR_LIMITS_EXCEEDED, "Maximum number of sessions (%" PRIu64 ") reached, refusing further sessions.", m->sessions_max);
766
767         audit_session_from_pid(leader, &audit_id);
768         if (audit_id > 0) {
769                 /* Keep our session IDs and the audit session IDs in sync */
770
771                 if (asprintf(&id, "%"PRIu32, audit_id) < 0)
772                         return -ENOMEM;
773
774                 /* Wut? There's already a session by this name and we
775                  * didn't find it above? Weird, then let's not trust
776                  * the audit data and let's better register a new
777                  * ID */
778                 if (hashmap_get(m->sessions, id)) {
779                         log_warning("Existing logind session ID %s used by new audit session, ignoring", id);
780                         audit_id = 0;
781
782                         id = mfree(id);
783                 }
784         }
785
786         if (!id) {
787                 do {
788                         id = mfree(id);
789
790                         if (asprintf(&id, "c%lu", ++m->session_counter) < 0)
791                                 return -ENOMEM;
792
793                 } while (hashmap_get(m->sessions, id));
794         }
795
796         r = manager_add_user_by_uid(m, uid, &user);
797         if (r < 0)
798                 goto fail;
799
800         r = manager_add_session(m, id, &session);
801         if (r < 0)
802                 goto fail;
803
804         session_set_user(session, user);
805
806         session->leader = leader;
807         session->audit_id = audit_id;
808         session->type = t;
809         session->class = c;
810         session->remote = remote;
811         session->vtnr = vtnr;
812
813         if (!isempty(tty)) {
814                 session->tty = strdup(tty);
815                 if (!session->tty) {
816                         r = -ENOMEM;
817                         goto fail;
818                 }
819         }
820
821         if (!isempty(display)) {
822                 session->display = strdup(display);
823                 if (!session->display) {
824                         r = -ENOMEM;
825                         goto fail;
826                 }
827         }
828
829         if (!isempty(remote_user)) {
830                 session->remote_user = strdup(remote_user);
831                 if (!session->remote_user) {
832                         r = -ENOMEM;
833                         goto fail;
834                 }
835         }
836
837         if (!isempty(remote_host)) {
838                 session->remote_host = strdup(remote_host);
839                 if (!session->remote_host) {
840                         r = -ENOMEM;
841                         goto fail;
842                 }
843         }
844
845         if (!isempty(service)) {
846                 session->service = strdup(service);
847                 if (!session->service) {
848                         r = -ENOMEM;
849                         goto fail;
850                 }
851         }
852
853         if (!isempty(desktop)) {
854                 session->desktop = strdup(desktop);
855                 if (!session->desktop) {
856                         r = -ENOMEM;
857                         goto fail;
858                 }
859         }
860
861         if (seat) {
862                 r = seat_attach_session(seat, session);
863                 if (r < 0)
864                         goto fail;
865         }
866
867         r = session_start(session);
868         if (r < 0)
869                 goto fail;
870
871         session->create_message = sd_bus_message_ref(message);
872
873 #if 0 /// UNNEEDED by elogind
874         /* Now, let's wait until the slice unit and stuff got
875          * created. We send the reply back from
876          * session_send_create_reply(). */
877 #else
878         /* We reply directly. */
879
880         r = session_send_create_reply(session, NULL);
881         if (r < 0)
882                 goto fail;
883 #endif // 0
884
885         return 1;
886
887 fail:
888         if (session)
889                 session_add_to_gc_queue(session);
890
891         if (user)
892                 user_add_to_gc_queue(user);
893
894         return r;
895 }
896
897 static int method_release_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
898         Manager *m = userdata;
899         Session *session;
900         const char *name;
901         int r;
902
903         assert(message);
904         assert(m);
905
906         r = sd_bus_message_read(message, "s", &name);
907         if (r < 0)
908                 return r;
909
910         r = manager_get_session_from_creds(m, message, name, error, &session);
911         if (r < 0)
912                 return r;
913
914         r = session_release(session);
915         if (r < 0)
916                 return r;
917
918         session_add_to_gc_queue(session);
919
920         return sd_bus_reply_method_return(message, NULL);
921 }
922
923 static int method_activate_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
924         Manager *m = userdata;
925         Session *session;
926         const char *name;
927         int r;
928
929         assert(message);
930         assert(m);
931
932         r = sd_bus_message_read(message, "s", &name);
933         if (r < 0)
934                 return r;
935
936         r = manager_get_session_from_creds(m, message, name, error, &session);
937         if (r < 0)
938                 return r;
939
940         return bus_session_method_activate(message, session, error);
941 }
942
943 static int method_activate_session_on_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
944         const char *session_name, *seat_name;
945         Manager *m = userdata;
946         Session *session;
947         Seat *seat;
948         int r;
949
950         assert(message);
951         assert(m);
952
953         /* Same as ActivateSession() but refuses to work if
954          * the seat doesn't match */
955
956         r = sd_bus_message_read(message, "ss", &session_name, &seat_name);
957         if (r < 0)
958                 return r;
959
960         r = manager_get_session_from_creds(m, message, session_name, error, &session);
961         if (r < 0)
962                 return r;
963
964         r = manager_get_seat_from_creds(m, message, seat_name, error, &seat);
965         if (r < 0)
966                 return r;
967
968         if (session->seat != seat)
969                 return sd_bus_error_setf(error, BUS_ERROR_SESSION_NOT_ON_SEAT, "Session %s not on seat %s", session_name, seat_name);
970
971         r = session_activate(session);
972         if (r < 0)
973                 return r;
974
975         return sd_bus_reply_method_return(message, NULL);
976 }
977
978 static int method_lock_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
979         Manager *m = userdata;
980         Session *session;
981         const char *name;
982         int r;
983
984         assert(message);
985         assert(m);
986
987         r = sd_bus_message_read(message, "s", &name);
988         if (r < 0)
989                 return r;
990
991         r = manager_get_session_from_creds(m, message, name, error, &session);
992         if (r < 0)
993                 return r;
994
995         return bus_session_method_lock(message, session, error);
996 }
997
998 static int method_lock_sessions(sd_bus_message *message, void *userdata, sd_bus_error *error) {
999         Manager *m = userdata;
1000         int r;
1001
1002         assert(message);
1003         assert(m);
1004
1005         r = bus_verify_polkit_async(
1006                         message,
1007                         CAP_SYS_ADMIN,
1008                         "org.freedesktop.login1.lock-sessions",
1009                         NULL,
1010                         false,
1011                         UID_INVALID,
1012                         &m->polkit_registry,
1013                         error);
1014         if (r < 0)
1015                 return r;
1016         if (r == 0)
1017                 return 1; /* Will call us back */
1018
1019         r = session_send_lock_all(m, streq(sd_bus_message_get_member(message), "LockSessions"));
1020         if (r < 0)
1021                 return r;
1022
1023         return sd_bus_reply_method_return(message, NULL);
1024 }
1025
1026 static int method_kill_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1027         const char *name;
1028         Manager *m = userdata;
1029         Session *session;
1030         int r;
1031
1032         assert(message);
1033         assert(m);
1034
1035         r = sd_bus_message_read(message, "s", &name);
1036         if (r < 0)
1037                 return r;
1038
1039         r = manager_get_session_from_creds(m, message, name, error, &session);
1040         if (r < 0)
1041                 return r;
1042
1043         return bus_session_method_kill(message, session, error);
1044 }
1045
1046 static int method_kill_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1047         Manager *m = userdata;
1048         uint32_t uid;
1049         User *user;
1050         int r;
1051
1052         assert(message);
1053         assert(m);
1054
1055         r = sd_bus_message_read(message, "u", &uid);
1056         if (r < 0)
1057                 return r;
1058
1059         r = manager_get_user_from_creds(m, message, uid, error, &user);
1060         if (r < 0)
1061                 return r;
1062
1063         return bus_user_method_kill(message, user, error);
1064 }
1065
1066 static int method_terminate_session(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1067         Manager *m = userdata;
1068         const char *name;
1069         Session *session;
1070         int r;
1071
1072         assert(message);
1073         assert(m);
1074
1075         r = sd_bus_message_read(message, "s", &name);
1076         if (r < 0)
1077                 return r;
1078
1079         r = manager_get_session_from_creds(m, message, name, error, &session);
1080         if (r < 0)
1081                 return r;
1082
1083         return bus_session_method_terminate(message, session, error);
1084 }
1085
1086 static int method_terminate_user(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1087         Manager *m = userdata;
1088         uint32_t uid;
1089         User *user;
1090         int r;
1091
1092         assert(message);
1093         assert(m);
1094
1095         r = sd_bus_message_read(message, "u", &uid);
1096         if (r < 0)
1097                 return r;
1098
1099         r = manager_get_user_from_creds(m, message, uid, error, &user);
1100         if (r < 0)
1101                 return r;
1102
1103         return bus_user_method_terminate(message, user, error);
1104 }
1105
1106 static int method_terminate_seat(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1107         Manager *m = userdata;
1108         const char *name;
1109         Seat *seat;
1110         int r;
1111
1112         assert(message);
1113         assert(m);
1114
1115         r = sd_bus_message_read(message, "s", &name);
1116         if (r < 0)
1117                 return r;
1118
1119         r = manager_get_seat_from_creds(m, message, name, error, &seat);
1120         if (r < 0)
1121                 return r;
1122
1123         return bus_seat_method_terminate(message, seat, error);
1124 }
1125
1126 static int method_set_user_linger(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1127         _cleanup_free_ char *cc = NULL;
1128         Manager *m = userdata;
1129         int r, b, interactive;
1130         struct passwd *pw;
1131         const char *path;
1132         uint32_t uid;
1133         bool self = false;
1134
1135         assert(message);
1136         assert(m);
1137
1138         r = sd_bus_message_read(message, "ubb", &uid, &b, &interactive);
1139         if (r < 0)
1140                 return r;
1141
1142         if (uid == UID_INVALID) {
1143                 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
1144
1145                 /* Note that we get the owner UID of the session, not the actual client UID here! */
1146                 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_OWNER_UID|SD_BUS_CREDS_AUGMENT, &creds);
1147                 if (r < 0)
1148                         return r;
1149
1150                 r = sd_bus_creds_get_owner_uid(creds, &uid);
1151                 if (r < 0)
1152                         return r;
1153
1154                 self = true;
1155
1156         } else if (!uid_is_valid(uid))
1157                 return -EINVAL;
1158
1159         errno = 0;
1160         pw = getpwuid(uid);
1161         if (!pw)
1162                 return errno > 0 ? -errno : -ENOENT;
1163
1164         r = bus_verify_polkit_async(
1165                         message,
1166                         CAP_SYS_ADMIN,
1167                         self ? "org.freedesktop.login1.set-self-linger" : "org.freedesktop.login1.set-user-linger",
1168                         NULL,
1169                         interactive,
1170                         UID_INVALID,
1171                         &m->polkit_registry,
1172                         error);
1173         if (r < 0)
1174                 return r;
1175         if (r == 0)
1176                 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1177
1178         mkdir_p_label("/var/lib/systemd", 0755);
1179
1180         r = mkdir_safe_label("/var/lib/systemd/linger", 0755, 0, 0);
1181         if (r < 0)
1182                 return r;
1183
1184         cc = cescape(pw->pw_name);
1185         if (!cc)
1186                 return -ENOMEM;
1187
1188         path = strjoina("/var/lib/systemd/linger/", cc);
1189         if (b) {
1190                 User *u;
1191
1192                 r = touch(path);
1193                 if (r < 0)
1194                         return r;
1195
1196                 if (manager_add_user_by_uid(m, uid, &u) >= 0)
1197                         user_start(u);
1198
1199         } else {
1200                 User *u;
1201
1202                 r = unlink(path);
1203                 if (r < 0 && errno != ENOENT)
1204                         return -errno;
1205
1206                 u = hashmap_get(m->users, UID_TO_PTR(uid));
1207                 if (u)
1208                         user_add_to_gc_queue(u);
1209         }
1210
1211         return sd_bus_reply_method_return(message, NULL);
1212 }
1213
1214 static int trigger_device(Manager *m, struct udev_device *d) {
1215         _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
1216         struct udev_list_entry *first, *item;
1217         int r;
1218
1219         assert(m);
1220
1221         e = udev_enumerate_new(m->udev);
1222         if (!e)
1223                 return -ENOMEM;
1224
1225         if (d) {
1226                 r = udev_enumerate_add_match_parent(e, d);
1227                 if (r < 0)
1228                         return r;
1229         }
1230
1231         r = udev_enumerate_scan_devices(e);
1232         if (r < 0)
1233                 return r;
1234
1235         first = udev_enumerate_get_list_entry(e);
1236         udev_list_entry_foreach(item, first) {
1237                 _cleanup_free_ char *t = NULL;
1238                 const char *p;
1239
1240                 p = udev_list_entry_get_name(item);
1241
1242                 t = strappend(p, "/uevent");
1243                 if (!t)
1244                         return -ENOMEM;
1245
1246                 write_string_file(t, "change", WRITE_STRING_FILE_CREATE);
1247         }
1248
1249         return 0;
1250 }
1251
1252 static int attach_device(Manager *m, const char *seat, const char *sysfs) {
1253         _cleanup_udev_device_unref_ struct udev_device *d = NULL;
1254         _cleanup_free_ char *rule = NULL, *file = NULL;
1255         const char *id_for_seat;
1256         int r;
1257
1258         assert(m);
1259         assert(seat);
1260         assert(sysfs);
1261
1262         d = udev_device_new_from_syspath(m->udev, sysfs);
1263         if (!d)
1264                 return -ENODEV;
1265
1266         if (!udev_device_has_tag(d, "seat"))
1267                 return -ENODEV;
1268
1269         id_for_seat = udev_device_get_property_value(d, "ID_FOR_SEAT");
1270         if (!id_for_seat)
1271                 return -ENODEV;
1272
1273         if (asprintf(&file, "/etc/udev/rules.d/72-seat-%s.rules", id_for_seat) < 0)
1274                 return -ENOMEM;
1275
1276         if (asprintf(&rule, "TAG==\"seat\", ENV{ID_FOR_SEAT}==\"%s\", ENV{ID_SEAT}=\"%s\"", id_for_seat, seat) < 0)
1277                 return -ENOMEM;
1278
1279         mkdir_p_label("/etc/udev/rules.d", 0755);
1280         r = write_string_file_atomic_label(file, rule);
1281         if (r < 0)
1282                 return r;
1283
1284         return trigger_device(m, d);
1285 }
1286
1287 static int flush_devices(Manager *m) {
1288         _cleanup_closedir_ DIR *d;
1289
1290         assert(m);
1291
1292         d = opendir("/etc/udev/rules.d");
1293         if (!d) {
1294                 if (errno != ENOENT)
1295                         log_warning_errno(errno, "Failed to open /etc/udev/rules.d: %m");
1296         } else {
1297                 struct dirent *de;
1298
1299                 while ((de = readdir(d))) {
1300
1301                         if (!dirent_is_file(de))
1302                                 continue;
1303
1304                         if (!startswith(de->d_name, "72-seat-"))
1305                                 continue;
1306
1307                         if (!endswith(de->d_name, ".rules"))
1308                                 continue;
1309
1310                         if (unlinkat(dirfd(d), de->d_name, 0) < 0)
1311                                 log_warning_errno(errno, "Failed to unlink %s: %m", de->d_name);
1312                 }
1313         }
1314
1315         return trigger_device(m, NULL);
1316 }
1317
1318 static int method_attach_device(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1319         const char *sysfs, *seat;
1320         Manager *m = userdata;
1321         int interactive, r;
1322
1323         assert(message);
1324         assert(m);
1325
1326         r = sd_bus_message_read(message, "ssb", &seat, &sysfs, &interactive);
1327         if (r < 0)
1328                 return r;
1329
1330         if (!path_startswith(sysfs, "/sys"))
1331                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not in /sys", sysfs);
1332
1333         if (!seat_name_is_valid(seat))
1334                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Seat %s is not valid", seat);
1335
1336         r = bus_verify_polkit_async(
1337                         message,
1338                         CAP_SYS_ADMIN,
1339                         "org.freedesktop.login1.attach-device",
1340                         NULL,
1341                         interactive,
1342                         UID_INVALID,
1343                         &m->polkit_registry,
1344                         error);
1345         if (r < 0)
1346                 return r;
1347         if (r == 0)
1348                 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1349
1350         r = attach_device(m, seat, sysfs);
1351         if (r < 0)
1352                 return r;
1353
1354         return sd_bus_reply_method_return(message, NULL);
1355 }
1356
1357 static int method_flush_devices(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1358         Manager *m = userdata;
1359         int interactive, r;
1360
1361         assert(message);
1362         assert(m);
1363
1364         r = sd_bus_message_read(message, "b", &interactive);
1365         if (r < 0)
1366                 return r;
1367
1368         r = bus_verify_polkit_async(
1369                         message,
1370                         CAP_SYS_ADMIN,
1371                         "org.freedesktop.login1.flush-devices",
1372                         NULL,
1373                         interactive,
1374                         UID_INVALID,
1375                         &m->polkit_registry,
1376                         error);
1377         if (r < 0)
1378                 return r;
1379         if (r == 0)
1380                 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1381
1382         r = flush_devices(m);
1383         if (r < 0)
1384                 return r;
1385
1386         return sd_bus_reply_method_return(message, NULL);
1387 }
1388
1389 static int have_multiple_sessions(
1390                 Manager *m,
1391                 uid_t uid) {
1392
1393         Session *session;
1394         Iterator i;
1395
1396         assert(m);
1397
1398         /* Check for other users' sessions. Greeter sessions do not
1399          * count, and non-login sessions do not count either. */
1400         HASHMAP_FOREACH(session, m->sessions, i)
1401                 if (session->class == SESSION_USER &&
1402                     session->user->uid != uid)
1403                         return true;
1404
1405         return false;
1406 }
1407
1408 static int bus_manager_log_shutdown(
1409                 Manager *m,
1410                 InhibitWhat w,
1411 #if 0 /// elogind does not support systemd units
1412                 const char *unit_name) {
1413
1414         const char *p, *q;
1415
1416         assert(m);
1417         assert(unit_name);
1418
1419         if (w != INHIBIT_SHUTDOWN)
1420                 return 0;
1421
1422         if (streq(unit_name, SPECIAL_POWEROFF_TARGET)) {
1423                 p = "MESSAGE=System is powering down";
1424                 q = "SHUTDOWN=power-off";
1425         } else if (streq(unit_name, SPECIAL_HALT_TARGET)) {
1426                 p = "MESSAGE=System is halting";
1427                 q = "SHUTDOWN=halt";
1428         } else if (streq(unit_name, SPECIAL_REBOOT_TARGET)) {
1429                 p = "MESSAGE=System is rebooting";
1430                 q = "SHUTDOWN=reboot";
1431         } else if (streq(unit_name, SPECIAL_KEXEC_TARGET)) {
1432                 p = "MESSAGE=System is rebooting with kexec";
1433                 q = "SHUTDOWN=kexec";
1434         } else {
1435                 p = "MESSAGE=System is shutting down";
1436                 q = NULL;
1437         }
1438 #else
1439                  HandleAction action) {
1440
1441          const char *p, *q;
1442
1443          assert(m);
1444
1445          if (w != INHIBIT_SHUTDOWN)
1446                  return 0;
1447
1448          switch (action) {
1449          case HANDLE_POWEROFF:
1450                  p = "MESSAGE=System is powering down.";
1451                  q = "SHUTDOWN=power-off";
1452                  break;
1453          case HANDLE_HALT:
1454                  p = "MESSAGE=System is halting.";
1455                  q = "SHUTDOWN=halt";
1456                  break;
1457          case HANDLE_REBOOT:
1458                  p = "MESSAGE=System is rebooting.";
1459                  q = "SHUTDOWN=reboot";
1460                  break;
1461          case HANDLE_KEXEC:
1462                  p = "MESSAGE=System is rebooting with kexec.";
1463                  q = "SHUTDOWN=kexec";
1464                  break;
1465          default:
1466                  p = "MESSAGE=System is shutting down.";
1467                  q = NULL;
1468          }
1469 #endif // 0
1470         if (isempty(m->wall_message))
1471                 p = strjoina(p, ".");
1472         else
1473                 p = strjoina(p, " (", m->wall_message, ").");
1474
1475         return log_struct(LOG_NOTICE,
1476                           LOG_MESSAGE_ID(SD_MESSAGE_SHUTDOWN),
1477                           p,
1478                           q,
1479                           NULL);
1480 }
1481
1482 static int lid_switch_ignore_handler(sd_event_source *e, uint64_t usec, void *userdata) {
1483         Manager *m = userdata;
1484
1485         assert(e);
1486         assert(m);
1487
1488         m->lid_switch_ignore_event_source = sd_event_source_unref(m->lid_switch_ignore_event_source);
1489         return 0;
1490 }
1491
1492 int manager_set_lid_switch_ignore(Manager *m, usec_t until) {
1493         int r;
1494
1495         assert(m);
1496
1497         if (until <= now(CLOCK_MONOTONIC))
1498                 return 0;
1499
1500         /* We want to ignore the lid switch for a while after each
1501          * suspend, and after boot-up. Hence let's install a timer for
1502          * this. As long as the event source exists we ignore the lid
1503          * switch. */
1504
1505         if (m->lid_switch_ignore_event_source) {
1506                 usec_t u;
1507
1508                 r = sd_event_source_get_time(m->lid_switch_ignore_event_source, &u);
1509                 if (r < 0)
1510                         return r;
1511
1512                 if (until <= u)
1513                         return 0;
1514
1515                 r = sd_event_source_set_time(m->lid_switch_ignore_event_source, until);
1516         } else
1517                 r = sd_event_add_time(
1518                                 m->event,
1519                                 &m->lid_switch_ignore_event_source,
1520                                 CLOCK_MONOTONIC,
1521                                 until, 0,
1522                                 lid_switch_ignore_handler, m);
1523
1524         return r;
1525 }
1526
1527 static void reset_scheduled_shutdown(Manager *m) {
1528         m->scheduled_shutdown_timeout_source = sd_event_source_unref(m->scheduled_shutdown_timeout_source);
1529         m->wall_message_timeout_source = sd_event_source_unref(m->wall_message_timeout_source);
1530         m->nologin_timeout_source = sd_event_source_unref(m->nologin_timeout_source);
1531         m->scheduled_shutdown_type = mfree(m->scheduled_shutdown_type);
1532         m->scheduled_shutdown_timeout = 0;
1533         m->shutdown_dry_run = false;
1534
1535         if (m->unlink_nologin) {
1536                 (void) unlink("/run/nologin");
1537                 m->unlink_nologin = false;
1538         }
1539 }
1540
1541 static int execute_shutdown_or_sleep(
1542                 Manager *m,
1543                 InhibitWhat w,
1544                 HandleAction action,
1545                 sd_bus_error *error) {
1546
1547 #if 0 /// elogind does not need these, we do it ourselves
1548         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1549         char *c = NULL;
1550         const char *p;
1551 #endif // 0
1552         int r;
1553
1554         assert(m);
1555         assert(w >= 0);
1556         assert(w < _INHIBIT_WHAT_MAX);
1557
1558         bus_manager_log_shutdown(m, w, action);
1559
1560 #if 0 /// elogind does it directly without depending on systemd running the system
1561         if (m->shutdown_dry_run) {
1562                 log_info("Running in dry run, suppressing action.");
1563                 reset_scheduled_shutdown(m);
1564         } else {
1565                 r = sd_bus_call_method(
1566                                 m->bus,
1567                                 "org.freedesktop.systemd1",
1568                                 "/org/freedesktop/systemd1",
1569                                 "org.freedesktop.systemd1.Manager",
1570                                 "StartUnit",
1571                                 error,
1572                                 &reply,
1573                                 "ss", unit_name, "replace-irreversibly");
1574                 if (r < 0)
1575                         return r;
1576
1577                 r = sd_bus_message_read(reply, "o", &p);
1578                 if (r < 0)
1579                         return r;
1580
1581                 c = strdup(p);
1582                 if (!c)
1583                         return -ENOMEM;
1584
1585                 m->action_unit = unit_name;
1586                 free(m->action_job);
1587                 m->action_job = c;
1588                 m->action_what = w;
1589         }
1590 #else
1591         r = shutdown_or_sleep(m, action);
1592
1593         /* no more pending actions, whether this failed or not */
1594         m->pending_action = HANDLE_IGNORE;
1595         m->action_what    = 0;
1596         if (r < 0)
1597                 return r;
1598 #endif // 0
1599
1600         /* Make sure the lid switch is ignored for a while */
1601         manager_set_lid_switch_ignore(m, now(CLOCK_MONOTONIC) + m->holdoff_timeout_usec);
1602
1603         return 0;
1604 }
1605
1606 int manager_dispatch_delayed(Manager *manager, bool timeout) {
1607
1608         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1609         Inhibitor *offending = NULL;
1610         int r;
1611
1612         assert(manager);
1613
1614         if ( (0 == manager->action_what) || (HANDLE_IGNORE == manager->pending_action) )
1615                 return 0;
1616
1617         if (manager_is_inhibited(manager, manager->action_what, INHIBIT_DELAY, NULL, false, false, 0, &offending)) {
1618                 _cleanup_free_ char *comm = NULL, *u = NULL;
1619
1620                 if (!timeout)
1621                         return 0;
1622
1623                 (void) get_process_comm(offending->pid, &comm);
1624                 u = uid_to_name(offending->uid);
1625
1626                 log_notice("Delay lock is active (UID "UID_FMT"/%s, PID "PID_FMT"/%s) but inhibitor timeout is reached.",
1627                            offending->uid, strna(u),
1628                            offending->pid, strna(comm));
1629         }
1630
1631         /* Actually do the operation */
1632         r = execute_shutdown_or_sleep(manager, manager->action_what, manager->pending_action, &error);
1633         if (r < 0) {
1634                 log_warning("Failed to send delayed message: %s", bus_error_message(&error, r));
1635
1636                 manager->pending_action = HANDLE_IGNORE;
1637                 manager->action_what    = 0;
1638                 return r;
1639         }
1640
1641         return 1;
1642 }
1643
1644 static int manager_inhibit_timeout_handler(
1645                         sd_event_source *s,
1646                         uint64_t usec,
1647                         void *userdata) {
1648
1649         Manager *manager = userdata;
1650         int r;
1651
1652         assert(manager);
1653         assert(manager->inhibit_timeout_source == s);
1654
1655         r = manager_dispatch_delayed(manager, true);
1656         return (r < 0) ? r : 0;
1657 }
1658
1659 static int delay_shutdown_or_sleep(
1660                 Manager *m,
1661                 InhibitWhat w,
1662                 HandleAction action) {
1663
1664         int r;
1665         usec_t timeout_val;
1666
1667         assert(m);
1668         assert(w >= 0);
1669         assert(w < _INHIBIT_WHAT_MAX);
1670
1671         timeout_val = now(CLOCK_MONOTONIC) + m->inhibit_delay_max;
1672
1673         if (m->inhibit_timeout_source) {
1674                 r = sd_event_source_set_time(m->inhibit_timeout_source, timeout_val);
1675                 if (r < 0)
1676                         return log_error_errno(r, "sd_event_source_set_time() failed: %m");
1677
1678                 r = sd_event_source_set_enabled(m->inhibit_timeout_source, SD_EVENT_ONESHOT);
1679                 if (r < 0)
1680                         return log_error_errno(r, "sd_event_source_set_enabled() failed: %m");
1681         } else {
1682                 r = sd_event_add_time(m->event, &m->inhibit_timeout_source, CLOCK_MONOTONIC,
1683                                       timeout_val, 0, manager_inhibit_timeout_handler, m);
1684                 if (r < 0)
1685                         return r;
1686         }
1687
1688         m->pending_action = action;
1689         m->action_what = w;
1690
1691         return 0;
1692 }
1693
1694 static int send_prepare_for(Manager *m, InhibitWhat w, bool _active) {
1695
1696         static const char * const signal_name[_INHIBIT_WHAT_MAX] = {
1697                 [INHIBIT_SHUTDOWN] = "PrepareForShutdown",
1698                 [INHIBIT_SLEEP] = "PrepareForSleep"
1699         };
1700
1701         int active = _active;
1702
1703         assert(m);
1704         assert(w >= 0);
1705         assert(w < _INHIBIT_WHAT_MAX);
1706         assert(signal_name[w]);
1707
1708         return sd_bus_emit_signal(m->bus,
1709                                   "/org/freedesktop/login1",
1710                                   "org.freedesktop.login1.Manager",
1711                                   signal_name[w],
1712                                   "b",
1713                                   active);
1714 }
1715
1716 int bus_manager_shutdown_or_sleep_now_or_later(
1717                 Manager *m,
1718                 HandleAction action,
1719                 InhibitWhat w,
1720                 sd_bus_error *error) {
1721
1722         bool delayed;
1723         int r;
1724
1725         assert(m);
1726         assert(w >= 0);
1727         assert(w <= _INHIBIT_WHAT_MAX);
1728
1729         /* Tell everybody to prepare for shutdown/sleep */
1730         send_prepare_for(m, w, true);
1731
1732         delayed =
1733                 m->inhibit_delay_max > 0 &&
1734                 manager_is_inhibited(m, w, INHIBIT_DELAY, NULL, false, false, 0, NULL);
1735
1736         if (delayed)
1737                 /* Shutdown is delayed, keep in mind what we
1738                  * want to do, and start a timeout */
1739                 r = delay_shutdown_or_sleep(m, w, action);
1740         else
1741                 /* Shutdown is not delayed, execute it
1742                  * immediately */
1743                 r = execute_shutdown_or_sleep(m, w, action, error);
1744
1745         return r;
1746 }
1747
1748 static int verify_shutdown_creds(
1749                 Manager *m,
1750                 sd_bus_message *message,
1751                 InhibitWhat w,
1752                 bool interactive,
1753                 const char *action,
1754                 const char *action_multiple_sessions,
1755                 const char *action_ignore_inhibit,
1756                 sd_bus_error *error) {
1757
1758         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
1759         bool multiple_sessions, blocked;
1760         uid_t uid;
1761         int r;
1762
1763         assert(m);
1764         assert(message);
1765         assert(w >= 0);
1766         assert(w <= _INHIBIT_WHAT_MAX);
1767
1768         r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
1769         if (r < 0)
1770                 return r;
1771
1772         r = sd_bus_creds_get_euid(creds, &uid);
1773         if (r < 0)
1774                 return r;
1775
1776         r = have_multiple_sessions(m, uid);
1777         if (r < 0)
1778                 return r;
1779
1780         multiple_sessions = r > 0;
1781         blocked = manager_is_inhibited(m, w, INHIBIT_BLOCK, NULL, false, true, uid, NULL);
1782
1783         if (multiple_sessions && action_multiple_sessions) {
1784                 r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action_multiple_sessions, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
1785                 if (r < 0)
1786                         return r;
1787                 if (r == 0)
1788                         return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1789         }
1790
1791         if (blocked && action_ignore_inhibit) {
1792                 r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action_ignore_inhibit, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
1793                 if (r < 0)
1794                         return r;
1795                 if (r == 0)
1796                         return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1797         }
1798
1799         if (!multiple_sessions && !blocked && action) {
1800                 r = bus_verify_polkit_async(message, CAP_SYS_BOOT, action, NULL, interactive, UID_INVALID, &m->polkit_registry, error);
1801                 if (r < 0)
1802                         return r;
1803                 if (r == 0)
1804                         return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
1805         }
1806
1807         return 0;
1808 }
1809
1810 static int method_do_shutdown_or_sleep(
1811                 Manager *m,
1812                 sd_bus_message *message,
1813                 HandleAction sleep_action,
1814                 InhibitWhat w,
1815                 const char *action,
1816                 const char *action_multiple_sessions,
1817                 const char *action_ignore_inhibit,
1818                 const char *sleep_verb,
1819                 sd_bus_error *error) {
1820
1821         int interactive, r;
1822
1823         assert(m);
1824         assert(message);
1825         assert(w >= 0);
1826         assert(w <= _INHIBIT_WHAT_MAX);
1827
1828         r = sd_bus_message_read(message, "b", &interactive);
1829         if (r < 0)
1830                 return r;
1831
1832         /* Don't allow multiple jobs being executed at the same time */
1833         if (m->action_what)
1834                 return sd_bus_error_setf(error, BUS_ERROR_OPERATION_IN_PROGRESS, "There's already a shutdown or sleep operation in progress");
1835
1836         if (sleep_verb) {
1837                 r = can_sleep(m, sleep_verb);
1838                 if (r < 0)
1839                         return r;
1840
1841                 if (r == 0)
1842                         return sd_bus_error_setf(error, BUS_ERROR_SLEEP_VERB_NOT_SUPPORTED, "Sleep verb not supported");
1843         }
1844
1845         r = verify_shutdown_creds(m, message, w, interactive, action, action_multiple_sessions,
1846                                   action_ignore_inhibit, error);
1847         if (r != 0)
1848                 return r;
1849
1850         r = bus_manager_shutdown_or_sleep_now_or_later(m, sleep_action, w, error);
1851         if (r < 0)
1852                 return r;
1853
1854         return sd_bus_reply_method_return(message, NULL);
1855 }
1856
1857 static int method_poweroff(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1858         Manager *m = userdata;
1859
1860         return method_do_shutdown_or_sleep(
1861                         m, message,
1862                         HANDLE_POWEROFF,
1863                         INHIBIT_SHUTDOWN,
1864                         "org.freedesktop.login1.power-off",
1865                         "org.freedesktop.login1.power-off-multiple-sessions",
1866                         "org.freedesktop.login1.power-off-ignore-inhibit",
1867                         NULL,
1868                         error);
1869 }
1870
1871 static int method_reboot(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1872         Manager *m = userdata;
1873
1874         return method_do_shutdown_or_sleep(
1875                         m, message,
1876                         HANDLE_REBOOT,
1877                         INHIBIT_SHUTDOWN,
1878                         "org.freedesktop.login1.reboot",
1879                         "org.freedesktop.login1.reboot-multiple-sessions",
1880                         "org.freedesktop.login1.reboot-ignore-inhibit",
1881                         NULL,
1882                         error);
1883 }
1884
1885 static int method_suspend(sd_bus_message *message, void *userdata, sd_bus_error *error) {
1886         Manager *m = userdata;
1887
1888         return method_do_shutdown_or_sleep(
1889                         m, message,
1890                         HANDLE_SUSPEND,
1891                         INHIBIT_SLEEP,
1892                         "org.freedesktop.login1.suspend",
1893                         "org.freedesktop.login1.suspend-multiple-sessions",
1894                         "org.freedesktop.login1.suspend-ignore-inhibit",
1895                         "suspend",
1896                         error);
1897 }
1898
1899 static int nologin_timeout_handler(
1900                         sd_event_source *s,
1901                         uint64_t usec,
1902                         void *userdata) {
1903
1904         Manager *m = userdata;
1905         int r;
1906
1907         log_info("Creating /run/nologin, blocking further logins...");
1908
1909         r = write_string_file_atomic_label("/run/nologin", "System is going down.");
1910         if (r < 0)
1911                 log_error_errno(r, "Failed to create /run/nologin: %m");
1912         else
1913                 m->unlink_nologin = true;
1914
1915         return 0;
1916 }
1917
1918 static int update_schedule_file(Manager *m) {
1919         _cleanup_free_ char *temp_path = NULL;
1920         _cleanup_fclose_ FILE *f = NULL;
1921         int r;
1922
1923         assert(m);
1924
1925         r = mkdir_safe_label("/run/systemd/shutdown", 0755, 0, 0);
1926         if (r < 0)
1927                 return log_error_errno(r, "Failed to create shutdown subdirectory: %m");
1928
1929         r = fopen_temporary("/run/systemd/shutdown/scheduled", &f, &temp_path);
1930         if (r < 0)
1931                 return log_error_errno(r, "Failed to save information about scheduled shutdowns: %m");
1932
1933         (void) fchmod(fileno(f), 0644);
1934
1935         fprintf(f,
1936                 "USEC="USEC_FMT"\n"
1937                 "WARN_WALL=%i\n"
1938                 "MODE=%s\n",
1939                 m->scheduled_shutdown_timeout,
1940                 m->enable_wall_messages,
1941                 m->scheduled_shutdown_type);
1942
1943         if (!isempty(m->wall_message)) {
1944                 _cleanup_free_ char *t;
1945
1946                 t = cescape(m->wall_message);
1947                 if (!t) {
1948                         r = -ENOMEM;
1949                         goto fail;
1950                 }
1951
1952                 fprintf(f, "WALL_MESSAGE=%s\n", t);
1953         }
1954
1955         r = fflush_and_check(f);
1956         if (r < 0)
1957                 goto fail;
1958
1959         if (rename(temp_path, "/run/systemd/shutdown/scheduled") < 0) {
1960                 r = -errno;
1961                 goto fail;
1962         }
1963
1964         return 0;
1965
1966 fail:
1967         (void) unlink(temp_path);
1968         (void) unlink("/run/systemd/shutdown/scheduled");
1969
1970         return log_error_errno(r, "Failed to write information about scheduled shutdowns: %m");
1971 }
1972
1973 static int manager_scheduled_shutdown_handler(
1974                         sd_event_source *s,
1975                         uint64_t usec,
1976                         void *userdata) {
1977
1978         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1979         Manager *m = userdata;
1980         HandleAction action;
1981         int r;
1982
1983         assert(m);
1984
1985         if (isempty(m->scheduled_shutdown_type))
1986                 return 0;
1987
1988         if (streq(m->scheduled_shutdown_type, "halt"))
1989                 action = HANDLE_HALT;
1990         else if (streq(m->scheduled_shutdown_type, "poweroff"))
1991                 action = HANDLE_POWEROFF;
1992         else
1993                 action = HANDLE_REBOOT;
1994
1995         r = execute_shutdown_or_sleep(m, 0, action, &error);
1996         if (r < 0)
1997                 return log_error_errno(r, "Unable to execute transition to %s: %m", m->scheduled_shutdown_type);
1998
1999         return 0;
2000 }
2001
2002 static int method_schedule_shutdown(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2003         Manager *m = userdata;
2004         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
2005         const char *action_multiple_sessions = NULL;
2006         const char *action_ignore_inhibit = NULL;
2007         const char *action = NULL;
2008         uint64_t elapse;
2009         char *type;
2010         int r;
2011
2012         assert(m);
2013         assert(message);
2014
2015         r = sd_bus_message_read(message, "st", &type, &elapse);
2016         if (r < 0)
2017                 return r;
2018
2019         if (startswith(type, "dry-")) {
2020                 type += 4;
2021                 m->shutdown_dry_run = true;
2022         }
2023
2024         if (streq(type, "reboot")) {
2025                 action = "org.freedesktop.login1.reboot";
2026                 action_multiple_sessions = "org.freedesktop.login1.reboot-multiple-sessions";
2027                 action_ignore_inhibit = "org.freedesktop.login1.reboot-ignore-inhibit";
2028         } else if (streq(type, "halt")) {
2029                 action = "org.freedesktop.login1.halt";
2030                 action_multiple_sessions = "org.freedesktop.login1.halt-multiple-sessions";
2031                 action_ignore_inhibit = "org.freedesktop.login1.halt-ignore-inhibit";
2032         } else if (streq(type, "poweroff")) {
2033                 action = "org.freedesktop.login1.power-off";
2034                 action_multiple_sessions = "org.freedesktop.login1.power-off-multiple-sessions";
2035                 action_ignore_inhibit = "org.freedesktop.login1.power-off-ignore-inhibit";
2036         } else
2037                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Unsupported shutdown type");
2038
2039         r = verify_shutdown_creds(m, message, INHIBIT_SHUTDOWN, false,
2040                                   action, action_multiple_sessions, action_ignore_inhibit, error);
2041         if (r != 0)
2042                 return r;
2043
2044         if (m->scheduled_shutdown_timeout_source) {
2045                 r = sd_event_source_set_time(m->scheduled_shutdown_timeout_source, elapse);
2046                 if (r < 0)
2047                         return log_error_errno(r, "sd_event_source_set_time() failed: %m");
2048
2049                 r = sd_event_source_set_enabled(m->scheduled_shutdown_timeout_source, SD_EVENT_ONESHOT);
2050                 if (r < 0)
2051                         return log_error_errno(r, "sd_event_source_set_enabled() failed: %m");
2052         } else {
2053                 r = sd_event_add_time(m->event, &m->scheduled_shutdown_timeout_source,
2054                                       CLOCK_REALTIME, elapse, 0, manager_scheduled_shutdown_handler, m);
2055                 if (r < 0)
2056                         return log_error_errno(r, "sd_event_add_time() failed: %m");
2057         }
2058
2059         r = free_and_strdup(&m->scheduled_shutdown_type, type);
2060         if (r < 0) {
2061                 m->scheduled_shutdown_timeout_source = sd_event_source_unref(m->scheduled_shutdown_timeout_source);
2062                 return log_oom();
2063         }
2064
2065         if (m->nologin_timeout_source) {
2066                 r = sd_event_source_set_time(m->nologin_timeout_source, elapse);
2067                 if (r < 0)
2068                         return log_error_errno(r, "sd_event_source_set_time() failed: %m");
2069
2070                 r = sd_event_source_set_enabled(m->nologin_timeout_source, SD_EVENT_ONESHOT);
2071                 if (r < 0)
2072                         return log_error_errno(r, "sd_event_source_set_enabled() failed: %m");
2073         } else {
2074                 r = sd_event_add_time(m->event, &m->nologin_timeout_source,
2075                                       CLOCK_REALTIME, elapse - 5 * USEC_PER_MINUTE, 0, nologin_timeout_handler, m);
2076                 if (r < 0)
2077                         return log_error_errno(r, "sd_event_add_time() failed: %m");
2078         }
2079
2080         m->scheduled_shutdown_timeout = elapse;
2081
2082         r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_AUGMENT|SD_BUS_CREDS_TTY|SD_BUS_CREDS_UID, &creds);
2083         if (r >= 0) {
2084                 const char *tty = NULL;
2085
2086                 (void) sd_bus_creds_get_uid(creds, &m->scheduled_shutdown_uid);
2087                 (void) sd_bus_creds_get_tty(creds, &tty);
2088
2089                 r = free_and_strdup(&m->scheduled_shutdown_tty, tty);
2090                 if (r < 0) {
2091                         m->scheduled_shutdown_timeout_source = sd_event_source_unref(m->scheduled_shutdown_timeout_source);
2092                         return log_oom();
2093                 }
2094         }
2095
2096 #if 0 /// elogind does not support utmp-wtmp
2097         r = manager_setup_wall_message_timer(m);
2098         if (r < 0)
2099                 return r;
2100 #endif // 0
2101
2102         if (!isempty(type)) {
2103                 r = update_schedule_file(m);
2104                 if (r < 0)
2105                         return r;
2106         } else
2107                 (void) unlink("/run/systemd/shutdown/scheduled");
2108
2109         return sd_bus_reply_method_return(message, NULL);
2110 }
2111
2112 static int method_cancel_scheduled_shutdown(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2113         Manager *m = userdata;
2114         bool cancelled;
2115
2116         assert(m);
2117         assert(message);
2118
2119         cancelled = m->scheduled_shutdown_type != NULL;
2120         reset_scheduled_shutdown(m);
2121
2122 #if 0 /// elogind does not support utmp-wtmp
2123         if (cancelled) {
2124                 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
2125                 const char *tty = NULL;
2126                 uid_t uid = 0;
2127                 int r;
2128
2129                 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_AUGMENT|SD_BUS_CREDS_TTY|SD_BUS_CREDS_UID, &creds);
2130                 if (r >= 0) {
2131                         (void) sd_bus_creds_get_uid(creds, &uid);
2132                         (void) sd_bus_creds_get_tty(creds, &tty);
2133                 }
2134
2135                 utmp_wall("The system shutdown has been cancelled",
2136                           uid_to_name(uid), tty, logind_wall_tty_filter, m);
2137         }
2138 #endif // 0
2139
2140         return sd_bus_reply_method_return(message, "b", cancelled);
2141 }
2142
2143 static int method_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2144         Manager *m = userdata;
2145
2146         return method_do_shutdown_or_sleep(
2147                         m, message,
2148                         HANDLE_HIBERNATE,
2149                         INHIBIT_SLEEP,
2150                         "org.freedesktop.login1.hibernate",
2151                         "org.freedesktop.login1.hibernate-multiple-sessions",
2152                         "org.freedesktop.login1.hibernate-ignore-inhibit",
2153                         "hibernate",
2154                         error);
2155 }
2156
2157 static int method_hybrid_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2158         Manager *m = userdata;
2159
2160         return method_do_shutdown_or_sleep(
2161                         m, message,
2162                         HANDLE_HYBRID_SLEEP,
2163                         INHIBIT_SLEEP,
2164                         "org.freedesktop.login1.hibernate",
2165                         "org.freedesktop.login1.hibernate-multiple-sessions",
2166                         "org.freedesktop.login1.hibernate-ignore-inhibit",
2167                         "hybrid-sleep",
2168                         error);
2169 }
2170
2171 static int method_can_shutdown_or_sleep(
2172                 Manager *m,
2173                 sd_bus_message *message,
2174                 InhibitWhat w,
2175                 const char *action,
2176                 const char *action_multiple_sessions,
2177                 const char *action_ignore_inhibit,
2178                 const char *sleep_verb,
2179                 sd_bus_error *error) {
2180
2181         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
2182         bool multiple_sessions, challenge, blocked;
2183         const char *result = NULL;
2184         uid_t uid;
2185         int r;
2186
2187         assert(m);
2188         assert(message);
2189         assert(w >= 0);
2190         assert(w <= _INHIBIT_WHAT_MAX);
2191         assert(action);
2192         assert(action_multiple_sessions);
2193         assert(action_ignore_inhibit);
2194
2195         if (sleep_verb) {
2196                 r = can_sleep(m, sleep_verb);
2197                 if (r < 0)
2198                         return r;
2199                 if (r == 0)
2200                         return sd_bus_reply_method_return(message, "s", "na");
2201         }
2202
2203         r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID, &creds);
2204         if (r < 0)
2205                 return r;
2206
2207         r = sd_bus_creds_get_euid(creds, &uid);
2208         if (r < 0)
2209                 return r;
2210
2211         r = have_multiple_sessions(m, uid);
2212         if (r < 0)
2213                 return r;
2214
2215         multiple_sessions = r > 0;
2216         blocked = manager_is_inhibited(m, w, INHIBIT_BLOCK, NULL, false, true, uid, NULL);
2217
2218         if (multiple_sessions) {
2219                 r = bus_test_polkit(message, CAP_SYS_BOOT, action_multiple_sessions, NULL, UID_INVALID, &challenge, error);
2220                 if (r < 0)
2221                         return r;
2222
2223                 if (r > 0)
2224                         result = "yes";
2225                 else if (challenge)
2226                         result = "challenge";
2227                 else
2228                         result = "no";
2229         }
2230
2231         if (blocked) {
2232                 r = bus_test_polkit(message, CAP_SYS_BOOT, action_ignore_inhibit, NULL, UID_INVALID, &challenge, error);
2233                 if (r < 0)
2234                         return r;
2235
2236                 if (r > 0 && !result)
2237                         result = "yes";
2238                 else if (challenge && (!result || streq(result, "yes")))
2239                         result = "challenge";
2240                 else
2241                         result = "no";
2242         }
2243
2244         if (!multiple_sessions && !blocked) {
2245                 /* If neither inhibit nor multiple sessions
2246                  * apply then just check the normal policy */
2247
2248                 r = bus_test_polkit(message, CAP_SYS_BOOT, action, NULL, UID_INVALID, &challenge, error);
2249                 if (r < 0)
2250                         return r;
2251
2252                 if (r > 0)
2253                         result = "yes";
2254                 else if (challenge)
2255                         result = "challenge";
2256                 else
2257                         result = "no";
2258         }
2259
2260         return sd_bus_reply_method_return(message, "s", result);
2261 }
2262
2263 static int method_can_poweroff(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2264         Manager *m = userdata;
2265
2266         return method_can_shutdown_or_sleep(
2267                         m, message,
2268                         INHIBIT_SHUTDOWN,
2269                         "org.freedesktop.login1.power-off",
2270                         "org.freedesktop.login1.power-off-multiple-sessions",
2271                         "org.freedesktop.login1.power-off-ignore-inhibit",
2272                         NULL,
2273                         error);
2274 }
2275
2276 static int method_can_reboot(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2277         Manager *m = userdata;
2278
2279         return method_can_shutdown_or_sleep(
2280                         m, message,
2281                         INHIBIT_SHUTDOWN,
2282                         "org.freedesktop.login1.reboot",
2283                         "org.freedesktop.login1.reboot-multiple-sessions",
2284                         "org.freedesktop.login1.reboot-ignore-inhibit",
2285                         NULL,
2286                         error);
2287 }
2288
2289 static int method_can_suspend(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2290         Manager *m = userdata;
2291
2292         return method_can_shutdown_or_sleep(
2293                         m, message,
2294                         INHIBIT_SLEEP,
2295                         "org.freedesktop.login1.suspend",
2296                         "org.freedesktop.login1.suspend-multiple-sessions",
2297                         "org.freedesktop.login1.suspend-ignore-inhibit",
2298                         "suspend",
2299                         error);
2300 }
2301
2302 static int method_can_hibernate(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2303         Manager *m = userdata;
2304
2305         return method_can_shutdown_or_sleep(
2306                         m, message,
2307                         INHIBIT_SLEEP,
2308                         "org.freedesktop.login1.hibernate",
2309                         "org.freedesktop.login1.hibernate-multiple-sessions",
2310                         "org.freedesktop.login1.hibernate-ignore-inhibit",
2311                         "hibernate",
2312                         error);
2313 }
2314
2315 static int method_can_hybrid_sleep(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2316         Manager *m = userdata;
2317
2318         return method_can_shutdown_or_sleep(
2319                         m, message,
2320                         INHIBIT_SLEEP,
2321                         "org.freedesktop.login1.hibernate",
2322                         "org.freedesktop.login1.hibernate-multiple-sessions",
2323                         "org.freedesktop.login1.hibernate-ignore-inhibit",
2324                         "hybrid-sleep",
2325                         error);
2326 }
2327
2328 static int property_get_reboot_to_firmware_setup(
2329                 sd_bus *bus,
2330                 const char *path,
2331                 const char *interface,
2332                 const char *property,
2333                 sd_bus_message *reply,
2334                 void *userdata,
2335                 sd_bus_error *error) {
2336 #if 0 /// elogind does not support EFI
2337         int r;
2338
2339         assert(bus);
2340         assert(reply);
2341         assert(userdata);
2342
2343         r = efi_get_reboot_to_firmware();
2344         if (r < 0 && r != -EOPNOTSUPP)
2345                 return r;
2346
2347         return sd_bus_message_append(reply, "b", r > 0);
2348 #else
2349         return sd_bus_message_append(reply, "b", -EOPNOTSUPP);
2350 #endif // 0
2351 }
2352
2353 static int method_set_reboot_to_firmware_setup(
2354                 sd_bus_message *message,
2355                 void *userdata,
2356                 sd_bus_error *error) {
2357
2358         int b, r;
2359         Manager *m = userdata;
2360
2361         assert(message);
2362         assert(m);
2363
2364         r = sd_bus_message_read(message, "b", &b);
2365         if (r < 0)
2366                 return r;
2367
2368         r = bus_verify_polkit_async(message,
2369                                     CAP_SYS_ADMIN,
2370                                     "org.freedesktop.login1.set-reboot-to-firmware-setup",
2371                                     NULL,
2372                                     false,
2373                                     UID_INVALID,
2374                                     &m->polkit_registry,
2375                                     error);
2376         if (r < 0)
2377                 return r;
2378         if (r == 0)
2379                 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
2380
2381 #if 0 /// elogind does not support EFI
2382         r = efi_set_reboot_to_firmware(b);
2383         if (r < 0)
2384                 return r;
2385 #endif // 0
2386
2387         return sd_bus_reply_method_return(message, NULL);
2388 }
2389
2390 static int method_can_reboot_to_firmware_setup(
2391                 sd_bus_message *message,
2392                 void *userdata,
2393                 sd_bus_error *error) {
2394
2395 #if 0 /// elogind does not support EFI
2396         int r;
2397         bool challenge;
2398         const char *result;
2399         Manager *m = userdata;
2400
2401         assert(message);
2402         assert(m);
2403
2404         r = efi_reboot_to_firmware_supported();
2405         if (r == -EOPNOTSUPP)
2406                 return sd_bus_reply_method_return(message, "s", "na");
2407         else if (r < 0)
2408                 return r;
2409
2410         r = bus_test_polkit(message,
2411                             CAP_SYS_ADMIN,
2412                             "org.freedesktop.login1.set-reboot-to-firmware-setup",
2413                             NULL,
2414                             UID_INVALID,
2415                             &challenge,
2416                             error);
2417         if (r < 0)
2418                 return r;
2419
2420         if (r > 0)
2421                 result = "yes";
2422         else if (challenge)
2423                 result = "challenge";
2424         else
2425                 result = "no";
2426
2427         return sd_bus_reply_method_return(message, "s", result);
2428 #else
2429         return sd_bus_reply_method_return(message, "s", "na");
2430 #endif // 0
2431 }
2432
2433 static int method_set_wall_message(
2434                 sd_bus_message *message,
2435                 void *userdata,
2436                 sd_bus_error *error) {
2437
2438         int r;
2439         Manager *m = userdata;
2440         char *wall_message;
2441         int enable_wall_messages;
2442
2443         assert(message);
2444         assert(m);
2445
2446         r = sd_bus_message_read(message, "sb", &wall_message, &enable_wall_messages);
2447         if (r < 0)
2448                 return r;
2449
2450         r = bus_verify_polkit_async(message,
2451                                     CAP_SYS_ADMIN,
2452                                     "org.freedesktop.login1.set-wall-message",
2453                                     NULL,
2454                                     false,
2455                                     UID_INVALID,
2456                                     &m->polkit_registry,
2457                                     error);
2458         if (r < 0)
2459                 return r;
2460         if (r == 0)
2461                 return 1; /* Will call us back */
2462
2463         if (isempty(wall_message))
2464                 m->wall_message = mfree(m->wall_message);
2465         else {
2466                 r = free_and_strdup(&m->wall_message, wall_message);
2467                 if (r < 0)
2468                         return log_oom();
2469         }
2470
2471         m->enable_wall_messages = enable_wall_messages;
2472
2473         return sd_bus_reply_method_return(message, NULL);
2474 }
2475
2476 static int method_inhibit(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2477         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
2478         const char *who, *why, *what, *mode;
2479         _cleanup_free_ char *id = NULL;
2480         _cleanup_close_ int fifo_fd = -1;
2481         Manager *m = userdata;
2482         Inhibitor *i = NULL;
2483         InhibitMode mm;
2484         InhibitWhat w;
2485         pid_t pid;
2486         uid_t uid;
2487         int r;
2488
2489         assert(message);
2490         assert(m);
2491
2492         r = sd_bus_message_read(message, "ssss", &what, &who, &why, &mode);
2493         if (r < 0)
2494                 return r;
2495
2496         w = inhibit_what_from_string(what);
2497         if (w <= 0)
2498                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid what specification %s", what);
2499
2500         mm = inhibit_mode_from_string(mode);
2501         if (mm < 0)
2502                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid mode specification %s", mode);
2503
2504         /* Delay is only supported for shutdown/sleep */
2505         if (mm == INHIBIT_DELAY && (w & ~(INHIBIT_SHUTDOWN|INHIBIT_SLEEP)))
2506                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Delay inhibitors only supported for shutdown and sleep");
2507
2508         /* Don't allow taking delay locks while we are already
2509          * executing the operation. We shouldn't create the impression
2510          * that the lock was successful if the machine is about to go
2511          * down/suspend any moment. */
2512         if (m->action_what & w)
2513                 return sd_bus_error_setf(error, BUS_ERROR_OPERATION_IN_PROGRESS, "The operation inhibition has been requested for is already running");
2514
2515         r = bus_verify_polkit_async(
2516                         message,
2517                         CAP_SYS_BOOT,
2518                         w == INHIBIT_SHUTDOWN             ? (mm == INHIBIT_BLOCK ? "org.freedesktop.login1.inhibit-block-shutdown" : "org.freedesktop.login1.inhibit-delay-shutdown") :
2519                         w == INHIBIT_SLEEP                ? (mm == INHIBIT_BLOCK ? "org.freedesktop.login1.inhibit-block-sleep"    : "org.freedesktop.login1.inhibit-delay-sleep") :
2520                         w == INHIBIT_IDLE                 ? "org.freedesktop.login1.inhibit-block-idle" :
2521                         w == INHIBIT_HANDLE_POWER_KEY     ? "org.freedesktop.login1.inhibit-handle-power-key" :
2522                         w == INHIBIT_HANDLE_SUSPEND_KEY   ? "org.freedesktop.login1.inhibit-handle-suspend-key" :
2523                         w == INHIBIT_HANDLE_HIBERNATE_KEY ? "org.freedesktop.login1.inhibit-handle-hibernate-key" :
2524                                                             "org.freedesktop.login1.inhibit-handle-lid-switch",
2525                         NULL,
2526                         false,
2527                         UID_INVALID,
2528                         &m->polkit_registry,
2529                         error);
2530         if (r < 0)
2531                 return r;
2532         if (r == 0)
2533                 return 1; /* No authorization for now, but the async polkit stuff will call us again when it has it */
2534
2535         r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_EUID|SD_BUS_CREDS_PID, &creds);
2536         if (r < 0)
2537                 return r;
2538
2539         r = sd_bus_creds_get_euid(creds, &uid);
2540         if (r < 0)
2541                 return r;
2542
2543         r = sd_bus_creds_get_pid(creds, &pid);
2544         if (r < 0)
2545                 return r;
2546
2547         if (hashmap_size(m->inhibitors) >= m->inhibitors_max)
2548                 return sd_bus_error_setf(error, SD_BUS_ERROR_LIMITS_EXCEEDED, "Maximum number of inhibitors (%" PRIu64 ") reached, refusing further inhibitors.", m->inhibitors_max);
2549
2550         do {
2551                 id = mfree(id);
2552
2553                 if (asprintf(&id, "%lu", ++m->inhibit_counter) < 0)
2554                         return -ENOMEM;
2555
2556         } while (hashmap_get(m->inhibitors, id));
2557
2558         r = manager_add_inhibitor(m, id, &i);
2559         if (r < 0)
2560                 return r;
2561
2562         i->what = w;
2563         i->mode = mm;
2564         i->pid = pid;
2565         i->uid = uid;
2566         i->why = strdup(why);
2567         i->who = strdup(who);
2568
2569         if (!i->why || !i->who) {
2570                 r = -ENOMEM;
2571                 goto fail;
2572         }
2573
2574         fifo_fd = inhibitor_create_fifo(i);
2575         if (fifo_fd < 0) {
2576                 r = fifo_fd;
2577                 goto fail;
2578         }
2579
2580         inhibitor_start(i);
2581
2582         return sd_bus_reply_method_return(message, "h", fifo_fd);
2583
2584 fail:
2585         if (i)
2586                 inhibitor_free(i);
2587
2588         return r;
2589 }
2590
2591 const sd_bus_vtable manager_vtable[] = {
2592         SD_BUS_VTABLE_START(0),
2593
2594         SD_BUS_WRITABLE_PROPERTY("EnableWallMessages", "b", NULL, NULL, offsetof(Manager, enable_wall_messages), 0),
2595         SD_BUS_WRITABLE_PROPERTY("WallMessage", "s", NULL, NULL, offsetof(Manager, wall_message), 0),
2596
2597 //        SD_BUS_PROPERTY("NAutoVTs", "u", NULL, offsetof(Manager, n_autovts), SD_BUS_VTABLE_PROPERTY_CONST),
2598         SD_BUS_PROPERTY("KillOnlyUsers", "as", NULL, offsetof(Manager, kill_only_users), SD_BUS_VTABLE_PROPERTY_CONST),
2599         SD_BUS_PROPERTY("KillExcludeUsers", "as", NULL, offsetof(Manager, kill_exclude_users), SD_BUS_VTABLE_PROPERTY_CONST),
2600         SD_BUS_PROPERTY("KillUserProcesses", "b", NULL, offsetof(Manager, kill_user_processes), SD_BUS_VTABLE_PROPERTY_CONST),
2601         SD_BUS_PROPERTY("RebootToFirmwareSetup", "b", property_get_reboot_to_firmware_setup, 0, SD_BUS_VTABLE_PROPERTY_CONST),
2602         SD_BUS_PROPERTY("IdleHint", "b", property_get_idle_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
2603         SD_BUS_PROPERTY("IdleSinceHint", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
2604         SD_BUS_PROPERTY("IdleSinceHintMonotonic", "t", property_get_idle_since_hint, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
2605         SD_BUS_PROPERTY("BlockInhibited", "s", property_get_inhibited, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
2606         SD_BUS_PROPERTY("DelayInhibited", "s", property_get_inhibited, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
2607         SD_BUS_PROPERTY("InhibitDelayMaxUSec", "t", NULL, offsetof(Manager, inhibit_delay_max), SD_BUS_VTABLE_PROPERTY_CONST),
2608         SD_BUS_PROPERTY("HandlePowerKey", "s", property_get_handle_action, offsetof(Manager, handle_power_key), SD_BUS_VTABLE_PROPERTY_CONST),
2609         SD_BUS_PROPERTY("HandleSuspendKey", "s", property_get_handle_action, offsetof(Manager, handle_suspend_key), SD_BUS_VTABLE_PROPERTY_CONST),
2610         SD_BUS_PROPERTY("HandleHibernateKey", "s", property_get_handle_action, offsetof(Manager, handle_hibernate_key), SD_BUS_VTABLE_PROPERTY_CONST),
2611         SD_BUS_PROPERTY("HandleLidSwitch", "s", property_get_handle_action, offsetof(Manager, handle_lid_switch), SD_BUS_VTABLE_PROPERTY_CONST),
2612         SD_BUS_PROPERTY("HandleLidSwitchDocked", "s", property_get_handle_action, offsetof(Manager, handle_lid_switch_docked), SD_BUS_VTABLE_PROPERTY_CONST),
2613         SD_BUS_PROPERTY("HoldoffTimeoutUSec", "t", NULL, offsetof(Manager, holdoff_timeout_usec), SD_BUS_VTABLE_PROPERTY_CONST),
2614         SD_BUS_PROPERTY("IdleAction", "s", property_get_handle_action, offsetof(Manager, idle_action), SD_BUS_VTABLE_PROPERTY_CONST),
2615         SD_BUS_PROPERTY("IdleActionUSec", "t", NULL, offsetof(Manager, idle_action_usec), SD_BUS_VTABLE_PROPERTY_CONST),
2616         SD_BUS_PROPERTY("PreparingForShutdown", "b", property_get_preparing, 0, 0),
2617         SD_BUS_PROPERTY("PreparingForSleep", "b", property_get_preparing, 0, 0),
2618         SD_BUS_PROPERTY("ScheduledShutdown", "(st)", property_get_scheduled_shutdown, 0, 0),
2619         SD_BUS_PROPERTY("Docked", "b", property_get_docked, 0, 0),
2620         SD_BUS_PROPERTY("RemoveIPC", "b", bus_property_get_bool, offsetof(Manager, remove_ipc), SD_BUS_VTABLE_PROPERTY_CONST),
2621         SD_BUS_PROPERTY("RuntimeDirectorySize", "t", bus_property_get_size, offsetof(Manager, runtime_dir_size), SD_BUS_VTABLE_PROPERTY_CONST),
2622         SD_BUS_PROPERTY("InhibitorsMax", "t", NULL, offsetof(Manager, inhibitors_max), SD_BUS_VTABLE_PROPERTY_CONST),
2623         SD_BUS_PROPERTY("NCurrentInhibitors", "t", property_get_current_inhibitors, 0, 0),
2624         SD_BUS_PROPERTY("SessionsMax", "t", NULL, offsetof(Manager, sessions_max), SD_BUS_VTABLE_PROPERTY_CONST),
2625         SD_BUS_PROPERTY("NCurrentSessions", "t", property_get_current_sessions, 0, 0),
2626         SD_BUS_PROPERTY("UserTasksMax", "t", NULL, offsetof(Manager, user_tasks_max), SD_BUS_VTABLE_PROPERTY_CONST),
2627
2628         SD_BUS_METHOD("GetSession", "s", "o", method_get_session, SD_BUS_VTABLE_UNPRIVILEGED),
2629         SD_BUS_METHOD("GetSessionByPID", "u", "o", method_get_session_by_pid, SD_BUS_VTABLE_UNPRIVILEGED),
2630         SD_BUS_METHOD("GetUser", "u", "o", method_get_user, SD_BUS_VTABLE_UNPRIVILEGED),
2631         SD_BUS_METHOD("GetUserByPID", "u", "o", method_get_user_by_pid, SD_BUS_VTABLE_UNPRIVILEGED),
2632         SD_BUS_METHOD("GetSeat", "s", "o", method_get_seat, SD_BUS_VTABLE_UNPRIVILEGED),
2633         SD_BUS_METHOD("ListSessions", NULL, "a(susso)", method_list_sessions, SD_BUS_VTABLE_UNPRIVILEGED),
2634         SD_BUS_METHOD("ListUsers", NULL, "a(uso)", method_list_users, SD_BUS_VTABLE_UNPRIVILEGED),
2635         SD_BUS_METHOD("ListSeats", NULL, "a(so)", method_list_seats, SD_BUS_VTABLE_UNPRIVILEGED),
2636         SD_BUS_METHOD("ListInhibitors", NULL, "a(ssssuu)", method_list_inhibitors, SD_BUS_VTABLE_UNPRIVILEGED),
2637         SD_BUS_METHOD("CreateSession", "uusssssussbssa(sv)", "soshusub", method_create_session, 0),
2638         SD_BUS_METHOD("ReleaseSession", "s", NULL, method_release_session, 0),
2639         SD_BUS_METHOD("ActivateSession", "s", NULL, method_activate_session, SD_BUS_VTABLE_UNPRIVILEGED),
2640         SD_BUS_METHOD("ActivateSessionOnSeat", "ss", NULL, method_activate_session_on_seat, SD_BUS_VTABLE_UNPRIVILEGED),
2641         SD_BUS_METHOD("LockSession", "s", NULL, method_lock_session, SD_BUS_VTABLE_UNPRIVILEGED),
2642         SD_BUS_METHOD("UnlockSession", "s", NULL, method_lock_session, SD_BUS_VTABLE_UNPRIVILEGED),
2643         SD_BUS_METHOD("LockSessions", NULL, NULL, method_lock_sessions, SD_BUS_VTABLE_UNPRIVILEGED),
2644         SD_BUS_METHOD("UnlockSessions", NULL, NULL, method_lock_sessions, SD_BUS_VTABLE_UNPRIVILEGED),
2645         SD_BUS_METHOD("KillSession", "ssi", NULL, method_kill_session, SD_BUS_VTABLE_UNPRIVILEGED),
2646         SD_BUS_METHOD("KillUser", "ui", NULL, method_kill_user, SD_BUS_VTABLE_UNPRIVILEGED),
2647         SD_BUS_METHOD("TerminateSession", "s", NULL, method_terminate_session, SD_BUS_VTABLE_UNPRIVILEGED),
2648         SD_BUS_METHOD("TerminateUser", "u", NULL, method_terminate_user, SD_BUS_VTABLE_UNPRIVILEGED),
2649         SD_BUS_METHOD("TerminateSeat", "s", NULL, method_terminate_seat, SD_BUS_VTABLE_UNPRIVILEGED),
2650         SD_BUS_METHOD("SetUserLinger", "ubb", NULL, method_set_user_linger, SD_BUS_VTABLE_UNPRIVILEGED),
2651         SD_BUS_METHOD("AttachDevice", "ssb", NULL, method_attach_device, SD_BUS_VTABLE_UNPRIVILEGED),
2652         SD_BUS_METHOD("FlushDevices", "b", NULL, method_flush_devices, SD_BUS_VTABLE_UNPRIVILEGED),
2653         SD_BUS_METHOD("PowerOff", "b", NULL, method_poweroff, SD_BUS_VTABLE_UNPRIVILEGED),
2654         SD_BUS_METHOD("Reboot", "b", NULL, method_reboot, SD_BUS_VTABLE_UNPRIVILEGED),
2655         SD_BUS_METHOD("Suspend", "b", NULL, method_suspend, SD_BUS_VTABLE_UNPRIVILEGED),
2656         SD_BUS_METHOD("Hibernate", "b", NULL, method_hibernate, SD_BUS_VTABLE_UNPRIVILEGED),
2657         SD_BUS_METHOD("HybridSleep", "b", NULL, method_hybrid_sleep, SD_BUS_VTABLE_UNPRIVILEGED),
2658         SD_BUS_METHOD("CanPowerOff", NULL, "s", method_can_poweroff, SD_BUS_VTABLE_UNPRIVILEGED),
2659         SD_BUS_METHOD("CanReboot", NULL, "s", method_can_reboot, SD_BUS_VTABLE_UNPRIVILEGED),
2660         SD_BUS_METHOD("CanSuspend", NULL, "s", method_can_suspend, SD_BUS_VTABLE_UNPRIVILEGED),
2661         SD_BUS_METHOD("CanHibernate", NULL, "s", method_can_hibernate, SD_BUS_VTABLE_UNPRIVILEGED),
2662         SD_BUS_METHOD("CanHybridSleep", NULL, "s", method_can_hybrid_sleep, SD_BUS_VTABLE_UNPRIVILEGED),
2663         SD_BUS_METHOD("ScheduleShutdown", "st", NULL, method_schedule_shutdown, SD_BUS_VTABLE_UNPRIVILEGED),
2664         SD_BUS_METHOD("CancelScheduledShutdown", NULL, "b", method_cancel_scheduled_shutdown, SD_BUS_VTABLE_UNPRIVILEGED),
2665         SD_BUS_METHOD("Inhibit", "ssss", "h", method_inhibit, SD_BUS_VTABLE_UNPRIVILEGED),
2666         SD_BUS_METHOD("CanRebootToFirmwareSetup", NULL, "s", method_can_reboot_to_firmware_setup, SD_BUS_VTABLE_UNPRIVILEGED),
2667         SD_BUS_METHOD("SetRebootToFirmwareSetup", "b", NULL, method_set_reboot_to_firmware_setup, SD_BUS_VTABLE_UNPRIVILEGED),
2668         SD_BUS_METHOD("SetWallMessage", "sb", NULL, method_set_wall_message, SD_BUS_VTABLE_UNPRIVILEGED),
2669
2670         SD_BUS_SIGNAL("SessionNew", "so", 0),
2671         SD_BUS_SIGNAL("SessionRemoved", "so", 0),
2672         SD_BUS_SIGNAL("UserNew", "uo", 0),
2673         SD_BUS_SIGNAL("UserRemoved", "uo", 0),
2674         SD_BUS_SIGNAL("SeatNew", "so", 0),
2675         SD_BUS_SIGNAL("SeatRemoved", "so", 0),
2676         SD_BUS_SIGNAL("PrepareForShutdown", "b", 0),
2677         SD_BUS_SIGNAL("PrepareForSleep", "b", 0),
2678
2679         SD_BUS_VTABLE_END
2680 };
2681
2682 #if 0 /// UNNEEDED by elogind
2683 static int session_jobs_reply(Session *s, const char *unit, const char *result) {
2684         int r = 0;
2685
2686         assert(s);
2687         assert(unit);
2688
2689         if (!s->started)
2690                 return r;
2691
2692         if (streq(result, "done"))
2693                 r = session_send_create_reply(s, NULL);
2694         else {
2695                 _cleanup_(sd_bus_error_free) sd_bus_error e = SD_BUS_ERROR_NULL;
2696
2697                 sd_bus_error_setf(&e, BUS_ERROR_JOB_FAILED, "Start job for unit %s failed with '%s'", unit, result);
2698                 r = session_send_create_reply(s, &e);
2699         }
2700
2701         return r;
2702 }
2703
2704 int match_job_removed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2705         const char *path, *result, *unit;
2706         Manager *m = userdata;
2707         Session *session;
2708         uint32_t id;
2709         User *user;
2710         int r;
2711
2712         assert(message);
2713         assert(m);
2714
2715         r = sd_bus_message_read(message, "uoss", &id, &path, &unit, &result);
2716         if (r < 0) {
2717                 bus_log_parse_error(r);
2718                 return 0;
2719         }
2720
2721         if (m->action_job && streq(m->action_job, path)) {
2722                 log_info("Operation '%s' finished.", inhibit_what_to_string(m->action_what));
2723
2724                 /* Tell people that they now may take a lock again */
2725                 send_prepare_for(m, m->action_what, false);
2726
2727                 m->action_job = mfree(m->action_job);
2728                 m->action_unit = NULL;
2729                 m->action_what = 0;
2730                 return 0;
2731         }
2732
2733         session = hashmap_get(m->session_units, unit);
2734         if (session && streq_ptr(path, session->scope_job)) {
2735                 session->scope_job = mfree(session->scope_job);
2736                 session_jobs_reply(session, unit, result);
2737
2738                 session_save(session);
2739                 user_save(session->user);
2740                 session_add_to_gc_queue(session);
2741         }
2742
2743         user = hashmap_get(m->user_units, unit);
2744         if (user &&
2745             (streq_ptr(path, user->service_job) ||
2746              streq_ptr(path, user->slice_job))) {
2747
2748                 if (streq_ptr(path, user->service_job))
2749                         user->service_job = mfree(user->service_job);
2750
2751                 if (streq_ptr(path, user->slice_job))
2752                         user->slice_job = mfree(user->slice_job);
2753
2754                 LIST_FOREACH(sessions_by_user, session, user->sessions)
2755                         session_jobs_reply(session, unit, result);
2756
2757                 user_save(user);
2758                 user_add_to_gc_queue(user);
2759         }
2760
2761         return 0;
2762 }
2763
2764 int match_unit_removed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2765         const char *path, *unit;
2766         Manager *m = userdata;
2767         Session *session;
2768         User *user;
2769         int r;
2770
2771         assert(message);
2772         assert(m);
2773
2774         r = sd_bus_message_read(message, "so", &unit, &path);
2775         if (r < 0) {
2776                 bus_log_parse_error(r);
2777                 return 0;
2778         }
2779
2780         session = hashmap_get(m->session_units, unit);
2781         if (session)
2782                 session_add_to_gc_queue(session);
2783
2784         user = hashmap_get(m->user_units, unit);
2785         if (user)
2786                 user_add_to_gc_queue(user);
2787
2788         return 0;
2789 }
2790
2791 int match_properties_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2792         _cleanup_free_ char *unit = NULL;
2793         Manager *m = userdata;
2794         const char *path;
2795         Session *session;
2796         User *user;
2797         int r;
2798
2799         assert(message);
2800         assert(m);
2801
2802         path = sd_bus_message_get_path(message);
2803         if (!path)
2804                 return 0;
2805
2806         r = unit_name_from_dbus_path(path, &unit);
2807         if (r == -EINVAL) /* not a unit */
2808                 return 0;
2809         if (r < 0) {
2810                 log_oom();
2811                 return 0;
2812         }
2813
2814         session = hashmap_get(m->session_units, unit);
2815         if (session)
2816                 session_add_to_gc_queue(session);
2817
2818         user = hashmap_get(m->user_units, unit);
2819         if (user)
2820                 user_add_to_gc_queue(user);
2821
2822         return 0;
2823 }
2824
2825 int match_reloading(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2826         Manager *m = userdata;
2827         Session *session;
2828         Iterator i;
2829         int b, r;
2830
2831         assert(message);
2832         assert(m);
2833
2834         r = sd_bus_message_read(message, "b", &b);
2835         if (r < 0) {
2836                 bus_log_parse_error(r);
2837                 return 0;
2838         }
2839
2840         if (b)
2841                 return 0;
2842
2843         /* systemd finished reloading, let's recheck all our sessions */
2844         log_debug("System manager has been reloaded, rechecking sessions...");
2845
2846         HASHMAP_FOREACH(session, m->sessions, i)
2847                 session_add_to_gc_queue(session);
2848
2849         return 0;
2850 }
2851 #endif // 0
2852
2853 int manager_send_changed(Manager *manager, const char *property, ...) {
2854         char **l;
2855
2856         assert(manager);
2857
2858         l = strv_from_stdarg_alloca(property);
2859
2860         return sd_bus_emit_properties_changed_strv(
2861                         manager->bus,
2862                         "/org/freedesktop/login1",
2863                         "org.freedesktop.login1.Manager",
2864                         l);
2865 }
2866
2867 #if 0 /// UNNEEDED by elogind
2868 static int strdup_job(sd_bus_message *reply, char **job) {
2869         const char *j;
2870         char *copy;
2871         int r;
2872
2873         r = sd_bus_message_read(reply, "o", &j);
2874         if (r < 0)
2875                 return r;
2876
2877         copy = strdup(j);
2878         if (!copy)
2879                 return -ENOMEM;
2880
2881         *job = copy;
2882         return 1;
2883 }
2884
2885 int manager_start_slice(
2886                 Manager *manager,
2887                 const char *slice,
2888                 const char *description,
2889                 const char *after,
2890                 const char *after2,
2891                 uint64_t tasks_max,
2892                 sd_bus_error *error,
2893                 char **job) {
2894
2895         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2896         int r;
2897
2898         assert(manager);
2899         assert(slice);
2900
2901         r = sd_bus_message_new_method_call(
2902                         manager->bus,
2903                         &m,
2904                         "org.freedesktop.systemd1",
2905                         "/org/freedesktop/systemd1",
2906                         "org.freedesktop.systemd1.Manager",
2907                         "StartTransientUnit");
2908         if (r < 0)
2909                 return r;
2910
2911         r = sd_bus_message_append(m, "ss", strempty(slice), "fail");
2912         if (r < 0)
2913                 return r;
2914
2915         r = sd_bus_message_open_container(m, 'a', "(sv)");
2916         if (r < 0)
2917                 return r;
2918
2919         if (!isempty(description)) {
2920                 r = sd_bus_message_append(m, "(sv)", "Description", "s", description);
2921                 if (r < 0)
2922                         return r;
2923         }
2924
2925         if (!isempty(after)) {
2926                 r = sd_bus_message_append(m, "(sv)", "After", "as", 1, after);
2927                 if (r < 0)
2928                         return r;
2929         }
2930
2931         if (!isempty(after2)) {
2932                 r = sd_bus_message_append(m, "(sv)", "After", "as", 1, after2);
2933                 if (r < 0)
2934                         return r;
2935         }
2936
2937         r = sd_bus_message_append(m, "(sv)", "TasksMax", "t", tasks_max);
2938         if (r < 0)
2939                 return r;
2940
2941         r = sd_bus_message_close_container(m);
2942         if (r < 0)
2943                 return r;
2944
2945         r = sd_bus_message_append(m, "a(sa(sv))", 0);
2946         if (r < 0)
2947                 return r;
2948
2949         r = sd_bus_call(manager->bus, m, 0, error, &reply);
2950         if (r < 0)
2951                 return r;
2952
2953         if (job)
2954                 return strdup_job(reply, job);
2955         return 1;
2956 }
2957
2958 int manager_start_scope(
2959                 Manager *manager,
2960                 const char *scope,
2961                 pid_t pid,
2962                 const char *slice,
2963                 const char *description,
2964                 const char *after,
2965                 const char *after2,
2966                 uint64_t tasks_max,
2967                 sd_bus_error *error,
2968                 char **job) {
2969
2970         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2971         int r;
2972
2973         assert(manager);
2974         assert(scope);
2975         assert(pid > 1);
2976
2977         r = sd_bus_message_new_method_call(
2978                         manager->bus,
2979                         &m,
2980                         "org.freedesktop.systemd1",
2981                         "/org/freedesktop/systemd1",
2982                         "org.freedesktop.systemd1.Manager",
2983                         "StartTransientUnit");
2984         if (r < 0)
2985                 return r;
2986
2987         r = sd_bus_message_append(m, "ss", strempty(scope), "fail");
2988         if (r < 0)
2989                 return r;
2990
2991         r = sd_bus_message_open_container(m, 'a', "(sv)");
2992         if (r < 0)
2993                 return r;
2994
2995         if (!isempty(slice)) {
2996                 r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
2997                 if (r < 0)
2998                         return r;
2999         }
3000
3001         if (!isempty(description)) {
3002                 r = sd_bus_message_append(m, "(sv)", "Description", "s", description);
3003                 if (r < 0)
3004                         return r;
3005         }
3006
3007         if (!isempty(after)) {
3008                 r = sd_bus_message_append(m, "(sv)", "After", "as", 1, after);
3009                 if (r < 0)
3010                         return r;
3011         }
3012
3013         if (!isempty(after2)) {
3014                 r = sd_bus_message_append(m, "(sv)", "After", "as", 1, after2);
3015                 if (r < 0)
3016                         return r;
3017         }
3018
3019         /* cgroup empty notification is not available in containers
3020          * currently. To make this less problematic, let's shorten the
3021          * stop timeout for sessions, so that we don't wait
3022          * forever. */
3023
3024         /* Make sure that the session shells are terminated with
3025          * SIGHUP since bash and friends tend to ignore SIGTERM */
3026         r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", true);
3027         if (r < 0)
3028                 return r;
3029
3030         r = sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, pid);
3031         if (r < 0)
3032                 return r;
3033
3034         r = sd_bus_message_append(m, "(sv)", "TasksMax", "t", tasks_max);
3035         if (r < 0)
3036                 return r;
3037
3038         r = sd_bus_message_close_container(m);
3039         if (r < 0)
3040                 return r;
3041
3042         r = sd_bus_message_append(m, "a(sa(sv))", 0);
3043         if (r < 0)
3044                 return r;
3045
3046         r = sd_bus_call(manager->bus, m, 0, error, &reply);
3047         if (r < 0)
3048                 return r;
3049
3050         if (job)
3051                 return strdup_job(reply, job);
3052         return 1;
3053 }
3054
3055 int manager_start_unit(Manager *manager, const char *unit, sd_bus_error *error, char **job) {
3056         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
3057         int r;
3058
3059         assert(manager);
3060         assert(unit);
3061
3062         r = sd_bus_call_method(
3063                         manager->bus,
3064                         "org.freedesktop.systemd1",
3065                         "/org/freedesktop/systemd1",
3066                         "org.freedesktop.systemd1.Manager",
3067                         "StartUnit",
3068                         error,
3069                         &reply,
3070                         "ss", unit, "replace");
3071         if (r < 0)
3072                 return r;
3073
3074         if (job)
3075                 return strdup_job(reply, job);
3076         return 1;
3077 }
3078
3079 int manager_stop_unit(Manager *manager, const char *unit, sd_bus_error *error, char **job) {
3080         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
3081         int r;
3082
3083         assert(manager);
3084         assert(unit);
3085
3086         r = sd_bus_call_method(
3087                         manager->bus,
3088                         "org.freedesktop.systemd1",
3089                         "/org/freedesktop/systemd1",
3090                         "org.freedesktop.systemd1.Manager",
3091                         "StopUnit",
3092                         error,
3093                         &reply,
3094                         "ss", unit, "fail");
3095         if (r < 0) {
3096                 if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT) ||
3097                     sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED)) {
3098
3099                         if (job)
3100                                 *job = NULL;
3101
3102                         sd_bus_error_free(error);
3103                         return 0;
3104                 }
3105
3106                 return r;
3107         }
3108
3109         if (job)
3110                 return strdup_job(reply, job);
3111         return 1;
3112 }
3113
3114 int manager_abandon_scope(Manager *manager, const char *scope, sd_bus_error *error) {
3115         _cleanup_free_ char *path = NULL;
3116         int r;
3117
3118         assert(manager);
3119         assert(scope);
3120
3121         path = unit_dbus_path_from_name(scope);
3122         if (!path)
3123                 return -ENOMEM;
3124
3125         r = sd_bus_call_method(
3126                         manager->bus,
3127                         "org.freedesktop.systemd1",
3128                         path,
3129                         "org.freedesktop.systemd1.Scope",
3130                         "Abandon",
3131                         error,
3132                         NULL,
3133                         NULL);
3134         if (r < 0) {
3135                 if (sd_bus_error_has_name(error, BUS_ERROR_NO_SUCH_UNIT) ||
3136                     sd_bus_error_has_name(error, BUS_ERROR_LOAD_FAILED) ||
3137                     sd_bus_error_has_name(error, BUS_ERROR_SCOPE_NOT_RUNNING)) {
3138                         sd_bus_error_free(error);
3139                         return 0;
3140                 }
3141
3142                 return r;
3143         }
3144
3145         return 1;
3146 }
3147
3148 int manager_kill_unit(Manager *manager, const char *unit, KillWho who, int signo, sd_bus_error *error) {
3149         assert(manager);
3150         assert(unit);
3151
3152         return sd_bus_call_method(
3153                         manager->bus,
3154                         "org.freedesktop.systemd1",
3155                         "/org/freedesktop/systemd1",
3156                         "org.freedesktop.systemd1.Manager",
3157                         "KillUnit",
3158                         error,
3159                         NULL,
3160                         "ssi", unit, who == KILL_LEADER ? "main" : "all", signo);
3161 }
3162
3163 int manager_unit_is_active(Manager *manager, const char *unit) {
3164         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3165         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
3166         _cleanup_free_ char *path = NULL;
3167         const char *state;
3168         int r;
3169
3170         assert(manager);
3171         assert(unit);
3172
3173         path = unit_dbus_path_from_name(unit);
3174         if (!path)
3175                 return -ENOMEM;
3176
3177         r = sd_bus_get_property(
3178                         manager->bus,
3179                         "org.freedesktop.systemd1",
3180                         path,
3181                         "org.freedesktop.systemd1.Unit",
3182                         "ActiveState",
3183                         &error,
3184                         &reply,
3185                         "s");
3186         if (r < 0) {
3187                 /* systemd might have droppped off momentarily, let's
3188                  * not make this an error */
3189                 if (sd_bus_error_has_name(&error, SD_BUS_ERROR_NO_REPLY) ||
3190                     sd_bus_error_has_name(&error, SD_BUS_ERROR_DISCONNECTED))
3191                         return true;
3192
3193                 /* If the unit is already unloaded then it's not
3194                  * active */
3195                 if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT) ||
3196                     sd_bus_error_has_name(&error, BUS_ERROR_LOAD_FAILED))
3197                         return false;
3198
3199                 return r;
3200         }
3201
3202         r = sd_bus_message_read(reply, "s", &state);
3203         if (r < 0)
3204                 return -EINVAL;
3205
3206         return !streq(state, "inactive") && !streq(state, "failed");
3207 }
3208
3209 int manager_job_is_active(Manager *manager, const char *path) {
3210         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3211         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
3212         int r;
3213
3214         assert(manager);
3215         assert(path);
3216
3217         r = sd_bus_get_property(
3218                         manager->bus,
3219                         "org.freedesktop.systemd1",
3220                         path,
3221                         "org.freedesktop.systemd1.Job",
3222                         "State",
3223                         &error,
3224                         &reply,
3225                         "s");
3226         if (r < 0) {
3227                 if (sd_bus_error_has_name(&error, SD_BUS_ERROR_NO_REPLY) ||
3228                     sd_bus_error_has_name(&error, SD_BUS_ERROR_DISCONNECTED))
3229                         return true;
3230
3231                 if (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_OBJECT))
3232                         return false;
3233
3234                 return r;
3235         }
3236
3237         /* We don't actually care about the state really. The fact
3238          * that we could read the job state is enough for us */
3239
3240         return true;
3241 }
3242 #endif // 0