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