chiark / gitweb /
logind: trivial simplification
[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_ignore_inhibitors = false;
40 bool           arg_no_wall           = false;
41 BusTransport   arg_transport         = BUS_TRANSPORT_LOCAL;
42 char**         arg_wall              = NULL;
43 usec_t         arg_when              = 0;
44
45 static const struct {
46         HandleAction action;
47         const char*  verb;
48 } action_table[_ACTION_MAX] = {
49         [ACTION_POWEROFF]     = { HANDLE_POWEROFF,     "poweroff",    },
50         [ACTION_REBOOT]       = { HANDLE_REBOOT,       "reboot",      },
51         [ACTION_SUSPEND]      = { HANDLE_SUSPEND,      "suspend",     },
52         [ACTION_HIBERNATE]    = { HANDLE_HIBERNATE,    "hibernate",   },
53         [ACTION_HYBRID_SLEEP] = { HANDLE_HYBRID_SLEEP, "hybrid-sleep" },
54 };
55
56 static int elogind_set_wall_message(sd_bus* bus, const char* msg);
57
58 static enum elogind_action verb_to_action(const char *verb) {
59         enum elogind_action i;
60
61         for (i = _ACTION_INVALID; i < _ACTION_MAX; i++)
62                 if (streq_ptr(action_table[i].verb, verb))
63                         return i;
64
65         return _ACTION_INVALID;
66 }
67
68 static int check_inhibitors(sd_bus* bus, enum elogind_action a) {
69         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
70         _cleanup_strv_free_ char **sessions = NULL;
71         const char *what, *who, *why, *mode;
72         uint32_t uid, pid;
73         unsigned c = 0;
74         char **s;
75         int r;
76
77         if (arg_ignore_inhibitors)
78                 return 0;
79
80         if (arg_when > 0)
81                 return 0;
82
83         if (geteuid() == 0)
84                 return 0;
85
86         if (!on_tty())
87                 return 0;
88
89         r = sd_bus_call_method(
90                         bus,
91                         "org.freedesktop.login1",
92                         "/org/freedesktop/login1",
93                         "org.freedesktop.login1.Manager",
94                         "ListInhibitors",
95                         NULL,
96                         &reply,
97                         NULL);
98         if (r < 0)
99                 /* If logind is not around, then there are no inhibitors... */
100                 return 0;
101
102         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssuu)");
103         if (r < 0)
104                 return bus_log_parse_error(r);
105
106         while ((r = sd_bus_message_read(reply, "(ssssuu)", &what, &who, &why, &mode, &uid, &pid)) > 0) {
107                 _cleanup_free_ char *comm = NULL, *user = NULL;
108                 _cleanup_strv_free_ char **sv = NULL;
109
110                 if (!streq(mode, "block"))
111                         continue;
112
113                 sv = strv_split(what, ":");
114                 if (!sv)
115                         return log_oom();
116
117                 if ((pid_t) pid < 0)
118                         return log_error_errno(ERANGE, "Bad PID %"PRIu32": %m", pid);
119
120                 if (!strv_contains(sv,
121                                    IN_SET(a,
122                                           ACTION_HALT,
123                                           ACTION_POWEROFF,
124                                           ACTION_REBOOT,
125                                           ACTION_KEXEC) ? "shutdown" : "sleep"))
126                         continue;
127
128                 get_process_comm(pid, &comm);
129                 user = uid_to_name(uid);
130
131                 log_warning("Operation inhibited by \"%s\" (PID "PID_FMT" \"%s\", user %s), reason is \"%s\".",
132                             who, (pid_t) pid, strna(comm), strna(user), why);
133
134                 c++;
135         }
136         if (r < 0)
137                 return bus_log_parse_error(r);
138
139         r = sd_bus_message_exit_container(reply);
140         if (r < 0)
141                 return bus_log_parse_error(r);
142
143         /* Check for current sessions */
144         sd_get_sessions(&sessions);
145         STRV_FOREACH(s, sessions) {
146                 _cleanup_free_ char *type = NULL, *tty = NULL, *seat = NULL, *user = NULL, *service = NULL, *class = NULL;
147
148                 if (sd_session_get_uid(*s, &uid) < 0 || uid == getuid())
149                         continue;
150
151                 if (sd_session_get_class(*s, &class) < 0 || !streq(class, "user"))
152                         continue;
153
154                 if (sd_session_get_type(*s, &type) < 0 || (!streq(type, "x11") && !streq(type, "tty")))
155                         continue;
156
157                 sd_session_get_tty(*s, &tty);
158                 sd_session_get_seat(*s, &seat);
159                 sd_session_get_service(*s, &service);
160                 user = uid_to_name(uid);
161
162                 log_warning("User %s is logged in on %s.", strna(user), isempty(tty) ? (isempty(seat) ? strna(service) : seat) : tty);
163                 c++;
164         }
165
166         if (c <= 0)
167                 return 0;
168
169         log_error("Please retry operation after closing inhibitors and logging out other users.\nAlternatively, ignore inhibitors and users with 'loginctl -i %s'.",
170                   action_table[a].verb);
171
172         return -EPERM;
173 }
174
175 int elogind_cancel_shutdown(sd_bus *bus) {
176         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
177         int r;
178
179         r = elogind_set_wall_message(bus, NULL);
180
181         if (r < 0) {
182                 log_warning_errno(r, "Failed to set wall message, ignoring: %s",
183                                   bus_error_message(&error, r));
184                 sd_bus_error_free(&error);
185         }
186
187         r = sd_bus_call_method(
188                         bus,
189                         "org.freedesktop.login1",
190                         "/org/freedesktop/login1",
191                         "org.freedesktop.login1.Manager",
192                         "CancelScheduledShutdown",
193                         &error,
194                         NULL, NULL);
195         if (r < 0)
196                 return log_warning_errno(r, "Failed to talk to elogind, shutdown hasn't been cancelled: %s", bus_error_message(&error, r));
197
198         return 0;
199 }
200
201 void elogind_cleanup(void) {
202         polkit_agent_close();
203         strv_free(arg_wall);
204 }
205
206 static void elogind_log_special(enum elogind_action a) {
207 #ifdef ENABLE_DEBUG_ELOGIND
208         switch (a) {
209         case ACTION_HALT:
210                 log_struct(LOG_INFO,
211                            LOG_MESSAGE("Halt action called."),
212                            LOG_MESSAGE_ID(SD_MESSAGE_SHUTDOWN),
213                            NULL);
214                 break;
215         case ACTION_POWEROFF:
216                 log_struct(LOG_INFO,
217                            LOG_MESSAGE("Poweroff action called."),
218                            LOG_MESSAGE_ID(SD_MESSAGE_SHUTDOWN),
219                            NULL);
220                 break;
221         case ACTION_REBOOT:
222                 log_struct(LOG_INFO,
223                            LOG_MESSAGE("Reboot action called."),
224                            LOG_MESSAGE_ID(SD_MESSAGE_SHUTDOWN),
225                            NULL);
226                 break;
227         case ACTION_KEXEC:
228                 log_struct(LOG_INFO,
229                            LOG_MESSAGE("KExec action called."),
230                            LOG_MESSAGE_ID(SD_MESSAGE_SHUTDOWN),
231                            NULL);
232                 break;
233         case ACTION_SUSPEND:
234                 log_struct(LOG_INFO,
235                            LOG_MESSAGE("Suspend action called."),
236                            LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_START),
237                            NULL);
238                 break;
239         case ACTION_HIBERNATE:
240                 log_struct(LOG_INFO,
241                            LOG_MESSAGE("Hibernate action called."),
242                            LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_START),
243                            NULL);
244                 break;
245         case ACTION_HYBRID_SLEEP:
246                 log_struct(LOG_INFO,
247                            LOG_MESSAGE("Hybrid-Sleep action called."),
248                            LOG_MESSAGE_ID(SD_MESSAGE_SLEEP_START),
249                            NULL);
250                 break;
251         case ACTION_CANCEL_SHUTDOWN:
252                 log_struct(LOG_INFO,
253                            LOG_MESSAGE("Cancel Shutdown called."),
254                            LOG_MESSAGE_ID(SD_MESSAGE_SHUTDOWN),
255                            NULL);
256                 break;
257         default:
258                 break;
259         }
260 #endif // ENABLE_DEBUG_ELOGIND
261 }
262
263 static int elogind_reboot(sd_bus *bus, enum elogind_action a) {
264         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
265         const char *method  = NULL;
266         int r;
267         static const char *table[_ACTION_MAX] = {
268                 [ACTION_REBOOT]          = "The system is going down for reboot NOW!",
269                 [ACTION_POWEROFF]        = "The system is going down for power-off NOW!"
270         };
271
272         if (!bus)
273                 return -EIO;
274
275         switch (a) {
276
277         case ACTION_POWEROFF:
278                 method = "PowerOff";
279                 break;
280
281         case ACTION_REBOOT:
282                 method = "Reboot";
283                 break;
284
285         case ACTION_SUSPEND:
286                 method = "Suspend";
287                 break;
288
289         case ACTION_HIBERNATE:
290                 method = "Hibernate";
291                 break;
292
293         case ACTION_HYBRID_SLEEP:
294                 method = "HybridSleep";
295                 break;
296
297         default:
298                 return -EINVAL;
299         }
300
301         polkit_agent_open_if_enabled();
302
303         if ( IN_SET(a, ACTION_POWEROFF, ACTION_REBOOT) ) {
304                 r = elogind_set_wall_message(bus, table[a]);
305
306                 if (r < 0) {
307                         log_warning_errno(r, "Failed to set wall message, ignoring: %s",
308                                           bus_error_message(&error, r));
309                         sd_bus_error_free(&error);
310                 }
311         }
312
313         /* Now call elogind itself to request the operation */
314         r = sd_bus_call_method(
315                         bus,
316                         "org.freedesktop.login1",
317                         "/org/freedesktop/login1",
318                         "org.freedesktop.login1.Manager",
319                         method,
320                         &error,
321                         NULL,
322                         "b", arg_ask_password);
323
324         if (r < 0)
325                 log_error("Failed to execute operation: %s", bus_error_message(&error, r));
326
327         return r;
328 }
329
330 static int elogind_schedule_shutdown(sd_bus *bus, enum elogind_action a) {
331         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
332         const char *method  = NULL;
333         int r;
334
335         if (!bus)
336                 return -EIO;
337
338         switch (a) {
339
340         case ACTION_POWEROFF:
341                 method = "poweroff";
342                 break;
343
344         case ACTION_REBOOT:
345                 method = "reboot";
346                 break;
347
348         default:
349                 return -EINVAL;
350         }
351
352         r = elogind_set_wall_message(bus, NULL);
353
354         if (r < 0) {
355                 log_warning_errno(r, "Failed to set wall message, ignoring: %s",
356                                   bus_error_message(&error, r));
357                 sd_bus_error_free(&error);
358         }
359
360         r = sd_bus_call_method(
361                         bus,
362                         "org.freedesktop.login1",
363                         "/org/freedesktop/login1",
364                         "org.freedesktop.login1.Manager",
365                         "ScheduleShutdown",
366                         &error,
367                         NULL,
368                         "st",
369                         method,
370                         arg_when);
371
372         if (r < 0)
373                 log_error("Failed to execute operation: %s", bus_error_message(&error, r));
374
375         return r;
376 }
377
378 static int elogind_set_wall_message(sd_bus* bus, const char* msg) {
379         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
380         _cleanup_free_ char *m = NULL;
381         int r;
382
383         if (strv_extend(&arg_wall, msg) < 0)
384                 return log_oom();
385
386         m = strv_join(arg_wall, " ");
387         if (!m)
388                 return log_oom();
389
390         r = sd_bus_call_method(
391                         bus,
392                         "org.freedesktop.login1",
393                         "/org/freedesktop/login1",
394                         "org.freedesktop.login1.Manager",
395                         "SetWallMessage",
396                         &error,
397                         NULL,
398                         "sb",
399                         m,
400                         !arg_no_wall);
401
402         if (r < 0)
403                 return log_warning_errno(r, "Failed to set wall message, ignoring: %s", bus_error_message(&error, r));
404
405         return 0;
406 }
407
408 static int parse_shutdown_time_spec(const char *t, usec_t *_u) {
409         assert(t);
410         assert(_u);
411
412         if (streq(t, "now"))
413                 *_u = 0;
414         else if (!strchr(t, ':')) {
415                 uint64_t u;
416
417                 if (safe_atou64(t, &u) < 0)
418                         return -EINVAL;
419
420                 *_u = now(CLOCK_REALTIME) + USEC_PER_MINUTE * u;
421         } else {
422                 char *e = NULL;
423                 long hour, minute;
424                 struct tm tm = {};
425                 time_t s;
426                 usec_t n;
427
428                 errno = 0;
429                 hour = strtol(t, &e, 10);
430                 if (errno > 0 || *e != ':' || hour < 0 || hour > 23)
431                         return -EINVAL;
432
433                 minute = strtol(e+1, &e, 10);
434                 if (errno > 0 || *e != 0 || minute < 0 || minute > 59)
435                         return -EINVAL;
436
437                 n = now(CLOCK_REALTIME);
438                 s = (time_t) (n / USEC_PER_SEC);
439
440                 assert_se(localtime_r(&s, &tm));
441
442                 tm.tm_hour = (int) hour;
443                 tm.tm_min = (int) minute;
444                 tm.tm_sec = 0;
445
446                 assert_se(s = mktime(&tm));
447
448                 *_u = (usec_t) s * USEC_PER_SEC;
449
450                 while (*_u <= n)
451                         *_u += USEC_PER_DAY;
452         }
453
454         return 0;
455 }
456
457 void polkit_agent_open_if_enabled(void) {
458
459         /* Open the polkit agent as a child process if necessary */
460
461         if (!arg_ask_password)
462                 return;
463
464         if (arg_transport != BUS_TRANSPORT_LOCAL)
465                 return;
466
467         polkit_agent_open();
468 }
469
470 int start_special(int argc, char *argv[], void *userdata) {
471         sd_bus *bus = userdata;
472         enum elogind_action a;
473         int r;
474         char** wall = NULL;
475
476         assert(argv);
477
478         a = verb_to_action(argv[0]);
479
480         elogind_log_special(a);
481
482         /* For poweroff and reboot, some extra checks are performed: */
483         if ( IN_SET(a, ACTION_POWEROFF, ACTION_REBOOT) ) {
484
485                 /* No power off actions in chroot environments */
486                 if ( running_in_chroot() > 0 ) {
487                         log_info("Running in chroot, ignoring request.");
488                         return 0;
489                 }
490
491                 /* Check time argument */
492                 if ( (argc > 1) && (ACTION_CANCEL_SHUTDOWN != arg_action)) {
493                         r = parse_shutdown_time_spec(argv[1], &arg_when);
494                         if (r < 0) {
495                                 log_error("Failed to parse time specification: %s", argv[optind]);
496                                 return r;
497                         }
498                 }
499
500                 /* The optional user wall message must be set */
501                 if ( (argc > 1)
502                   && ( (arg_action == ACTION_CANCEL_SHUTDOWN)
503                     || (0 == arg_when) ) )
504                         /* No time argument for shutdown cancel, or no
505                          * time argument given. */
506                         wall = argv + 1;
507                 else if (argc > 2)
508                         /* We skip the time argument */
509                         wall = argv + 2;
510
511                 if (wall) {
512                         arg_wall = strv_copy(wall);
513                         if (!arg_wall)
514                                 return log_oom();
515                 }
516         }
517
518         /* Switch to cancel shutdown, if a shutdown action was requested,
519            and the option to cancel it was set: */
520         if ( IN_SET(a, ACTION_POWEROFF, ACTION_REBOOT)
521           && (arg_action == ACTION_CANCEL_SHUTDOWN) )
522                 return elogind_cancel_shutdown(bus);
523
524         r = check_inhibitors(bus, a);
525         if (r < 0)
526                 return r;
527
528         /* Perform requested action */
529         if (IN_SET(a,
530                    ACTION_POWEROFF,
531                    ACTION_REBOOT,
532                    ACTION_SUSPEND,
533                    ACTION_HIBERNATE,
534                    ACTION_HYBRID_SLEEP)) {
535                 if (arg_when > 0)
536                         return elogind_schedule_shutdown(bus, a);
537                 else
538                         return elogind_reboot(bus, a);
539         }
540
541         return -EOPNOTSUPP;
542 }
543