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