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