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