chiark / gitweb /
Prep v239: Add support for the new 'suspend-then-hibernate' method.
[elogind.git] / src / login / elogind.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-util.h"
22 #include "cgroup.h"
23 #include "elogind.h"
24 #include "fd-util.h"
25 #include "fileio.h"
26 #include "fs-util.h"
27 #include "mount-setup.h"
28 #include "parse-util.h"
29 #include "process-util.h"
30 #include "signal-util.h"
31 #include "socket-util.h"
32 #include "stdio-util.h"
33 #include "string-util.h"
34 #include "strv.h"
35 #include "umask-util.h"
36
37
38 #define CGROUPS_AGENT_RCVBUF_SIZE (8*1024*1024)
39 #ifndef ELOGIND_PID_FILE
40 #  define ELOGIND_PID_FILE "/run/elogind.pid"
41 #endif // ELOGIND_PID_FILE
42
43
44 static int elogind_signal_handler(sd_event_source *s,
45                                    const struct signalfd_siginfo *si,
46                                    void *userdata) {
47         Manager *m = userdata;
48         int r;
49
50         log_warning("Received signal %u [%s]", si->ssi_signo,
51                     signal_to_string(si->ssi_signo));
52
53         r = sd_event_get_state(m->event);
54
55         if (r != SD_EVENT_FINISHED)
56                 sd_event_exit(m->event, si->ssi_signo);
57
58         return 0;
59 }
60
61
62 static void remove_pid_file(void) {
63         if (access(ELOGIND_PID_FILE, F_OK) == 0)
64                 unlink_noerrno(ELOGIND_PID_FILE);
65 }
66
67
68 static void write_pid_file(void) {
69         char c[DECIMAL_STR_MAX(pid_t) + 2];
70         pid_t pid;
71         int   r;
72
73         pid = getpid_cached();
74
75         xsprintf(c, PID_FMT "\n", pid);
76
77         r = write_string_file(ELOGIND_PID_FILE, c,
78                               WRITE_STRING_FILE_CREATE |
79                               WRITE_STRING_FILE_VERIFY_ON_FAILURE);
80         if (r < 0)
81                 log_error_errno(-r, "Failed to write PID file %s: %m",
82                                 ELOGIND_PID_FILE);
83
84         /* Make sure the PID file gets cleaned up on exit! */
85         atexit(remove_pid_file);
86 }
87
88
89 /** daemonize elogind by double forking.
90   * The grand child returns 0.
91   * The parent and child return their forks PID.
92   * On error, a value < 0 is returned.
93 **/
94 static int elogind_daemonize(void) {
95         pid_t child;
96         pid_t grandchild;
97         pid_t SID;
98         int r;
99
100 #if ENABLE_DEBUG_ELOGIND
101         log_notice("Double forking elogind");
102         log_notice("Parent PID     : %5d", getpid_cached());
103         log_notice("Parent SID     : %5d", getsid(getpid_cached()));
104 #endif // ENABLE_DEBUG_ELOGIND
105
106         r = safe_fork_full("elogind-forker", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS|FORK_NULL_STDIO|FORK_WAIT, &child);
107
108         if (r < 0)
109                 return log_error_errno(errno, "Failed to fork daemon leader: %m");
110
111         /* safe_fork_full() Has waited for the child to terminate, so we
112          * are safe to return here. The child already has forked off the
113          * daemon itself.
114          */
115         if (r)
116                 return child;
117
118 #if ENABLE_DEBUG_ELOGIND
119         log_notice("Child PID      : %5d", getpid_cached());
120         log_notice("Child SID      : %5d", getsid(getpid_cached()));
121 #endif // ENABLE_DEBUG_ELOGIND
122
123         SID = setsid();
124         if ((pid_t)-1 == SID)
125                 return log_error_errno(errno, "Failed to create new SID: %m");
126
127 #if ENABLE_DEBUG_ELOGIND
128         log_notice("Child new SID  : %5d", getsid(getpid_cached()));
129 #endif // ENABLE_DEBUG_ELOGIND
130
131         umask(0022);
132
133         /* Now the grandchild, the true daemon, can be created. */
134         r = safe_fork_full("elogind-daemon", NULL, 0, FORK_REOPEN_LOG, &grandchild);
135
136         if (r < 0)
137                 return log_error_errno(errno, "Failed to fork daemon: %m");
138
139         if (r)
140                 /* Exit immediately! */
141                 return grandchild;
142
143         umask(0022);
144
145 #if ENABLE_DEBUG_ELOGIND
146         log_notice("Grand child PID: %5d", getpid_cached());
147         log_notice("Grand child SID: %5d", getsid(getpid_cached()));
148 #endif // ENABLE_DEBUG_ELOGIND
149
150         /* Take care of our PID-file now */
151         write_pid_file();
152
153         return 0;
154 }
155
156
157 /// Simple tool to see, if elogind is already running
158 static pid_t elogind_is_already_running(bool need_pid_file) {
159         _cleanup_free_ char *s = NULL;
160         pid_t pid;
161         int r;
162
163         r = read_one_line_file(ELOGIND_PID_FILE, &s);
164
165         if (r < 0)
166                 goto we_are_alone;
167
168         r = safe_atoi32(s, &pid);
169
170         if (r < 0)
171                 goto we_are_alone;
172
173         if ( (pid != getpid_cached()) && pid_is_alive(pid))
174                 return pid;
175
176 we_are_alone:
177
178         /* Take care of our PID-file now.
179            If the user is going to fork elogind, the PID file
180            will be overwritten. */
181         if (need_pid_file)
182                 write_pid_file();
183
184         return 0;
185 }
186
187
188 static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
189         Manager *m = userdata;
190         char buf[PATH_MAX+1];
191         ssize_t n;
192
193         n = recv(fd, buf, sizeof(buf), 0);
194         if (n < 0)
195                 return log_error_errno(errno, "Failed to read cgroups agent message: %m");
196         if (n == 0) {
197                 log_error("Got zero-length cgroups agent message, ignoring.");
198                 return 0;
199         }
200         if ((size_t) n >= sizeof(buf)) {
201                 log_error("Got overly long cgroups agent message, ignoring.");
202                 return 0;
203         }
204
205         if (memchr(buf, 0, n)) {
206                 log_error("Got cgroups agent message with embedded NUL byte, ignoring.");
207                 return 0;
208         }
209         buf[n] = 0;
210
211         manager_notify_cgroup_empty(m, buf);
212
213         return 0;
214 }
215
216
217 /// Add-On for manager_connect_bus()
218 /// Original: src/core/manager.c:manager_setup_cgroups_agent()
219 int elogind_setup_cgroups_agent(Manager *m) {
220
221         static const union sockaddr_union sa = {
222                 .un.sun_family = AF_UNIX,
223                 .un.sun_path = "/run/systemd/cgroups-agent",
224         };
225         int r = 0;
226
227         /* This creates a listening socket we receive cgroups agent messages on. We do not use D-Bus for delivering
228          * these messages from the cgroups agent binary to PID 1, as the cgroups agent binary is very short-living, and
229          * each instance of it needs a new D-Bus connection. Since D-Bus connections are SOCK_STREAM/AF_UNIX, on
230          * overloaded systems the backlog of the D-Bus socket becomes relevant, as not more than the configured number
231          * of D-Bus connections may be queued until the kernel will start dropping further incoming connections,
232          * possibly resulting in lost cgroups agent messages. To avoid this, we'll use a private SOCK_DGRAM/AF_UNIX
233          * socket, where no backlog is relevant as communication may take place without an actual connect() cycle, and
234          * we thus won't lose messages.
235          *
236          * Note that PID 1 will forward the agent message to system bus, so that the user systemd instance may listen
237          * to it. The system instance hence listens on this special socket, but the user instances listen on the system
238          * bus for these messages. */
239
240         if (m->test_run_flags)
241                 return 0;
242
243         if (!MANAGER_IS_SYSTEM(m))
244                 return 0;
245
246         r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
247         if (r < 0)
248                 return log_error_errno(r, "Failed to determine whether unified cgroups hierarchy is used: %m");
249         if (r > 0) /* We don't need this anymore on the unified hierarchy */
250                 return 0;
251
252         if (m->cgroups_agent_fd < 0) {
253                 _cleanup_close_ int fd = -1;
254
255                 /* First free all secondary fields */
256                 m->cgroups_agent_event_source = sd_event_source_unref(m->cgroups_agent_event_source);
257
258                 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
259                 if (fd < 0)
260                         return log_error_errno(errno, "Failed to allocate cgroups agent socket: %m");
261
262                 fd_inc_rcvbuf(fd, CGROUPS_AGENT_RCVBUF_SIZE);
263
264                 (void) unlink(sa.un.sun_path);
265
266                 /* Only allow root to connect to this socket */
267                 RUN_WITH_UMASK(0077)
268                         r = bind(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
269                 if (r < 0)
270                         return log_error_errno(errno, "bind(%s) failed: %m", sa.un.sun_path);
271
272                 m->cgroups_agent_fd = fd;
273                 fd = -1;
274         }
275
276         if (!m->cgroups_agent_event_source) {
277                 r = sd_event_add_io(m->event, &m->cgroups_agent_event_source, m->cgroups_agent_fd, EPOLLIN, manager_dispatch_cgroups_agent_fd, m);
278                 if (r < 0)
279                         return log_error_errno(r, "Failed to allocate cgroups agent event source: %m");
280
281                 /* Process cgroups notifications early, but after having processed service notification messages or
282                  * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of notification,
283                  * and we collected the metadata the notification and SIGCHLD stuff offers first. Also see handling of
284                  * cgroup inotify for the unified cgroup stuff. */
285                 r = sd_event_source_set_priority(m->cgroups_agent_event_source, SD_EVENT_PRIORITY_NORMAL-5);
286                 if (r < 0)
287                         return log_error_errno(r, "Failed to set priority of cgroups agent event source: %m");
288
289                 (void) sd_event_source_set_description(m->cgroups_agent_event_source, "manager-cgroups-agent");
290         }
291
292         return 0;
293 }
294
295
296 /** Extra functionality at startup, exclusive to elogind
297   * return < 0 on error, exit with failure.
298   * return = 0 on success, continue normal operation.
299   * return > 0 if elogind is already running or forked, exit with success.
300 **/
301 int elogind_startup(int argc, char *argv[]) {
302         bool  daemonize = false;
303         pid_t pid;
304         int   r         = 0;
305         bool  show_help = false;
306         bool  wrong_arg = false;
307
308         /* add a -h/--help and a -d/--daemon argument. */
309         if ( (argc == 2) && argv[1] && strlen(argv[1]) ) {
310                 if ( streq(argv[1], "-D") || streq(argv[1], "--daemon") )
311                         daemonize = true;
312                 else if ( streq(argv[1], "-h") || streq(argv[1], "--help") ) {
313                         show_help = true;
314                         r = 1;
315                 } else
316                         wrong_arg = true;
317         } else if (argc > 2)
318                 wrong_arg = true;
319
320         /* Note: At this point, the logging is not initialized, so we can not
321                  use log_debug_elogind(). */
322 #if ENABLE_DEBUG_ELOGIND
323         log_notice("elogind startup: Daemonize: %s, Show Help: %s, Wrong arg: %s",
324                 daemonize ? "True" : "False",
325                 show_help ? "True" : "False",
326                 wrong_arg ? "True" : "False");
327 #endif // ENABLE_DEBUG_ELOGIND
328
329         /* try to get some meaningful output in case of an error */
330         if (wrong_arg) {
331                 log_error("Unknown arguments");
332                 show_help = true;
333                 r = -EINVAL;
334         }
335         if (show_help) {
336                 log_info("%s [<-D|--daemon>|<-h|--help>]", basename(argv[0]));
337                 return r;
338         }
339
340         /* Do not continue if elogind is already running */
341         pid = elogind_is_already_running(!daemonize);
342         if (pid) {
343                 log_error("elogind is already running as PID " PID_FMT, pid);
344                 return pid;
345         }
346
347         /* elogind allows to be daemonized using one argument "-D" / "--daemon" */
348         if (daemonize)
349                 r = elogind_daemonize();
350
351         return r;
352 }
353
354
355 /// Add-On for manager_free()
356 void elogind_manager_free(Manager* m) {
357
358         manager_shutdown_cgroup(m, true);
359
360         sd_event_source_unref(m->cgroups_agent_event_source);
361
362         safe_close(m->cgroups_agent_fd);
363
364         strv_free(m->suspend_mode);
365         strv_free(m->suspend_state);
366         strv_free(m->hibernate_mode);
367         strv_free(m->hibernate_state);
368         strv_free(m->hybrid_sleep_mode);
369         strv_free(m->hybrid_sleep_state);
370 }
371
372
373 /// Add-On for manager_new()
374 int elogind_manager_new(Manager* m) {
375         int r = 0;
376
377         m->cgroups_agent_fd = -1;
378         m->pin_cgroupfs_fd  = -1;
379         m->test_run_flags   = 0;
380
381         /* Init sleep modes and states */
382         m->suspend_mode        = NULL;
383         m->suspend_state       = NULL;
384         m->hibernate_mode      = NULL;
385         m->hibernate_state     = NULL;
386         m->hybrid_sleep_mode   = NULL;
387         m->hybrid_sleep_state  = NULL;
388         m->hibernate_delay_sec = 0;
389
390         /* If elogind should be its own controller, mount its cgroup */
391         if (streq(SYSTEMD_CGROUP_CONTROLLER, "_elogind")) {
392                 m->is_system = true;
393                 r = mount_setup(true);
394         } else
395                 m->is_system = false;
396
397         /* Make cgroups */
398         if (r > -1)
399                 r = manager_setup_cgroup(m);
400
401         return r;
402 }
403
404
405 /// Add-On for manager_reset_config()
406 void elogind_manager_reset_config(Manager* m) {
407
408 #if ENABLE_DEBUG_ELOGIND
409         int dbg_cnt;
410 #endif // ENABLE_DEBUG_ELOGIND
411
412         /* Set default Sleep config if not already set by logind.conf */
413         if (!m->suspend_state)
414                 m->suspend_state = strv_new("mem", "standby", "freeze", NULL);
415         if (!m->hibernate_mode)
416                 m->hibernate_mode = strv_new("platform", "shutdown", NULL);
417         if (!m->hibernate_state)
418                 m->hibernate_state = strv_new("disk", NULL);
419         if (!m->hybrid_sleep_mode)
420                 m->hybrid_sleep_mode = strv_new("suspend", "platform", "shutdown", NULL);
421         if (!m->hybrid_sleep_state)
422                 m->hybrid_sleep_state = strv_new("disk", NULL);
423         if (!m->hibernate_delay_sec)
424                 m->hibernate_delay_sec = 180 * USEC_PER_MINUTE;
425
426 #if ENABLE_DEBUG_ELOGIND
427         dbg_cnt = -1;
428         while (m->suspend_mode && m->suspend_mode[++dbg_cnt])
429                 log_debug_elogind("suspend_mode[%d] = %s",
430                                   dbg_cnt, m->suspend_mode[dbg_cnt]);
431         dbg_cnt = -1;
432         while (m->suspend_state[++dbg_cnt])
433                 log_debug_elogind("suspend_state[%d] = %s",
434                                   dbg_cnt, m->suspend_state[dbg_cnt]);
435         dbg_cnt = -1;
436         while (m->hibernate_mode[++dbg_cnt])
437                 log_debug_elogind("hibernate_mode[%d] = %s",
438                                   dbg_cnt, m->hibernate_mode[dbg_cnt]);
439         dbg_cnt = -1;
440         while (m->hibernate_state[++dbg_cnt])
441                 log_debug_elogind("hibernate_state[%d] = %s",
442                                   dbg_cnt, m->hibernate_state[dbg_cnt]);
443         dbg_cnt = -1;
444         while (m->hybrid_sleep_mode[++dbg_cnt])
445                 log_debug_elogind("hybrid_sleep_mode[%d] = %s",
446                                   dbg_cnt, m->hybrid_sleep_mode[dbg_cnt]);
447         dbg_cnt = -1;
448         while (m->hybrid_sleep_state[++dbg_cnt])
449                 log_debug_elogind("hybrid_sleep_state[%d] = %s",
450                                   dbg_cnt, m->hybrid_sleep_state[dbg_cnt]);
451         log_debug_elogind("hibernate_delay_sec: %ul seconds (%ul minutes)",
452                           m->hibernate_delay_sec / USEC_PER_SEC,
453                           m->hibernate_delay_sec / USEC_PER_MINUTE);
454 #endif // ENABLE_DEBUG_ELOGIND
455 }
456
457
458 /// Add-On for manager_startup()
459 int elogind_manager_startup(Manager *m) {
460         int r;
461
462         assert(m);
463
464         assert_se(sigprocmask_many(SIG_SETMASK, NULL, SIGINT, -1) >= 0);
465         r = sd_event_add_signal(m->event, NULL, SIGINT, elogind_signal_handler, m);
466         if (r < 0)
467                 return log_error_errno(r, "Failed to register SIGINT handler: %m");
468
469         assert_se(sigprocmask_many(SIG_SETMASK, NULL, SIGQUIT, -1) >= 0);
470         r = sd_event_add_signal(m->event, NULL, SIGQUIT, elogind_signal_handler, m);
471         if (r < 0)
472                 return log_error_errno(r, "Failed to register SIGQUIT handler: %m");
473
474         assert_se(sigprocmask_many(SIG_SETMASK, NULL, SIGTERM, -1) >= 0);
475         r = sd_event_add_signal(m->event, NULL, SIGTERM, elogind_signal_handler, m);
476         if (r < 0)
477                 return log_error_errno(r, "Failed to register SIGTERM handler: %m");
478
479         return 0;
480 }