chiark / gitweb /
log: properly open log target in the various utilities
[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(struct shutdownd_command *c) {
103
104         assert(c);
105         assert(c->warn_wall);
106
107         if (c->wall_message[0])
108                 utmp_wall(c->wall_message);
109         else {
110                 char date[FORMAT_TIMESTAMP_MAX];
111                 const char* prefix;
112                 char *l;
113
114                 if (c->mode == 'H')
115                         prefix = "The system is going down for system halt at";
116                 else if (c->mode == 'P')
117                         prefix = "The system is going down for power-off at";
118                 else if (c->mode == 'r')
119                         prefix = "The system is going down for reboot at";
120                 else
121                         assert_not_reached("Unknown mode!");
122
123                 if (asprintf(&l, "%s %s!",
124                              prefix,
125                              format_timestamp(date, sizeof(date), c->elapse)) < 0)
126                         log_error("Failed to allocate wall message");
127                 else {
128                         utmp_wall(l);
129                         free(l);
130                 }
131         }
132 }
133
134 static usec_t when_wall(usec_t n, usec_t elapse) {
135
136         static const struct {
137                 usec_t delay;
138                 usec_t interval;
139         } table[] = {
140                 { 10 * USEC_PER_MINUTE, USEC_PER_MINUTE      },
141                 { USEC_PER_HOUR,        15 * USEC_PER_MINUTE },
142                 { 3 * USEC_PER_HOUR,    30 * USEC_PER_MINUTE }
143         };
144
145         usec_t left, sub;
146         unsigned i;
147
148         /* If the time is already passed, then don't announce */
149         if (n >= elapse)
150                 return 0;
151
152         left = elapse - n;
153         for (i = 0; i < ELEMENTSOF(table); i++)
154                 if (n + table[i].delay >= elapse)
155                         sub = ((left / table[i].interval) * table[i].interval);
156
157         if (i >= ELEMENTSOF(table))
158                 sub = ((left / USEC_PER_HOUR) * USEC_PER_HOUR);
159
160         return elapse > sub ? elapse - sub : 1;
161 }
162
163 static usec_t when_nologin(usec_t elapse) {
164         return elapse > 5*USEC_PER_MINUTE ? elapse - 5*USEC_PER_MINUTE : 1;
165 }
166
167 int main(int argc, char *argv[]) {
168         enum {
169                 FD_SOCKET,
170                 FD_WALL_TIMER,
171                 FD_NOLOGIN_TIMER,
172                 FD_SHUTDOWN_TIMER,
173                 _FD_MAX
174         };
175
176         int r = 4, n_fds;
177         int one = 1;
178         struct shutdownd_command c;
179         struct pollfd pollfd[_FD_MAX];
180         bool exec_shutdown = false, unlink_nologin = false, failed = false;
181         unsigned i;
182
183         if (getppid() != 1) {
184                 log_error("This program should be invoked by init only.");
185                 return 1;
186         }
187
188         if (argc > 1) {
189                 log_error("This program does not take arguments.");
190                 return 1;
191         }
192
193         log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
194         log_parse_environment();
195         log_open();
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 1;
200         }
201
202         if (n_fds != 1) {
203                 log_error("Need exactly one file descriptor.");
204                 return 2;
205         }
206
207         if (setsockopt(SD_LISTEN_FDS_START, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
208                 log_error("SO_PASSCRED failed: %m");
209                 return 3;
210         }
211
212         zero(c);
213         zero(pollfd);
214
215         pollfd[FD_SOCKET].fd = SD_LISTEN_FDS_START;
216         pollfd[FD_SOCKET].events = POLLIN;
217
218         for (i = 0; i < _FD_MAX; i++) {
219
220                 if (i == FD_SOCKET)
221                         continue;
222
223                 pollfd[i].events = POLLIN;
224
225                 if ((pollfd[i].fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC)) < 0) {
226                         log_error("timerfd_create(): %m");
227                         failed = false;
228                 }
229         }
230
231         if (failed)
232                 goto finish;
233
234         log_debug("systemd-shutdownd running as pid %lu", (unsigned long) getpid());
235
236         sd_notify(false,
237                   "READY=1\n"
238                   "STATUS=Processing requests...");
239
240         do {
241                 int k;
242                 usec_t n;
243
244                 if (poll(pollfd, _FD_MAX, -1) < 0) {
245
246                         if (errno == EAGAIN || errno == EINTR)
247                                 continue;
248
249                         log_error("poll(): %m");
250                         goto finish;
251                 }
252
253                 n = now(CLOCK_REALTIME);
254
255                 if (pollfd[FD_SOCKET].revents) {
256
257                         if ((k = read_packet(pollfd[FD_SOCKET].fd, &c)) < 0)
258                                 goto finish;
259                         else if (k > 0 && c.elapse > 0) {
260                                 struct itimerspec its;
261                                 char date[FORMAT_TIMESTAMP_MAX];
262
263                                 if (c.warn_wall) {
264                                         /* Send wall messages every so often */
265                                         zero(its);
266                                         timespec_store(&its.it_value, when_wall(n, c.elapse));
267                                         if (timerfd_settime(pollfd[FD_WALL_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
268                                                 log_error("timerfd_settime(): %m");
269                                                 goto finish;
270                                         }
271
272                                         /* Warn immediately if less than 15 minutes are left */
273                                         if (n < c.elapse &&
274                                             n + 15*USEC_PER_MINUTE >= c.elapse)
275                                                 warn_wall(&c);
276                                 }
277
278                                 /* Disallow logins 5 minutes prior to shutdown */
279                                 zero(its);
280                                 timespec_store(&its.it_value, when_nologin(c.elapse));
281                                 if (timerfd_settime(pollfd[FD_NOLOGIN_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
282                                         log_error("timerfd_settime(): %m");
283                                         goto finish;
284                                 }
285
286                                 /* Shutdown after the specified time is reached */
287                                 zero(its);
288                                 timespec_store(&its.it_value, c.elapse);
289                                 if (timerfd_settime(pollfd[FD_SHUTDOWN_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
290                                         log_error("timerfd_settime(): %m");
291                                         goto finish;
292                                 }
293
294                                 sd_notifyf(false,
295                                            "STATUS=Shutting down at %s...",
296                                            format_timestamp(date, sizeof(date), c.elapse));
297                         }
298                 }
299
300                 if (pollfd[FD_WALL_TIMER].revents) {
301                         struct itimerspec its;
302
303                         warn_wall(&c);
304                         flush_fd(pollfd[FD_WALL_TIMER].fd);
305
306                         /* Restart timer */
307                         zero(its);
308                         timespec_store(&its.it_value, when_wall(n, c.elapse));
309                         if (timerfd_settime(pollfd[FD_WALL_TIMER].fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
310                                 log_error("timerfd_settime(): %m");
311                                 goto finish;
312                         }
313                 }
314
315                 if (pollfd[FD_NOLOGIN_TIMER].revents) {
316                         int e;
317
318                         if ((e = touch("/etc/nologin")) < 0)
319                                 log_error("Failed to create /etc/nologin: %s", strerror(-e));
320                         else
321                                 unlink_nologin = true;
322
323                         flush_fd(pollfd[FD_NOLOGIN_TIMER].fd);
324                 }
325
326                 if (pollfd[FD_SHUTDOWN_TIMER].revents) {
327                         exec_shutdown = true;
328                         goto finish;
329                 }
330
331         } while (c.elapse > 0);
332
333         r = 0;
334
335         log_debug("systemd-shutdownd stopped as pid %lu", (unsigned long) getpid());
336
337 finish:
338
339         for (i = 0; i < _FD_MAX; i++)
340                 if (pollfd[i].fd >= 0)
341                         close_nointr_nofail(pollfd[i].fd);
342
343         if (exec_shutdown) {
344                 char sw[3];
345
346                 sw[0] = '-';
347                 sw[1] = c.mode;
348                 sw[2] = 0;
349
350                 execl(SYSTEMCTL_BINARY_PATH, "shutdown", sw, "now", NULL);
351                 log_error("Failed to execute /sbin/shutdown: %m");
352         }
353
354         if (unlink_nologin)
355                 unlink("/etc/nologin");
356
357         sd_notify(false,
358                   "STATUS=Exiting...");
359
360         return r;
361 }