Debian Codegraph @

src/login/logind-inhibit.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <sys/stat.h>
5 #include <threads.h>
6 #include <unistd.h>
7
8 #include "sd-event.h"
9
10 #include "alloc-util.h"
11 #include "env-file.h"
12 #include "errno-util.h"
13 #include "escape.h"
14 #include "extract-word.h"
15 #include "fd-util.h"
16 #include "format-util.h"
17 #include "fs-util.h"
18 #include "hashmap.h"
19 #include "io-util.h"
20 #include "json-util.h"
21 #include "log.h"
22 #include "logind-session.h"
23 #include "logind.h"
24 #include "logind-dbus.h"
25 #include "logind-inhibit.h"
26 #include "mkdir.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "string-table.h"
30 #include "string-util.h"
31 #include "tmpfile-util.h"
32 #include "user-util.h"
33
34 static void inhibitor_remove_fifo(Inhibitor *i);
35
36 int inhibitor_new(Manager *m, const char* id, Inhibitor **ret) {
37 _cleanup_(inhibitor_freep) Inhibitor *i = NULL;
38 int r;
39
40 assert(m);
41 assert(id);
42 assert(ret);
43
44 i = new(Inhibitor, 1);
45 if (!i)
46 return -ENOMEM;
47
48 *i = (Inhibitor) {
49 .manager = m,
50 .id = strdup(id),
51 .state_file = path_join("/run/systemd/inhibit/", id),
52 .what = _INHIBIT_WHAT_INVALID,
53 .mode = _INHIBIT_MODE_INVALID,
54 .uid = UID_INVALID,
55 .fifo_fd = -EBADF,
56 .pid = PIDREF_NULL,
57 };
58
59 if (!i->id || !i->state_file)
60 return -ENOMEM;
61
62 r = hashmap_put(m->inhibitors, i->id, i);
63 if (r < 0)
64 return r;
65
66 *ret = TAKE_PTR(i);
67 return 0;
68 }
69
70 Inhibitor* inhibitor_free(Inhibitor *i) {
71
72 if (!i)
73 return NULL;
74
75 free(i->who);
76 free(i->why);
77
78 sd_event_source_unref(i->event_source);
79 safe_close(i->fifo_fd);
80
81 hashmap_remove(i->manager->inhibitors, i->id);
82
83 /* Note that we don't remove neither the state file nor the fifo path here, since we want both to
84 * survive daemon restarts */
85 free(i->fifo_path);
86 free(i->state_file);
87 free(i->id);
88
89 pidref_done(&i->pid);
90
91 return mfree(i);
92 }
93
94 static int inhibitor_save(Inhibitor *i) {
95 int r;
96
97 assert(i);
98
99 r = mkdir_safe_label("/run/systemd/inhibit", 0755, 0, 0, MKDIR_WARN_MODE);
100 if (r < 0)
101 return log_error_errno(r, "Failed to create /run/systemd/inhibit/: %m");
102
103 _cleanup_(unlink_and_freep) char *temp_path = NULL;
104 _cleanup_fclose_ FILE *f = NULL;
105 r = fopen_tmpfile_linkable(i->state_file, O_WRONLY|O_CLOEXEC, &temp_path, &f);
106 if (r < 0)
107 return log_error_errno(r, "Failed to create state file '%s': %m", i->state_file);
108
109 if (fchmod(fileno(f), 0644) < 0)
110 return log_error_errno(errno, "Failed to set access mode for state file '%s' to 0644: %m", i->state_file);
111
112 fprintf(f,
113 "# This is private data. Do not parse.\n"
114 "WHAT=%s\n"
115 "MODE=%s\n"
116 "UID="UID_FMT"\n",
117 inhibit_what_to_string(i->what),
118 inhibit_mode_to_string(i->mode),
119 i->uid);
120
121 if (pidref_is_set(&i->pid)) {
122 fprintf(f, "PID="PID_FMT"\n", i->pid.pid);
123
124 (void) pidref_acquire_pidfd_id(&i->pid);
125 if (i->pid.fd_id != 0)
126 fprintf(f, "PIDFDID=%" PRIu64 "\n", i->pid.fd_id);
127 }
128
129 /* For historical reasons there's double escaping applied here: once here via cescape(), and once by
130 * env_file_fputs_assignment() */
131 _cleanup_free_ char *who_escaped = cescape(i->who);
132 if (!who_escaped)
133 return log_oom();
134 env_file_fputs_assignment(f, "WHO=", who_escaped);
135
136 _cleanup_free_ char *why_escaped = cescape(i->why);
137 if (!why_escaped)
138 return log_oom();
139 env_file_fputs_assignment(f, "WHY=", why_escaped);
140
141 env_file_fputs_assignment(f, "FIFO=", i->fifo_path);
142
143 r = flink_tmpfile(f, temp_path, i->state_file, LINK_TMPFILE_REPLACE);
144 if (r < 0)
145 return log_error_errno(r, "Failed to move '%s' into place: %m", i->state_file);
146
147 temp_path = mfree(temp_path); /* disarm auto-destroy: temporary file does not exist anymore */
148 return 0;
149 }
150
151 static int bus_manager_send_inhibited_change(Inhibitor *i) {
152 assert(i);
153
154 return manager_send_changed(i->manager,
155 i->mode == INHIBIT_DELAY ? "DelayInhibited" : "BlockInhibited",
156 "NCurrentInhibitors");
157 }
158
159 int inhibitor_start(Inhibitor *i) {
160 assert(i);
161
162 if (i->started)
163 return 0;
164
165 dual_timestamp_now(&i->since);
166
167 log_debug("Inhibitor %s (%s) pid="PID_FMT" uid="UID_FMT" mode=%s started.",
168 strna(i->who), strna(i->why),
169 i->pid.pid, i->uid,
170 inhibit_mode_to_string(i->mode));
171
172 i->started = true;
173
174 inhibitor_save(i);
175
176 bus_manager_send_inhibited_change(i);
177
178 return 0;
179 }
180
181 void inhibitor_stop(Inhibitor *i) {
182 assert(i);
183
184 if (i->started)
185 log_debug("Inhibitor %s (%s) pid="PID_FMT" uid="UID_FMT" mode=%s stopped.",
186 strna(i->who), strna(i->why),
187 i->pid.pid, i->uid,
188 inhibit_mode_to_string(i->mode));
189
190 inhibitor_remove_fifo(i);
191
192 if (i->state_file)
193 (void) unlink(i->state_file);
194
195 i->started = false;
196
197 bus_manager_send_inhibited_change(i);
198 }
199
200 int inhibitor_load(Inhibitor *i) {
201 _cleanup_free_ char *what = NULL, *uid = NULL, *pid = NULL, *pidfdid = NULL, *who = NULL, *why = NULL, *mode = NULL;
202 InhibitWhat w;
203 InhibitMode mm;
204 char *cc;
205 ssize_t l;
206 int r;
207
208 r = parse_env_file(NULL, i->state_file,
209 "WHAT", &what,
210 "UID", &uid,
211 "PID", &pid,
212 "PIDFDID", &pidfdid,
213 "WHO", &who,
214 "WHY", &why,
215 "MODE", &mode,
216 "FIFO", &i->fifo_path);
217 if (r < 0)
218 return log_error_errno(r, "Failed to read %s: %m", i->state_file);
219
220 w = what ? inhibit_what_from_string(what) : 0;
221 if (w >= 0)
222 i->what = w;
223
224 mm = mode ? inhibit_mode_from_string(mode) : INHIBIT_BLOCK;
225 if (mm >= 0)
226 i->mode = mm;
227
228 if (uid) {
229 r = parse_uid(uid, &i->uid);
230 if (r < 0)
231 log_debug_errno(r, "Failed to parse UID of inhibitor: %s", uid);
232 }
233
234 pidref_done(&i->pid);
235 if (pid) {
236 r = pidref_set_pidstr(&i->pid, pid);
237 if (r < 0)
238 log_debug_errno(r, "Failed to parse PID of inhibitor, ignoring: %s", pid);
239 else if (pidfdid) {
240 uint64_t fd_id;
241 r = safe_atou64(pidfdid, &fd_id);
242 if (r < 0)
243 log_warning_errno(r, "Failed to parse leader pidfd ID, ignoring: %s", pidfdid);
244 else {
245 (void) pidref_acquire_pidfd_id(&i->pid);
246
247 if (fd_id != i->pid.fd_id) {
248 log_debug("PID got recycled, ignoring.");
249 pidref_done(&i->pid);
250 }
251 }
252 }
253 }
254
255 if (who) {
256 l = cunescape(who, 0, &cc);
257 if (l < 0)
258 return log_debug_errno(l, "Failed to unescape \"who\" of inhibitor: %m");
259
260 free_and_replace(i->who, cc);
261 }
262
263 if (why) {
264 l = cunescape(why, 0, &cc);
265 if (l < 0)
266 return log_debug_errno(l, "Failed to unescape \"why\" of inhibitor: %m");
267
268 free_and_replace(i->why, cc);
269 }
270
271 if (i->fifo_path) {
272 _cleanup_close_ int fd = -EBADF;
273
274 /* Let's reopen the FIFO on both sides, and close the writing side right away */
275 fd = inhibitor_create_fifo(i);
276 if (fd < 0)
277 return log_error_errno(fd, "Failed to reopen FIFO: %m");
278 }
279
280 return 0;
281 }
282
283 static int inhibitor_dispatch_fifo(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
284 Inhibitor *i = ASSERT_PTR(userdata);
285
286 assert(s);
287 assert(fd == i->fifo_fd);
288
289 inhibitor_stop(i);
290 inhibitor_free(i);
291
292 return 0;
293 }
294
295 int inhibitor_create_fifo(Inhibitor *i) {
296 int r;
297
298 assert(i);
299
300 /* Create FIFO */
301 if (!i->fifo_path) {
302 r = mkdir_safe_label("/run/systemd/inhibit", 0755, 0, 0, MKDIR_WARN_MODE);
303 if (r < 0)
304 return r;
305
306 i->fifo_path = strjoin("/run/systemd/inhibit/", i->id, ".ref");
307 if (!i->fifo_path)
308 return -ENOMEM;
309
310 if (mkfifo(i->fifo_path, 0600) < 0 && errno != EEXIST)
311 return -errno;
312 }
313
314 /* Open reading side */
315 if (i->fifo_fd < 0) {
316 i->fifo_fd = open(i->fifo_path, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
317 if (i->fifo_fd < 0)
318 return -errno;
319 }
320
321 if (!i->event_source) {
322 r = sd_event_add_io(i->manager->event, &i->event_source, i->fifo_fd, 0, inhibitor_dispatch_fifo, i);
323 if (r < 0)
324 return r;
325
326 r = sd_event_source_set_priority(i->event_source, SD_EVENT_PRIORITY_IDLE-10);
327 if (r < 0)
328 return r;
329
330 (void) sd_event_source_set_description(i->event_source, "inhibitor-ref");
331 }
332
333 /* Open writing side */
334 return RET_NERRNO(open(i->fifo_path, O_WRONLY|O_CLOEXEC|O_NONBLOCK));
335 }
336
337 static void inhibitor_remove_fifo(Inhibitor *i) {
338 assert(i);
339
340 i->event_source = sd_event_source_unref(i->event_source);
341 i->fifo_fd = safe_close(i->fifo_fd);
342
343 if (i->fifo_path) {
344 (void) unlink(i->fifo_path);
345 i->fifo_path = mfree(i->fifo_path);
346 }
347 }
348
349 bool inhibitor_is_orphan(Inhibitor *i) {
350 assert(i);
351
352 if (!i->started)
353 return true;
354
355 if (!i->fifo_path)
356 return true;
357
358 if (i->fifo_fd < 0)
359 return true;
360
361 if (pipe_eof(i->fifo_fd) != 0)
362 return true;
363
364 return false;
365 }
366
367 InhibitWhat manager_inhibit_what(Manager *m, InhibitMode mode) {
368 Inhibitor *i;
369 InhibitWhat what = 0;
370
371 assert(m);
372
373 HASHMAP_FOREACH(i, m->inhibitors)
374 if (i->started && i->mode == mode)
375 what |= i->what;
376
377 return what;
378 }
379
380 static int pidref_is_active_session(Manager *m, const PidRef *pid) {
381 Session *s;
382 int r;
383
384 assert(m);
385 assert(pid);
386
387 /* Get client session. This is not what you are looking for these days.
388 * FIXME #6852 */
389 r = manager_get_session_by_pidref(m, pid, &s);
390 if (r < 0)
391 return r;
392
393 /* If there's no session assigned to it, then it's globally active on all ttys */
394 if (r == 0)
395 return 1;
396
397 return session_is_active(s);
398 }
399
400 bool manager_is_inhibited(
401 Manager *m,
402 InhibitWhat w,
403 dual_timestamp *since,
404 ManagerIsInhibitedFlags flags,
405 uid_t uid_to_ignore,
406 Inhibitor **ret_offending) {
407
408 Inhibitor *i, *offending = NULL;
409 struct dual_timestamp ts = DUAL_TIMESTAMP_NULL;
410 bool inhibited = false;
411
412 assert(m);
413 assert(w > 0);
414 assert(w < _INHIBIT_WHAT_MAX);
415
416 HASHMAP_FOREACH(i, m->inhibitors) {
417 if (!i->started)
418 continue;
419
420 if (!(i->what & w))
421 continue;
422
423 if (FLAGS_SET(flags, MANAGER_IS_INHIBITED_CHECK_DELAY) != (i->mode == INHIBIT_DELAY))
424 continue;
425
426 if (FLAGS_SET(flags, MANAGER_IS_INHIBITED_IGNORE_INACTIVE) &&
427 pidref_is_active_session(m, &i->pid) <= 0)
428 continue;
429
430 if (i->mode == INHIBIT_BLOCK_WEAK &&
431 uid_is_valid(uid_to_ignore) &&
432 uid_to_ignore == i->uid)
433 continue;
434
435 if (!inhibited || i->since.monotonic < ts.monotonic)
436 ts = i->since;
437
438 inhibited = true;
439
440 /* Stronger inhibitor wins */
441 if (!offending || (i->mode < offending->mode))
442 offending = i;
443 }
444
445 if (since)
446 *since = ts;
447
448 if (ret_offending)
449 *ret_offending = offending;
450
451 return inhibited;
452 }
453
454 const char* inhibit_what_to_string(InhibitWhat w) {
455 static thread_local char buffer[STRLEN(
456 "shutdown:"
457 "sleep:"
458 "idle:"
459 "handle-power-key:"
460 "handle-suspend-key:"
461 "handle-hibernate-key:"
462 "handle-lid-switch:"
463 "handle-reboot-key")+1];
464 char *p;
465
466 if (!inhibit_what_is_valid(w))
467 return NULL;
468
469 p = buffer;
470 if (w & INHIBIT_SHUTDOWN)
471 p = stpcpy(p, "shutdown:");
472 if (w & INHIBIT_SLEEP)
473 p = stpcpy(p, "sleep:");
474 if (w & INHIBIT_IDLE)
475 p = stpcpy(p, "idle:");
476 if (w & INHIBIT_HANDLE_POWER_KEY)
477 p = stpcpy(p, "handle-power-key:");
478 if (w & INHIBIT_HANDLE_SUSPEND_KEY)
479 p = stpcpy(p, "handle-suspend-key:");
480 if (w & INHIBIT_HANDLE_HIBERNATE_KEY)
481 p = stpcpy(p, "handle-hibernate-key:");
482 if (w & INHIBIT_HANDLE_LID_SWITCH)
483 p = stpcpy(p, "handle-lid-switch:");
484 if (w & INHIBIT_HANDLE_REBOOT_KEY)
485 p = stpcpy(p, "handle-reboot-key:");
486
487 if (p > buffer)
488 *(p-1) = 0;
489 else
490 *p = 0;
491
492 return buffer;
493 }
494
495 int inhibit_what_from_string(const char *s) {
496 InhibitWhat what = 0;
497
498 for (const char *p = s;;) {
499 _cleanup_free_ char *word = NULL;
500 int r;
501
502 /* A sanity check that our return values fit in an int */
503 assert_cc((int) _INHIBIT_WHAT_MAX == _INHIBIT_WHAT_MAX);
504
505 r = extract_first_word(&p, &word, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
506 if (r < 0)
507 return r;
508 if (r == 0)
509 return what;
510
511 if (streq(word, "shutdown"))
512 what |= INHIBIT_SHUTDOWN;
513 else if (streq(word, "sleep"))
514 what |= INHIBIT_SLEEP;
515 else if (streq(word, "idle"))
516 what |= INHIBIT_IDLE;
517 else if (streq(word, "handle-power-key"))
518 what |= INHIBIT_HANDLE_POWER_KEY;
519 else if (streq(word, "handle-suspend-key"))
520 what |= INHIBIT_HANDLE_SUSPEND_KEY;
521 else if (streq(word, "handle-hibernate-key"))
522 what |= INHIBIT_HANDLE_HIBERNATE_KEY;
523 else if (streq(word, "handle-lid-switch"))
524 what |= INHIBIT_HANDLE_LID_SWITCH;
525 else if (streq(word, "handle-reboot-key"))
526 what |= INHIBIT_HANDLE_REBOOT_KEY;
527 else
528 return _INHIBIT_WHAT_INVALID;
529 }
530 }
531
532 static int inhibit_what_build_json(sd_json_variant **ret, const char *name, void *userdata) {
533 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
534 InhibitWhat *what = ASSERT_PTR(userdata);
535 int r;
536
537 assert(ret);
538 assert(inhibit_what_is_valid(*what));
539
540 for (unsigned bit = 0; (1U << bit) < (unsigned) _INHIBIT_WHAT_MAX; bit++) {
541 InhibitWhat w = 1U << bit;
542
543 if (!FLAGS_SET(*what, w))
544 continue;
545
546 r = sd_json_variant_append_arrayb(&v, JSON_BUILD_STRING_UNDERSCORIFY(inhibit_what_to_string(w)));
547 if (r < 0)
548 return r;
549 }
550
551 *ret = TAKE_PTR(v);
552 return 0;
553 }
554
555 static int inhibitor_context_build_json(sd_json_variant **ret, const char *name, void *userdata) {
556 Inhibitor *i = ASSERT_PTR(userdata);
557
558 assert(ret);
559 assert(i->mode >= 0 && i->mode < _INHIBIT_MODE_MAX);
560 assert(inhibit_what_is_valid(i->what));
561
562 return sd_json_buildo(
563 ret,
564 SD_JSON_BUILD_PAIR_STRING("Id", i->id),
565 SD_JSON_BUILD_PAIR_CALLBACK("What", inhibit_what_build_json, &i->what),
566 JSON_BUILD_PAIR_STRING_NON_EMPTY("Who", i->who),
567 JSON_BUILD_PAIR_STRING_NON_EMPTY("Why", i->why),
568 JSON_BUILD_PAIR_ENUM("Mode", inhibit_mode_to_string(i->mode)),
569 SD_JSON_BUILD_PAIR_UNSIGNED("UID", i->uid));
570 }
571
572 static int inhibitor_runtime_build_json(sd_json_variant **ret, const char *name, void *userdata) {
573 Inhibitor *i = ASSERT_PTR(userdata);
574
575 assert(ret);
576
577 return sd_json_buildo(
578 ret,
579 JSON_BUILD_PAIR_PIDREF_NON_NULL("PID", &i->pid),
580 JSON_BUILD_PAIR_DUAL_TIMESTAMP_NON_NULL("Since", &i->since));
581 }
582
583 int inhibitor_build_json(Inhibitor *i, sd_json_variant **ret) {
584 assert(i);
585 assert(ret);
586
587 return sd_json_buildo(
588 ret,
589 SD_JSON_BUILD_PAIR_CALLBACK("context", inhibitor_context_build_json, i),
590 SD_JSON_BUILD_PAIR_CALLBACK("runtime", inhibitor_runtime_build_json, i));
591 }
592
593 static const char* const inhibit_mode_table[_INHIBIT_MODE_MAX] = {
594 [INHIBIT_BLOCK] = "block",
595 [INHIBIT_BLOCK_WEAK] = "block-weak",
596 [INHIBIT_DELAY] = "delay",
597 };
598
599 DEFINE_STRING_TABLE_LOOKUP(inhibit_mode, InhibitMode);