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