chiark / gitweb /
46856b01ad616b8230f96193ce48ea26fc89bfd7
[elogind.git] / src / shutdownd.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/socket.h>
23 #include <sys/poll.h>
24 #include <sys/types.h>
25 #include <sys/timerfd.h>
26 #include <assert.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31
32 #include "shutdownd.h"
33 #include "log.h"
34 #include "macro.h"
35 #include "util.h"
36 #include "sd-daemon.h"
37 #include "utmp-wtmp.h"
38
39 static int read_packet(int fd, struct shutdownd_command *_c) {
40         struct msghdr msghdr;
41         struct iovec iovec;
42         struct ucred *ucred;
43         union {
44                 struct cmsghdr cmsghdr;
45                 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
46         } control;
47         struct shutdownd_command c;
48         ssize_t n;
49
50         assert(fd >= 0);
51         assert(_c);
52
53         zero(iovec);
54         iovec.iov_base = &c;
55         iovec.iov_len = sizeof(c);
56
57         zero(control);
58         zero(msghdr);
59         msghdr.msg_iov = &iovec;
60         msghdr.msg_iovlen = 1;
61         msghdr.msg_control = &control;
62         msghdr.msg_controllen = sizeof(control);
63
64         if ((n = recvmsg(fd, &msghdr, MSG_DONTWAIT)) <= 0) {
65                 if (n >= 0) {
66                         log_error("Short read");
67                         return -EIO;
68                 }
69
70                 if (errno == EAGAIN || errno == EINTR)
71                         return 0;
72
73                 log_error("recvmsg(): %m");
74                 return -errno;
75         }
76
77         if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
78             control.cmsghdr.cmsg_level != SOL_SOCKET ||
79             control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
80             control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
81                 log_warning("Received message without credentials. Ignoring.");
82                 return 0;
83         }
84
85         ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
86         if (ucred->uid != 0) {
87                 log_warning("Got request from unprivileged user. Ignoring.");
88                 return 0;
89         }
90
91         if (n != sizeof(c)) {
92                 log_warning("Message has invalid size. Ignoring");
93                 return 0;
94         }
95
96         char_array_0(c.wall_message);
97
98         *_c = c;
99         return 1;
100 }
101
102 static void warn_wall(usec_t n, struct shutdownd_command *c) {
103         char date[FORMAT_TIMESTAMP_MAX];
104         const char *prefix;
105         char *l = NULL;
106
107         assert(c);
108         assert(c->warn_wall);
109
110         if (n >= c->elapse)
111                 return;
112
113         if (c->mode == 'H')
114                 prefix = "The system is going down for system halt at ";
115         else if (c->mode == 'P')
116                 prefix = "The system is going down for power-off at ";
117         else if (c->mode == 'r')
118                 prefix = "The system is going down for reboot at ";
119         else
120                 assert_not_reached("Unknown mode!");
121
122         if (asprintf(&l, "%s%s%s%s!", c->wall_message, c->wall_message[0] ? "\n" : "",
123                      prefix, format_timestamp(date, sizeof(date), c->elapse)) < 0)
124                 log_error("Failed to allocate wall message");
125         else {
126                 utmp_wall(l, NULL);
127                 free(l);
128         }
129 }
130
131 static usec_t when_wall(usec_t n, usec_t elapse) {
132
133         static const struct {
134                 usec_t delay;
135                 usec_t interval;
136         } table[] = {
137                 { 10 * USEC_PER_MINUTE, USEC_PER_MINUTE      },
138                 { USEC_PER_HOUR,        15 * USEC_PER_MINUTE },
139                 { 3 * USEC_PER_HOUR,    30 * USEC_PER_MINUTE }
140         };
141
142         usec_t left, sub;
143         unsigned i;
144
145         /* If the time is already passed, then don't announce */
146         if (n >= elapse)
147                 return 0;
148
149         left = elapse - n;
150         for (i = 0; i < ELEMENTSOF(table); i++)
151                 if (n + table[i].delay >= elapse) {
152                         sub = ((left / table[i].interval) * table[i].interval);
153                         break;
154                 }
155
156         if (i >= ELEMENTSOF(table))
157                 sub = ((left / USEC_PER_HOUR) * USEC_PER_HOUR);
158
159         return elapse > sub ? elapse - sub : 1;
160 }
161
162 static usec_t when_nologin(usec_t elapse) {
163         return elapse > 5*USEC_PER_MINUTE ? elapse - 5*USEC_PER_MINUTE : 1;
164 }
165
166 int main(int argc, char *argv[]) {
167         enum {
168                 FD_SOCKET,
169                 FD_WALL_TIMER,
170                 FD_NOLOGIN_TIMER,
171                 FD_SHUTDOWN_TIMER,
172                 _FD_MAX
173         };
174
175         int r = EXIT_FAILURE, n_fds;
176         struct shutdownd_command c;
177         struct pollfd pollfd[_FD_MAX];
178         bool exec_shutdown = false, unlink_nologin = false, failed = false;
179         unsigned i;
180
181         if (getppid() != 1) {
182                 log_error("This program should be invoked by init only.");
183                 return EXIT_FAILURE;
184         }
185
186         if (argc > 1) {
187                 log_error("This program does not take arguments.");
188                 return EXIT_FAILURE;
189         }
190
191         log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
192         log_parse_environment();
193         log_open();
194
195         umask(0022);
196
197         if ((n_fds = sd_listen_fds(true)) < 0) {
198                 log_error("Failed to read listening file descriptors from environment: %s", strerror(-r));
199                 return EXIT_FAILURE;
200         }
201
202         if (n_fds != 1) {
203                 log_error("Need exactly one file descriptor.");
204                 return EXIT_FAILURE;
205         }
206
207         zero(c);
208         zero(pollfd);
209
210         pollfd[FD_SOCKET].fd = SD_LISTEN_FDS_START;
211         pollfd[FD_SOCKET].events = POLLIN;
212
213         for (i = 0; i < _FD_MAX; i++) {
214
215                 if (i == FD_SOCKET)
216                         continue;
217
218                 pollfd[i].events = POLLIN;
219
220                 if ((pollfd[i].fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC)) < 0) {
221                         log_error("timerfd_create(): %m");
222                         failed = true;
223                 }
224         }
225
226         if (failed)
227                 goto finish;
228
229         log_debug("systemd-shutdownd running as pid %lu", (unsigned long) getpid());
230
231         sd_notify(false,
232                   "READY=1\n"
233                   "STATUS=Processing requests...");
234
235         do {
236                 int k;
237                 usec_t n;
238
239                 if (poll(pollfd, _FD_MAX, -1) < 0) {
240
241                         if (errno == EAGAIN || errno == EINTR)
242                                 continue;
243
244                         log_error("poll(): %m");
245                         goto finish;
246                 }
247
248                 n = now(CLOCK_REALTIME);
249
250                 if (pollfd[FD_SOCKET].revents) {
251
252                         if ((k = read_packet(pollfd[FD_SOCKET].fd, &c)) < 0)
253                                 goto finish;
254                         else if (k > 0 && c.elapse > 0) {
255                                 struct itimerspec its;
256                                 char date[FORMAT_TIMESTAMP_MAX];
257
258                                 if (c.warn_wall) {
259                                         /* Send wall messages every so often */
260                                         zero(its);
261                                         timespec_store(&its.it_value, when_wall(n, c.elapse));
262                                         if (timerfd_settime(pollfd[FD_WALL_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
263                                                 log_error("timerfd_settime(): %m");
264                                                 goto finish;
265                                         }
266
267                                         /* Warn immediately if less than 15 minutes are left */
268                                         if (n < c.elapse &&
269                                             n + 15*USEC_PER_MINUTE >= c.elapse)
270                                                 warn_wall(n, &c);
271                                 }
272
273                                 /* Disallow logins 5 minutes prior to shutdown */
274                                 zero(its);
275                                 timespec_store(&its.it_value, when_nologin(c.elapse));
276                                 if (timerfd_settime(pollfd[FD_NOLOGIN_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
277                                         log_error("timerfd_settime(): %m");
278                                         goto finish;
279                                 }
280
281                                 /* Shutdown after the specified time is reached */
282                                 zero(its);
283                                 timespec_store(&its.it_value, c.elapse);
284                                 if (timerfd_settime(pollfd[FD_SHUTDOWN_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
285                                         log_error("timerfd_settime(): %m");
286                                         goto finish;
287                                 }
288
289                                 sd_notifyf(false,
290                                            "STATUS=Shutting down at %s...",
291                                            format_timestamp(date, sizeof(date), c.elapse));
292                         }
293                 }
294
295                 if (pollfd[FD_WALL_TIMER].revents) {
296                         struct itimerspec its;
297
298                         warn_wall(n, &c);
299                         flush_fd(pollfd[FD_WALL_TIMER].fd);
300
301                         /* Restart timer */
302                         zero(its);
303                         timespec_store(&its.it_value, when_wall(n, c.elapse));
304                         if (timerfd_settime(pollfd[FD_WALL_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
305                                 log_error("timerfd_settime(): %m");
306                                 goto finish;
307                         }
308                 }
309
310                 if (pollfd[FD_NOLOGIN_TIMER].revents) {
311                         int e;
312
313                         log_info("Creating /run/nologin, blocking further logins...");
314
315                         if ((e = write_one_line_file_atomic("/run/nologin", "System is going down.")) < 0)
316                                 log_error("Failed to create /run/nologin: %s", strerror(-e));
317                         else
318                                 unlink_nologin = true;
319
320                         flush_fd(pollfd[FD_NOLOGIN_TIMER].fd);
321                 }
322
323                 if (pollfd[FD_SHUTDOWN_TIMER].revents) {
324                         exec_shutdown = true;
325                         goto finish;
326                 }
327
328         } while (c.elapse > 0);
329
330         r = EXIT_SUCCESS;
331
332         log_debug("systemd-shutdownd stopped as pid %lu", (unsigned long) getpid());
333
334 finish:
335
336         for (i = 0; i < _FD_MAX; i++)
337                 if (pollfd[i].fd >= 0)
338                         close_nointr_nofail(pollfd[i].fd);
339
340         if (unlink_nologin)
341                 unlink("/run/nologin");
342
343         if (exec_shutdown && !c.dry_run) {
344                 char sw[3];
345
346                 sw[0] = '-';
347                 sw[1] = c.mode;
348                 sw[2] = 0;
349
350                 execl(SYSTEMCTL_BINARY_PATH,
351                       "shutdown",
352                       sw,
353                       "now",
354                       (c.warn_wall && c.wall_message[0]) ? c.wall_message :
355                       (c.warn_wall ? NULL : "--no-wall"),
356                       NULL);
357
358                 log_error("Failed to execute /sbin/shutdown: %m");
359         }
360
361         sd_notify(false,
362                   "STATUS=Exiting...");
363
364         return r;
365 }