chiark / gitweb /
fileio: fix MIN/MAX mixup (#3896)
[elogind.git] / src / shared / utmp-wtmp.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd 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   systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <poll.h>
23 #include <stddef.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/time.h>
28 #include <sys/utsname.h>
29 #include <unistd.h>
30 #include <utmpx.h>
31
32 #include "alloc-util.h"
33 #include "fd-util.h"
34 #include "hostname-util.h"
35 #include "macro.h"
36 #include "path-util.h"
37 #include "string-util.h"
38 #include "terminal-util.h"
39 #include "time-util.h"
40 #include "user-util.h"
41 #include "util.h"
42 #include "utmp-wtmp.h"
43
44 int utmp_get_runlevel(int *runlevel, int *previous) {
45         struct utmpx *found, lookup = { .ut_type = RUN_LVL };
46         int r;
47         const char *e;
48
49         assert(runlevel);
50
51         /* If these values are set in the environment this takes
52          * precedence. Presumably, sysvinit does this to work around a
53          * race condition that would otherwise exist where we'd always
54          * go to disk and hence might read runlevel data that might be
55          * very new and does not apply to the current script being
56          * executed. */
57
58         e = getenv("RUNLEVEL");
59         if (e && e[0] > 0) {
60                 *runlevel = e[0];
61
62                 if (previous) {
63                         /* $PREVLEVEL seems to be an Upstart thing */
64
65                         e = getenv("PREVLEVEL");
66                         if (e && e[0] > 0)
67                                 *previous = e[0];
68                         else
69                                 *previous = 0;
70                 }
71
72                 return 0;
73         }
74
75         if (utmpxname(_PATH_UTMPX) < 0)
76                 return -errno;
77
78         setutxent();
79
80         found = getutxid(&lookup);
81         if (!found)
82                 r = -errno;
83         else {
84                 int a, b;
85
86                 a = found->ut_pid & 0xFF;
87                 b = (found->ut_pid >> 8) & 0xFF;
88
89                 *runlevel = a;
90                 if (previous)
91                         *previous = b;
92
93                 r = 0;
94         }
95
96         endutxent();
97
98         return r;
99 }
100
101 static void init_timestamp(struct utmpx *store, usec_t t) {
102         assert(store);
103
104         if (t <= 0)
105                 t = now(CLOCK_REALTIME);
106
107         store->ut_tv.tv_sec = t / USEC_PER_SEC;
108         store->ut_tv.tv_usec = t % USEC_PER_SEC;
109 }
110
111 static void init_entry(struct utmpx *store, usec_t t) {
112         struct utsname uts = {};
113
114         assert(store);
115
116         init_timestamp(store, t);
117
118         if (uname(&uts) >= 0)
119                 strncpy(store->ut_host, uts.release, sizeof(store->ut_host));
120
121         strncpy(store->ut_line, "~", sizeof(store->ut_line));  /* or ~~ ? */
122         strncpy(store->ut_id, "~~", sizeof(store->ut_id));
123 }
124
125 static int write_entry_utmp(const struct utmpx *store) {
126         int r;
127
128         assert(store);
129
130         /* utmp is similar to wtmp, but there is only one entry for
131          * each entry type resp. user; i.e. basically a key/value
132          * table. */
133
134         if (utmpxname(_PATH_UTMPX) < 0)
135                 return -errno;
136
137         setutxent();
138
139         if (!pututxline(store))
140                 r = -errno;
141         else
142                 r = 0;
143
144         endutxent();
145
146         return r;
147 }
148
149 static int write_entry_wtmp(const struct utmpx *store) {
150         assert(store);
151
152         /* wtmp is a simple append-only file where each entry is
153         simply appended to the end; i.e. basically a log. */
154
155         errno = 0;
156         updwtmpx(_PATH_WTMPX, store);
157         return -errno;
158 }
159
160 static int write_utmp_wtmp(const struct utmpx *store_utmp, const struct utmpx *store_wtmp) {
161         int r, s;
162
163         r = write_entry_utmp(store_utmp);
164         s = write_entry_wtmp(store_wtmp);
165
166         if (r >= 0)
167                 r = s;
168
169         /* If utmp/wtmp have been disabled, that's a good thing, hence
170          * ignore the errors */
171         if (r == -ENOENT)
172                 r = 0;
173
174         return r;
175 }
176
177 static int write_entry_both(const struct utmpx *store) {
178         return write_utmp_wtmp(store, store);
179 }
180
181 int utmp_put_shutdown(void) {
182         struct utmpx store = {};
183
184         init_entry(&store, 0);
185
186         store.ut_type = RUN_LVL;
187         strncpy(store.ut_user, "shutdown", sizeof(store.ut_user));
188
189         return write_entry_both(&store);
190 }
191
192 int utmp_put_reboot(usec_t t) {
193         struct utmpx store = {};
194
195         init_entry(&store, t);
196
197         store.ut_type = BOOT_TIME;
198         strncpy(store.ut_user, "reboot", sizeof(store.ut_user));
199
200         return write_entry_both(&store);
201 }
202
203 _pure_ static const char *sanitize_id(const char *id) {
204         size_t l;
205
206         assert(id);
207         l = strlen(id);
208
209         if (l <= sizeof(((struct utmpx*) NULL)->ut_id))
210                 return id;
211
212         return id + l - sizeof(((struct utmpx*) NULL)->ut_id);
213 }
214
215 int utmp_put_init_process(const char *id, pid_t pid, pid_t sid, const char *line, int ut_type, const char *user) {
216         struct utmpx store = {
217                 .ut_type = INIT_PROCESS,
218                 .ut_pid = pid,
219                 .ut_session = sid,
220         };
221         int r;
222
223         assert(id);
224
225         init_timestamp(&store, 0);
226
227         /* ut_id needs only be nul-terminated if it is shorter than sizeof(ut_id) */
228         strncpy(store.ut_id, sanitize_id(id), sizeof(store.ut_id));
229
230         if (line)
231                 strncpy(store.ut_line, basename(line), sizeof(store.ut_line));
232
233         r = write_entry_both(&store);
234         if (r < 0)
235                 return r;
236
237         if (ut_type == LOGIN_PROCESS || ut_type == USER_PROCESS) {
238                 store.ut_type = LOGIN_PROCESS;
239                 r = write_entry_both(&store);
240                 if (r < 0)
241                         return r;
242         }
243
244         if (ut_type == USER_PROCESS) {
245                 store.ut_type = USER_PROCESS;
246                 strncpy(store.ut_user, user, sizeof(store.ut_user)-1);
247                 r = write_entry_both(&store);
248                 if (r < 0)
249                         return r;
250         }
251
252         return 0;
253 }
254
255 int utmp_put_dead_process(const char *id, pid_t pid, int code, int status) {
256         struct utmpx lookup = {
257                 .ut_type = INIT_PROCESS /* looks for DEAD_PROCESS, LOGIN_PROCESS, USER_PROCESS, too */
258         }, store, store_wtmp, *found;
259
260         assert(id);
261
262         setutxent();
263
264         /* ut_id needs only be nul-terminated if it is shorter than sizeof(ut_id) */
265         strncpy(lookup.ut_id, sanitize_id(id), sizeof(lookup.ut_id));
266
267         found = getutxid(&lookup);
268         if (!found)
269                 return 0;
270
271         if (found->ut_pid != pid)
272                 return 0;
273
274         memcpy(&store, found, sizeof(store));
275         store.ut_type = DEAD_PROCESS;
276         store.ut_exit.e_termination = code;
277         store.ut_exit.e_exit = status;
278
279         zero(store.ut_user);
280         zero(store.ut_host);
281         zero(store.ut_tv);
282
283         memcpy(&store_wtmp, &store, sizeof(store_wtmp));
284         /* wtmp wants the current time */
285         init_timestamp(&store_wtmp, 0);
286
287         return write_utmp_wtmp(&store, &store_wtmp);
288 }
289
290
291 int utmp_put_runlevel(int runlevel, int previous) {
292         struct utmpx store = {};
293         int r;
294
295         assert(runlevel > 0);
296
297         if (previous <= 0) {
298                 /* Find the old runlevel automatically */
299
300                 r = utmp_get_runlevel(&previous, NULL);
301                 if (r < 0) {
302                         if (r != -ESRCH)
303                                 return r;
304
305                         previous = 0;
306                 }
307         }
308
309         if (previous == runlevel)
310                 return 0;
311
312         init_entry(&store, 0);
313
314         store.ut_type = RUN_LVL;
315         store.ut_pid = (runlevel & 0xFF) | ((previous & 0xFF) << 8);
316         strncpy(store.ut_user, "runlevel", sizeof(store.ut_user));
317
318         return write_entry_both(&store);
319 }
320
321 #define TIMEOUT_MSEC 50
322
323 static int write_to_terminal(const char *tty, const char *message) {
324         _cleanup_close_ int fd = -1;
325         const char *p;
326         size_t left;
327         usec_t end;
328
329         assert(tty);
330         assert(message);
331
332         fd = open(tty, O_WRONLY|O_NDELAY|O_NOCTTY|O_CLOEXEC);
333         if (fd < 0 || !isatty(fd))
334                 return -errno;
335
336         p = message;
337         left = strlen(message);
338
339         end = now(CLOCK_MONOTONIC) + TIMEOUT_MSEC*USEC_PER_MSEC;
340
341         while (left > 0) {
342                 ssize_t n;
343                 struct pollfd pollfd = {
344                         .fd = fd,
345                         .events = POLLOUT,
346                 };
347                 usec_t t;
348                 int k;
349
350                 t = now(CLOCK_MONOTONIC);
351
352                 if (t >= end)
353                         return -ETIME;
354
355                 k = poll(&pollfd, 1, (end - t) / USEC_PER_MSEC);
356                 if (k < 0)
357                         return -errno;
358
359                 if (k == 0)
360                         return -ETIME;
361
362                 n = write(fd, p, left);
363                 if (n < 0) {
364                         if (errno == EAGAIN)
365                                 continue;
366
367                         return -errno;
368                 }
369
370                 assert((size_t) n <= left);
371
372                 p += n;
373                 left -= n;
374         }
375
376         return 0;
377 }
378
379 int utmp_wall(
380         const char *message,
381         const char *username,
382         const char *origin_tty,
383         bool (*match_tty)(const char *tty, void *userdata),
384         void *userdata) {
385
386         _cleanup_free_ char *text = NULL, *hn = NULL, *un = NULL, *stdin_tty = NULL;
387         char date[FORMAT_TIMESTAMP_MAX];
388         struct utmpx *u;
389         int r;
390
391         hn = gethostname_malloc();
392         if (!hn)
393                 return -ENOMEM;
394         if (!username) {
395                 un = getlogname_malloc();
396                 if (!un)
397                         return -ENOMEM;
398         }
399
400         if (!origin_tty) {
401                 getttyname_harder(STDIN_FILENO, &stdin_tty);
402                 origin_tty = stdin_tty;
403         }
404
405         if (asprintf(&text,
406                      "\a\r\n"
407                      "Broadcast message from %s@%s%s%s (%s):\r\n\r\n"
408                      "%s\r\n\r\n",
409                      un ?: username, hn,
410                      origin_tty ? " on " : "", strempty(origin_tty),
411                      format_timestamp(date, sizeof(date), now(CLOCK_REALTIME)),
412                      message) < 0)
413                 return -ENOMEM;
414
415         setutxent();
416
417         r = 0;
418
419         while ((u = getutxent())) {
420                 _cleanup_free_ char *buf = NULL;
421                 const char *path;
422                 int q;
423
424                 if (u->ut_type != USER_PROCESS || u->ut_user[0] == 0)
425                         continue;
426
427                 /* this access is fine, because strlen("/dev/") << 32 (UT_LINESIZE) */
428                 if (path_startswith(u->ut_line, "/dev/"))
429                         path = u->ut_line;
430                 else {
431                         if (asprintf(&buf, "/dev/%.*s", (int) sizeof(u->ut_line), u->ut_line) < 0)
432                                 return -ENOMEM;
433
434                         path = buf;
435                 }
436
437                 if (!match_tty || match_tty(path, userdata)) {
438                         q = write_to_terminal(path, text);
439                         if (q < 0)
440                                 r = q;
441                 }
442         }
443
444         return r;
445 }