chiark / gitweb /
111c770b5c9719751cfea881b22729b35bca1529
[elogind.git] / src / login / eloginctl.c
1 /***
2   This file is part of elogind.
3
4   Copyright 2017 Sven Eden
5
6   elogind is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   elogind is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with elogind; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20
21 #include "bus-error.h"
22 #include "bus-util.h"
23 #include "eloginctl.h"
24 #include "logind-action.h"
25 #include "parse-util.h"
26 #include "process-util.h"
27 #include "sd-login.h"
28 #include "sd-messages.h"
29 #include "spawn-polkit-agent.h"
30 #include "string-util.h"
31 #include "strv.h"
32 #include "terminal-util.h"
33 #include "user-util.h"
34 #include "virt.h"
35
36
37 elogind_action arg_action            = _ACTION_INVALID;
38 bool           arg_ask_password      = true;
39 bool           arg_dry_run           = false;
40 bool           arg_quiet             = false;
41 bool           arg_ignore_inhibitors = false;
42 bool           arg_no_wall           = false;
43 BusTransport   arg_transport         = BUS_TRANSPORT_LOCAL;
44 char**         arg_wall              = NULL;
45 usec_t         arg_when              = 0;
46
47 static const struct {
48         HandleAction action;
49         const char*  verb;
50 } action_table[_ACTION_MAX] = {
51         [ACTION_HALT]         = { HANDLE_HALT,         "halt"         },
52         [ACTION_POWEROFF]     = { HANDLE_POWEROFF,     "poweroff",    },
53         [ACTION_REBOOT]       = { HANDLE_REBOOT,       "reboot",      },
54         [ACTION_KEXEC]        = { HANDLE_KEXEC,        "kexec",       },
55         [ACTION_SUSPEND]      = { HANDLE_SUSPEND,      "suspend",     },
56         [ACTION_HIBERNATE]    = { HANDLE_HIBERNATE,    "hibernate",   },
57         [ACTION_HYBRID_SLEEP] = { HANDLE_HYBRID_SLEEP, "hybrid-sleep" }
58         /* ACTION_CANCEL_SHUTDOWN is handled differently */
59 };
60
61 static int elogind_set_wall_message(sd_bus* bus, const char* msg);
62
63 static enum elogind_action verb_to_action(const char *verb) {
64         enum elogind_action i;
65
66         for (i = _ACTION_INVALID; i < _ACTION_MAX; i++)
67                 if (streq_ptr(action_table[i].verb, verb))
68                         return i;
69
70         return _ACTION_INVALID;
71 }
72
73 /* Original:
74  * systemctl/systemctl.c:3314:logind_check_inhibitors()
75  */
76 static int check_inhibitors(sd_bus* bus, enum elogind_action a) {
77         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
78         _cleanup_strv_free_ char **sessions = NULL;
79         const char *what, *who, *why, *mode;
80         uint32_t uid, pid;
81         unsigned c = 0;
82         char **s;
83         int r;
84
85         if (arg_ignore_inhibitors)
86                 return 0;
87
88         if (arg_when > 0)
89                 return 0;
90
91         if (geteuid() == 0)
92                 return 0;
93
94         if (!on_tty())
95                 return 0;
96
97         if (arg_transport != BUS_TRANSPORT_LOCAL)
98                 return 0;
99
100         r = sd_bus_call_method(
101                         bus,
102                         "org.freedesktop.login1",
103                         "/org/freedesktop/login1",
104                         "org.freedesktop.login1.Manager",
105                         "ListInhibitors",
106                         NULL,
107                         &reply,
108                         NULL);
109         if (r < 0)
110                 /* If logind is not around, then there are no inhibitors... */
111                 return 0;
112
113         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
114         if (r < 0)
115                 return bus_log_parse_error(r);
116
117         while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
118                 _cleanup_free_ char *comm = NULL, *user = NULL;
119                 _cleanup_strv_free_ char **sv = NULL;
120
121                 if (!streq(mode, "block"))
122                         continue;
123
124                 sv = strv_split(what, ":");
125                 if (!sv)
126                         return log_oom();
127
128                 if (!pid_is_valid((pid_t) pid)) {
129                         log_error("Invalid PID "PID_FMT".", (pid_t) pid);
130                         return -ERANGE;
131                 }
132
133                 if (!strv_contains(sv,
134                                    IN_SET(a,
135                                           ACTION_HALT,
136                                           ACTION_POWEROFF,
137                                           ACTION_REBOOT,
138                                           ACTION_KEXEC) ? "shutdown" : "sleep"))
139                         continue;
140
141                 get_process_comm(pid, &comm);
142                 user = uid_to_name(uid);
143
144                 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT" \"%s\", user %s), reason is \"%s\".",
145                             who, (pid_t) pid, strna(comm), strna(user), why);
146
147                 c++;
148         }
149         if (r < 0)
150                 return bus_log_parse_error(r);
151
152         r = sd_bus_message_exit_container(reply);
153         if (r < 0)
154                 return bus_log_parse_error(r);
155
156         /* Check for current sessions */
157         sd_get_sessions(&sessions);
158         STRV_FOREACH(s, sessions) {
159                 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
160
161                 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
162                         continue;
163
164                 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
165                         continue;
166
167                 if (sd_session_get_type(*s, &type) < 0 || !STR_IN_SET(type, "x11", "wayland", "tty", "mir"))
168                         continue;
169
170                 sd_session_get_tty(*s, &tty);
171                 sd_session_get_seat(*s, &seat);
172                 sd_session_get_service(*s, &service);
173                 user = uid_to_name(uid);
174
175                 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
176                 c++;
177         }
178
179         if (c <= 0)
180                 return 0;
181
182         log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'loginctl %s -i'.",
183                   action_table[a].verb);
184
185         return -EPERM;
186 }
187
188 /* Original:
189  * systemctl/systemctl.c:8683:logind_cancel_shutdown()
190  */
191 int elogind_cancel_shutdown(sd_bus *bus) {
192         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
193         int r;
194
195         (void) elogind_set_wall_message(bus, NULL);
196
197         r = sd_bus_call_method(
198                         bus,
199                         "org.freedesktop.login1",
200                         "/org/freedesktop/login1",
201                         "org.freedesktop.login1.Manager",
202                         "CancelScheduledShutdown",
203                         &error,
204                         NULL, NULL);
205         if (r < 0)
206                 return log_warning_errno(r,
207                         "Failed to talk to elogind, shutdown hasn't been cancelled: %s",
208                         bus_error_message(&error, r));
209
210         return 0;
211 }
212
213 /* Only a little helper for cleaning up elogind specific extra stuff. */
214 void elogind_cleanup(void) {
215         polkit_agent_close();
216         strv_free(arg_wall);
217 }
218
219 /* Little debug log helper, helps debugging systemctl comands we mimic. */
220 static void elogind_log_special(enum elogind_action a) {
221 #if ENABLE_DEBUG_ELOGIND
222         switch (a) {
223         case ACTION_HALT:
224                 log_struct(LOG_INFO,
225                            LOG_MESSAGE("Halt action called."),
226                            "MESSAGE_ID=" SD_MESSAGE_SHUTDOWN_STR,
227                            NULL);
228                 break;
229         case ACTION_POWEROFF:
230                 log_struct(LOG_INFO,
231                            LOG_MESSAGE("Poweroff action called."),
232                            "MESSAGE_ID=" SD_MESSAGE_SHUTDOWN_STR,
233                            NULL);
234                 break;
235         case ACTION_REBOOT:
236                 log_struct(LOG_INFO,
237                            LOG_MESSAGE("Reboot action called."),
238                            "MESSAGE_ID=" SD_MESSAGE_SHUTDOWN_STR,
239                            NULL);
240                 break;
241         case ACTION_KEXEC:
242                 log_struct(LOG_INFO,
243                            LOG_MESSAGE("KExec action called."),
244                            "MESSAGE_ID=" SD_MESSAGE_SHUTDOWN_STR,
245                            NULL);
246                 break;
247         case ACTION_SUSPEND:
248                 log_struct(LOG_INFO,
249                            LOG_MESSAGE("Suspend action called."),
250                            "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
251                            NULL);
252                 break;
253         case ACTION_HIBERNATE:
254                 log_struct(LOG_INFO,
255                            LOG_MESSAGE("Hibernate action called."),
256                            "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
257                            NULL);
258                 break;
259         case ACTION_HYBRID_SLEEP:
260                 log_struct(LOG_INFO,
261                            LOG_MESSAGE("Hybrid-Sleep action called."),
262                            "MESSAGE_ID=" SD_MESSAGE_SLEEP_START_STR,
263                            NULL);
264                 break;
265         case ACTION_CANCEL_SHUTDOWN:
266                 log_struct(LOG_INFO,
267                            LOG_MESSAGE("Cancel Shutdown called."),
268                            "MESSAGE_ID=" SD_MESSAGE_SHUTDOWN_STR,
269                            NULL);
270                 break;
271         default:
272                 break;
273         }
274 #endif // ENABLE_DEBUG_ELOGIND
275 }
276
277 /* Original:
278  * systemctl/systemctl.c:3242:logind_reboot()
279  */
280 static int elogind_reboot(sd_bus *bus, enum elogind_action a) {
281         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
282         const char *method  = NULL, *description = NULL;
283         int r;
284         static const char *table[_ACTION_MAX] = {
285                 [ACTION_HALT]     = "The system is going down for halt NOW!",
286                 [ACTION_REBOOT]   = "The system is going down for reboot NOW!",
287                 [ACTION_POWEROFF] = "The system is going down for power-off NOW!"
288         };
289
290         if (!bus)
291                 return -EIO;
292
293         switch (a) {
294
295         case ACTION_HALT:
296                 method = "Halt";
297                 description = "halt system";
298                 break;
299
300         case ACTION_POWEROFF:
301                 method = "PowerOff";
302                 description = "power off system";
303                 break;
304
305         case ACTION_REBOOT:
306                 method = "Reboot";
307                 description = "reboot system";
308                 break;
309
310         case ACTION_SUSPEND:
311                 method = "Suspend";
312                 description = "suspend system";
313                 break;
314
315         case ACTION_HIBERNATE:
316                 method = "Hibernate";
317                 description = "hibernate system";
318                 break;
319
320         case ACTION_HYBRID_SLEEP:
321                 method = "HybridSleep";
322                 description = "put system into hybrid sleep";
323                 break;
324
325         default:
326                 return -EINVAL;
327         }
328
329         /* No need for polkit_agent_open_maybe() in elogind. Do it directly. */
330         polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
331
332         if ( IN_SET(a, ACTION_HALT, ACTION_POWEROFF, ACTION_REBOOT) )
333                 (void) elogind_set_wall_message(bus, table[a]);
334
335         log_debug("%s org.freedesktop.login1.Manager %s dbus call.", arg_dry_run ? "Would execute" : "Executing", method);
336
337         if (arg_dry_run)
338                 return 0;
339
340         /* Now call elogind itself to request the operation */
341         r = sd_bus_call_method(
342                         bus,
343                         "org.freedesktop.login1",
344                         "/org/freedesktop/login1",
345                         "org.freedesktop.login1.Manager",
346                         method,
347                         &error,
348                         NULL,
349                         "b", arg_ask_password);
350
351         if (r < 0)
352                 return log_error_errno(r, "Failed to %s via elogind: %s",
353                                        description,
354                                        bus_error_message(&error, r));
355
356         return 0;
357 }
358
359 /* Original:
360  * systemctl/systemctl.c:8553:logind_schedule_shutdown()
361  */
362 static int elogind_schedule_shutdown(sd_bus *bus, enum elogind_action a) {
363         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
364         char date[FORMAT_TIMESTAMP_MAX];
365         const char *action;
366         int r;
367
368         if (!bus)
369                 return -EIO;
370
371         switch (a) {
372         case ACTION_HALT:
373                 action = "halt";
374                 break;
375         case ACTION_POWEROFF:
376                 action = "poweroff";
377                 break;
378         case ACTION_KEXEC:
379                 action = "kexec";
380                 break;
381         case ACTION_REBOOT:
382         default:
383                 action = "reboot";
384                 break;
385         }
386
387         if (arg_dry_run)
388                 action = strjoina("dry-", action);
389
390         (void) elogind_set_wall_message(bus, NULL);
391
392         r = sd_bus_call_method(
393                         bus,
394                         "org.freedesktop.login1",
395                         "/org/freedesktop/login1",
396                         "org.freedesktop.login1.Manager",
397                         "ScheduleShutdown",
398                         &error,
399                         NULL,
400                         "st",
401                         action,
402                         arg_when);
403
404         if (r < 0)
405                 return log_warning_errno(r,
406                                 "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s",
407                                 bus_error_message(&error, r));
408
409         if (!arg_quiet)
410                 log_info("Shutdown scheduled for %s, use 'shutdown -c' to cancel.", format_timestamp(date, sizeof(date), arg_when));
411
412         return 0;
413 }
414
415 /* Original:
416  * systemctl/systemctl.c:3204:logind_set_wall_message()
417  * (Tweaked to allow an extra message to be appended.)
418  */
419 static int elogind_set_wall_message(sd_bus* bus, const char* msg) {
420         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
421         _cleanup_free_ char *m = NULL;
422         int r;
423
424         if (strv_extend(&arg_wall, msg) < 0)
425                 return log_oom();
426
427         m = strv_join(arg_wall, " ");
428         if (!m)
429                 return log_oom();
430
431         log_debug("%s wall message \"%s\".", arg_dry_run ? "Would set" : "Setting", m);
432         if (arg_dry_run)
433                 return 0;
434
435         r = sd_bus_call_method(
436                         bus,
437                         "org.freedesktop.login1",
438                         "/org/freedesktop/login1",
439                         "org.freedesktop.login1.Manager",
440                         "SetWallMessage",
441                         &error,
442                         NULL,
443                         "sb",
444                         m,
445                         !arg_no_wall);
446
447         if (r < 0)
448                 return log_warning_errno(r, "Failed to set wall message, ignoring: %s", bus_error_message(&error, r));
449
450         return 0;
451 }
452
453 /* Original:
454  * systemctl/systemctl.c:7743:parse_shutdown_time_spec()
455  */
456 static int parse_shutdown_time_spec(const char *t, usec_t *_u) {
457         assert(t);
458         assert(_u);
459
460         if (streq(t, "now"))
461                 *_u = 0;
462         else if (!strchr(t, ':')) {
463                 uint64_t u;
464
465                 if (safe_atou64(t, &u) < 0)
466                         return -EINVAL;
467
468                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
469         } else {
470                 char *e = NULL;
471                 long hour, minute;
472                 struct tm tm = {};
473                 time_t s;
474                 usec_t n;
475
476                 errno = 0;
477                 hour = strtol(t, &e, 10);
478                 if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
479                         return -EINVAL;
480
481                 minute = strtol(e+1, &e, 10);
482                 if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
483                         return -EINVAL;
484
485                 n = now(CLOCK_REALTIME);
486                 s = (time_t) (n / USEC_PER_SEC);
487
488                 assert_se(localtime_r(&s, &tm));
489
490                 tm.tm_hour = (int) hour;
491                 tm.tm_min = (int) minute;
492                 tm.tm_sec = 0;
493
494                 assert_se(s = mktime(&tm));
495
496                 *_u = (usec_t) s * USEC_PER_SEC;
497
498                 while (*_u <= n)
499                         *_u += USEC_PER_DAY;
500         }
501
502         return 0;
503 }
504
505 /* Original:
506  * systemctl/systemctl.c:3482:start_special()
507  * However, this elogind variant is very different from the original.
508  */
509 int start_special(int argc, char *argv[], void *userdata) {
510         sd_bus *bus = userdata;
511         enum elogind_action a;
512         int r;
513         char** wall = NULL;
514
515         assert(argv);
516
517         a = verb_to_action(argv[0]);
518
519         elogind_log_special(a);
520
521         /* For poweroff and reboot, some extra checks are performed: */
522         if ( IN_SET(a, ACTION_POWEROFF, ACTION_REBOOT) ) {
523
524                 /* No power off actions in chroot environments */
525                 if ( running_in_chroot() > 0 ) {
526                         log_info("Running in chroot, ignoring request.");
527                         return 0;
528                 }
529
530                 /* Check time argument */
531                 if ( (argc > 1) && (ACTION_CANCEL_SHUTDOWN != arg_action)) {
532                         r = parse_shutdown_time_spec(argv[1], &arg_when);
533                         if (r < 0) {
534                                 log_error("Failed to parse time specification: %s", argv[optind]);
535                                 return r;
536                         }
537                 }
538
539                 /* The optional user wall message must be set */
540                 if ( (argc > 1)
541                   && ( (arg_action == ACTION_CANCEL_SHUTDOWN)
542                     || (0 == arg_when) ) )
543                         /* No time argument for shutdown cancel, or no
544                          * time argument given. */
545                         wall = argv + 1;
546                 else if (argc > 2)
547                         /* We skip the time argument */
548                         wall = argv + 2;
549
550                 if (wall) {
551                         arg_wall = strv_copy(wall);
552                         if (!arg_wall)
553                                 return log_oom();
554                 }
555         }
556
557         /* Switch to cancel shutdown, if a shutdown action was requested,
558            and the option to cancel it was set: */
559         if ( IN_SET(a, ACTION_POWEROFF, ACTION_REBOOT)
560           && (arg_action == ACTION_CANCEL_SHUTDOWN) )
561                 return elogind_cancel_shutdown(bus);
562
563         r = check_inhibitors(bus, a);
564         if (r < 0)
565                 return r;
566
567         /* Perform requested action */
568         if (IN_SET(a,
569                    ACTION_POWEROFF,
570                    ACTION_REBOOT,
571                    ACTION_SUSPEND,
572                    ACTION_HIBERNATE,
573                    ACTION_HYBRID_SLEEP)) {
574                 if (arg_when > 0)
575                         return elogind_schedule_shutdown(bus, a);
576                 else
577                         return elogind_reboot(bus, a);
578         }
579
580         return -EOPNOTSUPP;
581 }
582