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