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