2 This file is part of elogind.
4 Copyright 2017 Sven Eden
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.
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.
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/>.
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"
35 #include "umask-util.h"
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
44 static int elogind_signal_handler(sd_event_source *s,
45 const struct signalfd_siginfo *si,
47 Manager *m = userdata;
50 log_warning("Received signal %u [%s]", si->ssi_signo,
51 signal_to_string(si->ssi_signo));
53 r = sd_event_get_state(m->event);
55 if (r != SD_EVENT_FINISHED)
56 sd_event_exit(m->event, si->ssi_signo);
62 static void remove_pid_file(void) {
63 if (access(ELOGIND_PID_FILE, F_OK) == 0)
64 unlink_noerrno(ELOGIND_PID_FILE);
68 static void write_pid_file(void) {
69 char c[DECIMAL_STR_MAX(pid_t) + 2];
73 pid = getpid_cached();
75 xsprintf(c, PID_FMT "\n", pid);
77 r = write_string_file(ELOGIND_PID_FILE, c,
78 WRITE_STRING_FILE_CREATE |
79 WRITE_STRING_FILE_VERIFY_ON_FAILURE);
81 log_error_errno(-r, "Failed to write PID file %s: %m",
84 /* Make sure the PID file gets cleaned up on exit! */
85 atexit(remove_pid_file);
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.
94 static int elogind_daemonize(void) {
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
106 r = safe_fork_full("elogind-forker", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS|FORK_NULL_STDIO|FORK_WAIT, &child);
109 return log_error_errno(errno, "Failed to fork daemon leader: %m");
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
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
124 if ((pid_t)-1 == SID)
125 return log_error_errno(errno, "Failed to create new SID: %m");
127 #if ENABLE_DEBUG_ELOGIND
128 log_notice("Child new SID : %5d", getsid(getpid_cached()));
129 #endif // ENABLE_DEBUG_ELOGIND
133 /* Now the grandchild, the true daemon, can be created. */
134 r = safe_fork_full("elogind-daemon", NULL, 0, FORK_REOPEN_LOG, &grandchild);
137 return log_error_errno(errno, "Failed to fork daemon: %m");
140 /* Exit immediately! */
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
150 /* Take care of our PID-file now */
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;
163 r = read_one_line_file(ELOGIND_PID_FILE, &s);
168 r = safe_atoi32(s, &pid);
173 if ( (pid != getpid_cached()) && pid_is_alive(pid))
178 /* Take care of our PID-file now.
179 If the user is going to fork elogind, the PID file
180 will be overwritten. */
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];
193 n = recv(fd, buf, sizeof(buf), 0);
195 return log_error_errno(errno, "Failed to read cgroups agent message: %m");
197 log_error("Got zero-length cgroups agent message, ignoring.");
200 if ((size_t) n >= sizeof(buf)) {
201 log_error("Got overly long cgroups agent message, ignoring.");
205 if (memchr(buf, 0, n)) {
206 log_error("Got cgroups agent message with embedded NUL byte, ignoring.");
211 manager_notify_cgroup_empty(m, buf);
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) {
221 static const union sockaddr_union sa = {
222 .un.sun_family = AF_UNIX,
223 .un.sun_path = "/run/systemd/cgroups-agent",
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.
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. */
240 if (m->test_run_flags)
243 if (!MANAGER_IS_SYSTEM(m))
246 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
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 */
252 if (m->cgroups_agent_fd < 0) {
253 _cleanup_close_ int fd = -1;
255 /* First free all secondary fields */
256 m->cgroups_agent_event_source = sd_event_source_unref(m->cgroups_agent_event_source);
258 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
260 return log_error_errno(errno, "Failed to allocate cgroups agent socket: %m");
262 fd_inc_rcvbuf(fd, CGROUPS_AGENT_RCVBUF_SIZE);
264 (void) unlink(sa.un.sun_path);
266 /* Only allow root to connect to this socket */
268 r = bind(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
270 return log_error_errno(errno, "bind(%s) failed: %m", sa.un.sun_path);
272 m->cgroups_agent_fd = fd;
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);
279 return log_error_errno(r, "Failed to allocate cgroups agent event source: %m");
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);
287 return log_error_errno(r, "Failed to set priority of cgroups agent event source: %m");
289 (void) sd_event_source_set_description(m->cgroups_agent_event_source, "manager-cgroups-agent");
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.
301 int elogind_startup(int argc, char *argv[]) {
302 bool daemonize = false;
305 bool show_help = false;
306 bool wrong_arg = false;
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") )
312 else if ( streq(argv[1], "-h") || streq(argv[1], "--help") ) {
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
329 /* try to get some meaningful output in case of an error */
331 log_error("Unknown arguments");
336 log_info("%s [<-D|--daemon>|<-h|--help>]", basename(argv[0]));
340 /* Do not continue if elogind is already running */
341 pid = elogind_is_already_running(!daemonize);
343 log_error("elogind is already running as PID " PID_FMT, pid);
347 /* elogind allows to be daemonized using one argument "-D" / "--daemon" */
349 r = elogind_daemonize();
355 /// Add-On for manager_free()
356 void elogind_manager_free(Manager* m) {
358 manager_shutdown_cgroup(m, true);
360 sd_event_source_unref(m->cgroups_agent_event_source);
362 safe_close(m->cgroups_agent_fd);
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);
373 /// Add-On for manager_new()
374 int elogind_manager_new(Manager* m) {
377 m->cgroups_agent_fd = -1;
378 m->pin_cgroupfs_fd = -1;
379 m->test_run_flags = 0;
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;
390 /* If elogind should be its own controller, mount its cgroup */
391 if (streq(SYSTEMD_CGROUP_CONTROLLER, "_elogind")) {
393 r = mount_setup(true);
395 m->is_system = false;
399 r = manager_setup_cgroup(m);
405 /// Add-On for manager_reset_config()
406 void elogind_manager_reset_config(Manager* m) {
408 #if ENABLE_DEBUG_ELOGIND
410 #endif // ENABLE_DEBUG_ELOGIND
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;
426 #if ENABLE_DEBUG_ELOGIND
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]);
432 while (m->suspend_state[++dbg_cnt])
433 log_debug_elogind("suspend_state[%d] = %s",
434 dbg_cnt, m->suspend_state[dbg_cnt]);
436 while (m->hibernate_mode[++dbg_cnt])
437 log_debug_elogind("hibernate_mode[%d] = %s",
438 dbg_cnt, m->hibernate_mode[dbg_cnt]);
440 while (m->hibernate_state[++dbg_cnt])
441 log_debug_elogind("hibernate_state[%d] = %s",
442 dbg_cnt, m->hibernate_state[dbg_cnt]);
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]);
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: %lu seconds (%lu minutes)",
452 m->hibernate_delay_sec / USEC_PER_SEC,
453 m->hibernate_delay_sec / USEC_PER_MINUTE);
454 #endif // ENABLE_DEBUG_ELOGIND
458 /// Add-On for manager_startup()
459 int elogind_manager_startup(Manager *m) {
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);
467 return log_error_errno(r, "Failed to register SIGINT handler: %m");
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);
472 return log_error_errno(r, "Failed to register SIGQUIT handler: %m");
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);
477 return log_error_errno(r, "Failed to register SIGTERM handler: %m");