]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/tty-ask-password-agent/tty-ask-password-agent.c
Merge pull request #11827 from keszybz/pkgconfig-variables
[thirdparty/systemd.git] / src / tty-ask-password-agent / tty-ask-password-agent.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
ec863ba6 2/***
96b2fb93 3 Copyright © 2015 Werner Fink
ec863ba6
LP
4***/
5
ec863ba6 6#include <errno.h>
3f6fd1ba
LP
7#include <fcntl.h>
8#include <getopt.h>
9#include <poll.h>
6af62124 10#include <signal.h>
3f6fd1ba
LP
11#include <stdbool.h>
12#include <stddef.h>
ec863ba6 13#include <string.h>
3f6fd1ba 14#include <sys/inotify.h>
6af62124 15#include <sys/prctl.h>
3f6fd1ba 16#include <sys/signalfd.h>
ec863ba6 17#include <sys/socket.h>
6af62124 18#include <sys/wait.h>
ec863ba6 19#include <sys/un.h>
ec863ba6 20#include <unistd.h>
ec863ba6 21
b5efdb8a 22#include "alloc-util.h"
3f6fd1ba
LP
23#include "ask-password-api.h"
24#include "conf-parser.h"
25#include "def.h"
a0956174 26#include "dirent-util.h"
6af62124 27#include "exit-status.h"
3ffd4af2 28#include "fd-util.h"
6af62124
WF
29#include "fileio.h"
30#include "hashmap.h"
c004493c 31#include "io-util.h"
6af62124 32#include "macro.h"
5e332028 33#include "main-func.h"
49e942b2 34#include "mkdir.h"
9eb977db 35#include "path-util.h"
294bf0c3 36#include "pretty-print.h"
3f6fd1ba
LP
37#include "process-util.h"
38#include "signal-util.h"
e5ebf783 39#include "socket-util.h"
07630cea 40#include "string-util.h"
21bc923a 41#include "strv.h"
288a74cc 42#include "terminal-util.h"
3f6fd1ba
LP
43#include "util.h"
44#include "utmp-wtmp.h"
ec863ba6
LP
45
46static enum {
47 ACTION_LIST,
48 ACTION_QUERY,
49 ACTION_WATCH,
50 ACTION_WALL
51} arg_action = ACTION_QUERY;
52
e5ebf783 53static bool arg_plymouth = false;
0cf84693 54static bool arg_console = false;
6af62124 55static const char *arg_device = NULL;
e5ebf783 56
21bc923a
LP
57static int ask_password_plymouth(
58 const char *message,
59 usec_t until,
e287086b 60 AskPasswordFlags flags,
21bc923a 61 const char *flag_file,
e287086b 62 char ***ret) {
21bc923a 63
fc2fffe7 64 static const union sockaddr_union sa = PLYMOUTH_SOCKET;
1d749d04 65 _cleanup_close_ int fd = -1, notify = -1;
1d749d04 66 _cleanup_free_ char *packet = NULL;
e5ebf783
LP
67 ssize_t k;
68 int r, n;
b92bea5d 69 struct pollfd pollfd[2] = {};
e5ebf783
LP
70 char buffer[LINE_MAX];
71 size_t p = 0;
72 enum {
73 POLL_SOCKET,
74 POLL_INOTIFY
75 };
76
e287086b 77 assert(ret);
21bc923a 78
e5ebf783 79 if (flag_file) {
1d749d04
ZJS
80 notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK);
81 if (notify < 0)
82 return -errno;
e5ebf783 83
1d749d04
ZJS
84 r = inotify_add_watch(notify, flag_file, IN_ATTRIB); /* for the link count */
85 if (r < 0)
86 return -errno;
e5ebf783
LP
87 }
88
1d749d04
ZJS
89 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
90 if (fd < 0)
91 return -errno;
e5ebf783 92
fc2fffe7 93 r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
4a62c710 94 if (r < 0)
00843602 95 return -errno;
e5ebf783 96
e287086b 97 if (flags & ASK_PASSWORD_ACCEPT_CACHED) {
21bc923a
LP
98 packet = strdup("c");
99 n = 1;
00843602 100 } else if (asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n) < 0)
7de80bfe 101 packet = NULL;
1d749d04 102 if (!packet)
00843602 103 return -ENOMEM;
e5ebf783 104
553acb7b
ZJS
105 r = loop_write(fd, packet, n + 1, true);
106 if (r < 0)
107 return r;
e5ebf783 108
e5ebf783
LP
109 pollfd[POLL_SOCKET].fd = fd;
110 pollfd[POLL_SOCKET].events = POLLIN;
111 pollfd[POLL_INOTIFY].fd = notify;
112 pollfd[POLL_INOTIFY].events = POLLIN;
113
114 for (;;) {
115 int sleep_for = -1, j;
116
117 if (until > 0) {
118 usec_t y;
119
120 y = now(CLOCK_MONOTONIC);
121
1602b008
LP
122 if (y > until) {
123 r = -ETIME;
124 goto finish;
125 }
e5ebf783
LP
126
127 sleep_for = (int) ((until - y) / USEC_PER_MSEC);
128 }
129
1602b008
LP
130 if (flag_file && access(flag_file, F_OK) < 0) {
131 r = -errno;
132 goto finish;
133 }
e5ebf783 134
e287086b 135 j = poll(pollfd, notify >= 0 ? 2 : 1, sleep_for);
1d749d04 136 if (j < 0) {
e5ebf783
LP
137 if (errno == EINTR)
138 continue;
139
1602b008
LP
140 r = -errno;
141 goto finish;
142 } else if (j == 0) {
143 r = -ETIME;
144 goto finish;
145 }
e5ebf783 146
e287086b 147 if (notify >= 0 && pollfd[POLL_INOTIFY].revents != 0)
665dfe93 148 (void) flush_fd(notify);
e5ebf783
LP
149
150 if (pollfd[POLL_SOCKET].revents == 0)
151 continue;
152
1d749d04 153 k = read(fd, buffer + p, sizeof(buffer) - p);
e287086b 154 if (k < 0) {
3742095b 155 if (IN_SET(errno, EINTR, EAGAIN))
e287086b
LP
156 continue;
157
1602b008
LP
158 r = -errno;
159 goto finish;
160 } else if (k == 0) {
161 r = -EIO;
162 goto finish;
163 }
e5ebf783
LP
164
165 p += k;
166
167 if (p < 1)
168 continue;
169
170 if (buffer[0] == 5) {
21bc923a 171
e287086b 172 if (flags & ASK_PASSWORD_ACCEPT_CACHED) {
21bc923a
LP
173 /* Hmm, first try with cached
174 * passwords failed, so let's retry
175 * with a normal password request */
97b11eed 176 packet = mfree(packet);
21bc923a 177
1602b008
LP
178 if (asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n) < 0) {
179 r = -ENOMEM;
180 goto finish;
181 }
21bc923a 182
553acb7b
ZJS
183 r = loop_write(fd, packet, n+1, true);
184 if (r < 0)
1602b008 185 goto finish;
21bc923a 186
e287086b 187 flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
21bc923a
LP
188 p = 0;
189 continue;
190 }
191
e5ebf783 192 /* No password, because UI not shown */
1602b008
LP
193 r = -ENOENT;
194 goto finish;
e5ebf783 195
4c701096 196 } else if (IN_SET(buffer[0], 2, 9)) {
e5ebf783 197 uint32_t size;
21bc923a 198 char **l;
e5ebf783 199
4cf07da2 200 /* One or more answers */
e5ebf783
LP
201 if (p < 5)
202 continue;
203
204 memcpy(&size, buffer+1, sizeof(size));
bb53abeb 205 size = le32toh(size);
1602b008
LP
206 if (size + 5 > sizeof(buffer)) {
207 r = -EIO;
208 goto finish;
209 }
e5ebf783
LP
210
211 if (p-5 < size)
212 continue;
213
1d749d04 214 l = strv_parse_nulstr(buffer + 5, size);
1602b008
LP
215 if (!l) {
216 r = -ENOMEM;
217 goto finish;
218 }
e5ebf783 219
e287086b 220 *ret = l;
e5ebf783 221 break;
21bc923a 222
1602b008 223 } else {
e5ebf783 224 /* Unknown packet */
1602b008
LP
225 r = -EIO;
226 goto finish;
227 }
e5ebf783
LP
228 }
229
1602b008
LP
230 r = 0;
231
232finish:
87f54463 233 explicit_bzero_safe(buffer, sizeof(buffer));
1602b008 234 return r;
e5ebf783
LP
235}
236
bbada6d7
JAS
237static int send_passwords(const char *socket_name, char **passwords) {
238 _cleanup_free_ char *packet = NULL;
239 _cleanup_close_ int socket_fd = -1;
15a3e96f 240 union sockaddr_union sa = {};
bbada6d7
JAS
241 size_t packet_length = 1;
242 char **p, *d;
5439206b 243 ssize_t n;
15a3e96f 244 int r, salen;
bbada6d7
JAS
245
246 assert(socket_name);
247
15a3e96f
LP
248 salen = sockaddr_un_set_path(&sa.un, socket_name);
249 if (salen < 0)
250 return salen;
251
bbada6d7
JAS
252 STRV_FOREACH(p, passwords)
253 packet_length += strlen(*p) + 1;
254
255 packet = new(char, packet_length);
256 if (!packet)
257 return -ENOMEM;
258
259 packet[0] = '+';
260
261 d = packet + 1;
262 STRV_FOREACH(p, passwords)
263 d = stpcpy(d, *p) + 1;
264
265 socket_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
266 if (socket_fd < 0) {
267 r = log_debug_errno(errno, "socket(): %m");
268 goto finish;
269 }
270
15a3e96f 271 n = sendto(socket_fd, packet, packet_length, MSG_NOSIGNAL, &sa.sa, salen);
5439206b 272 if (n < 0) {
bbada6d7 273 r = log_debug_errno(errno, "sendto(): %m");
5439206b
LP
274 goto finish;
275 }
276
277 r = (int) n;
bbada6d7
JAS
278
279finish:
87f54463 280 explicit_bzero_safe(packet, packet_length);
bbada6d7
JAS
281 return r;
282}
283
0ddf1d3a 284static int parse_password(const char *filename, char **wall) {
bbada6d7 285 _cleanup_free_ char *socket_name = NULL, *message = NULL;
1602b008 286 bool accept_cached = false, echo = false;
ec863ba6
LP
287 uint64_t not_after = 0;
288 unsigned pid = 0;
ec863ba6 289
f975e971
LP
290 const ConfigTableItem items[] = {
291 { "Ask", "Socket", config_parse_string, 0, &socket_name },
292 { "Ask", "NotAfter", config_parse_uint64, 0, &not_after },
293 { "Ask", "Message", config_parse_string, 0, &message },
294 { "Ask", "PID", config_parse_unsigned, 0, &pid },
295 { "Ask", "AcceptCached", config_parse_bool, 0, &accept_cached },
64845bdc 296 { "Ask", "Echo", config_parse_bool, 0, &echo },
1d749d04 297 {}
ec863ba6
LP
298 };
299
ec863ba6 300 int r;
ec863ba6
LP
301
302 assert(filename);
303
36f822c4
ZJS
304 r = config_parse(NULL, filename, NULL,
305 NULL,
306 config_item_table_lookup, items,
bcde742e 307 CONFIG_PARSE_RELAXED|CONFIG_PARSE_WARN, NULL);
36f822c4
ZJS
308 if (r < 0)
309 return r;
ec863ba6 310
baaa35ad
ZJS
311 if (!socket_name)
312 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
313 "Invalid password file %s", filename);
ec863ba6 314
e46eab86
ZJS
315 if (not_after > 0 && now(CLOCK_MONOTONIC) > not_after)
316 return 0;
ec863ba6 317
e46eab86
ZJS
318 if (pid > 0 && !pid_is_alive(pid))
319 return 0;
ded80335 320
ec863ba6
LP
321 if (arg_action == ACTION_LIST)
322 printf("'%s' (PID %u)\n", message, pid);
e46eab86 323
ec863ba6 324 else if (arg_action == ACTION_WALL) {
0ddf1d3a 325 char *_wall;
ec863ba6 326
0ddf1d3a
LP
327 if (asprintf(&_wall,
328 "%s%sPassword entry required for \'%s\' (PID %u).\r\n"
a1c111c2 329 "Please enter password with the systemd-tty-ask-password-agent tool:",
5cfee414 330 strempty(*wall),
0ddf1d3a 331 *wall ? "\r\n\r\n" : "",
ec863ba6 332 message,
e46eab86
ZJS
333 pid) < 0)
334 return log_oom();
ec863ba6 335
0ddf1d3a
LP
336 free(*wall);
337 *wall = _wall;
e46eab86 338
ec863ba6 339 } else {
bbada6d7 340 _cleanup_strv_free_erase_ char **passwords = NULL;
ec863ba6 341
3742095b 342 assert(IN_SET(arg_action, ACTION_QUERY, ACTION_WATCH));
ec863ba6
LP
343
344 if (access(socket_name, W_OK) < 0) {
ec863ba6
LP
345 if (arg_action == ACTION_QUERY)
346 log_info("Not querying '%s' (PID %u), lacking privileges.", message, pid);
347
e46eab86 348 return 0;
ec863ba6
LP
349 }
350
bbada6d7 351 if (arg_plymouth)
e287086b 352 r = ask_password_plymouth(message, not_after, accept_cached ? ASK_PASSWORD_ACCEPT_CACHED : 0, filename, &passwords);
bbada6d7 353 else {
00843602 354 int tty_fd = -1;
0cf84693 355
e46eab86 356 if (arg_console) {
149bc84a 357 const char *con = arg_device ?: "/dev/console";
6af62124 358
8854d795 359 tty_fd = acquire_terminal(con, ACQUIRE_TERMINAL_WAIT, USEC_INFINITY);
e46eab86 360 if (tty_fd < 0)
befd657b 361 return log_error_errno(tty_fd, "Failed to acquire %s: %m", con);
3d18b167
LP
362
363 r = reset_terminal_fd(tty_fd, true);
364 if (r < 0)
365 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
e46eab86 366 }
0cf84693 367
c2b32159
LP
368 r = ask_password_tty(tty_fd, message, NULL, not_after,
369 (echo ? ASK_PASSWORD_ECHO : 0) |
370 (arg_console ? ASK_PASSWORD_CONSOLE_COLOR : 0),
c7b7d74e 371 filename, &passwords);
e5ebf783 372
0cf84693 373 if (arg_console) {
00843602 374 tty_fd = safe_close(tty_fd);
0cf84693
LP
375 release_terminal();
376 }
1602b008 377 }
ec863ba6 378
bbada6d7
JAS
379 /* If the query went away, that's OK */
380 if (IN_SET(r, -ETIME, -ENOENT))
381 return 0;
ec863ba6 382
bbada6d7
JAS
383 if (r < 0)
384 return log_error_errno(r, "Failed to query password: %m");
ec863ba6 385
bbada6d7 386 r = send_passwords(socket_name, passwords);
00843602 387 if (r < 0)
bbada6d7 388 return log_error_errno(r, "Failed to send: %m");
ec863ba6
LP
389 }
390
e46eab86 391 return 0;
ec863ba6
LP
392}
393
0cf84693 394static int wall_tty_block(void) {
1d749d04 395 _cleanup_free_ char *p = NULL;
fc116c6a 396 dev_t devnr;
00843602 397 int fd, r;
7af53310 398
4d6d6518 399 r = get_ctty_devnr(0, &devnr);
e287086b
LP
400 if (r == -ENXIO) /* We have no controlling tty */
401 return -ENOTTY;
4d6d6518 402 if (r < 0)
00843602 403 return log_error_errno(r, "Failed to get controlling TTY: %m");
7af53310 404
2b583ce6 405 if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(devnr), minor(devnr)) < 0)
00843602 406 return log_oom();
7af53310 407
e3e2cf07
LP
408 (void) mkdir_parents_label(p, 0700);
409 (void) mkfifo(p, 0600);
7af53310
LP
410
411 fd = open(p, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
7af53310 412 if (fd < 0)
2ee4e222 413 return log_debug_errno(errno, "Failed to open %s: %m", p);
7af53310
LP
414
415 return fd;
416}
417
99f710dd 418static bool wall_tty_match(const char *path, void *userdata) {
1d749d04 419 _cleanup_free_ char *p = NULL;
00843602
LP
420 _cleanup_close_ int fd = -1;
421 struct stat st;
fc116c6a 422
1d749d04 423 if (!path_is_absolute(path))
63c372cb 424 path = strjoina("/dev/", path);
fc116c6a 425
00843602
LP
426 if (lstat(path, &st) < 0) {
427 log_debug_errno(errno, "Failed to stat %s: %m", path);
fc116c6a 428 return true;
00843602 429 }
fc116c6a 430
00843602
LP
431 if (!S_ISCHR(st.st_mode)) {
432 log_debug("%s is not a character device.", path);
fc116c6a 433 return true;
00843602 434 }
7af53310
LP
435
436 /* We use named pipes to ensure that wall messages suggesting
437 * password entry are not printed over password prompts
438 * already shown. We use the fact here that opening a pipe in
439 * non-blocking mode for write-only will succeed only if
440 * there's some writer behind it. Using pipes has the
441 * advantage that the block will automatically go away if the
442 * process dies. */
443
00843602
LP
444 if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(st.st_rdev), minor(st.st_rdev)) < 0) {
445 log_oom();
7af53310 446 return true;
00843602 447 }
7af53310
LP
448
449 fd = open(p, O_WRONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
00843602 450 if (fd < 0) {
fe4a1d0f 451 log_debug_errno(errno, "Failed to open the wall pipe: %m");
00843602
LP
452 return 1;
453 }
7af53310
LP
454
455 /* What, we managed to open the pipe? Then this tty is filtered. */
00843602 456 return 0;
7af53310
LP
457}
458
ec863ba6 459static int show_passwords(void) {
1d749d04 460 _cleanup_closedir_ DIR *d;
ec863ba6
LP
461 struct dirent *de;
462 int r = 0;
463
1d749d04
ZJS
464 d = opendir("/run/systemd/ask-password");
465 if (!d) {
ec863ba6
LP
466 if (errno == ENOENT)
467 return 0;
468
ad71eee5 469 return log_error_errno(errno, "Failed to open /run/systemd/ask-password: %m");
ec863ba6
LP
470 }
471
00843602 472 FOREACH_DIRENT_ALL(de, d, return log_error_errno(errno, "Failed to read directory: %m")) {
1d749d04 473 _cleanup_free_ char *p = NULL, *wall = NULL;
ec863ba6
LP
474 int q;
475
1a6f4df6
LP
476 /* We only support /dev on tmpfs, hence we can rely on
477 * d_type to be reliable */
478
ec863ba6
LP
479 if (de->d_type != DT_REG)
480 continue;
481
55cdd057 482 if (hidden_or_backup_file(de->d_name))
ec863ba6
LP
483 continue;
484
485 if (!startswith(de->d_name, "ask."))
486 continue;
487
1d749d04
ZJS
488 p = strappend("/run/systemd/ask-password/", de->d_name);
489 if (!p)
490 return log_oom();
ec863ba6 491
1d749d04
ZJS
492 q = parse_password(p, &wall);
493 if (q < 0 && r == 0)
ec863ba6
LP
494 r = q;
495
1d749d04 496 if (wall)
00843602 497 (void) utmp_wall(wall, NULL, NULL, wall_tty_match, NULL);
ec863ba6
LP
498 }
499
ec863ba6
LP
500 return r;
501}
502
503static int watch_passwords(void) {
b9ba604e
LP
504 enum {
505 FD_INOTIFY,
506 FD_SIGNAL,
507 _FD_MAX
508 };
509
1d749d04 510 _cleanup_close_ int notify = -1, signal_fd = -1, tty_block_fd = -1;
b92bea5d 511 struct pollfd pollfd[_FD_MAX] = {};
b9ba604e 512 sigset_t mask;
ec863ba6
LP
513 int r;
514
0cf84693 515 tty_block_fd = wall_tty_block();
7af53310 516
00843602 517 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
ec863ba6 518
1d749d04
ZJS
519 notify = inotify_init1(IN_CLOEXEC);
520 if (notify < 0)
00843602 521 return log_error_errno(errno, "Failed to allocate directory watch: %m");
ec863ba6 522
1432d2db
JS
523 if (inotify_add_watch(notify, "/run/systemd/ask-password", IN_CLOSE_WRITE|IN_MOVED_TO) < 0) {
524 if (errno == ENOSPC)
525 return log_error_errno(errno, "Failed to add /run/systemd/ask-password to directory watch: inotify watch limit reached");
526 else
527 return log_error_errno(errno, "Failed to add /run/systemd/ask-password to directory watch: %m");
528 }
ec863ba6 529
72c0a2c2
LP
530 assert_se(sigemptyset(&mask) >= 0);
531 assert_se(sigset_add_many(&mask, SIGINT, SIGTERM, -1) >= 0);
532 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) >= 0);
b9ba604e 533
1d749d04
ZJS
534 signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
535 if (signal_fd < 0)
00843602 536 return log_error_errno(errno, "Failed to allocate signal file descriptor: %m");
b9ba604e 537
b9ba604e
LP
538 pollfd[FD_INOTIFY].fd = notify;
539 pollfd[FD_INOTIFY].events = POLLIN;
540 pollfd[FD_SIGNAL].fd = signal_fd;
541 pollfd[FD_SIGNAL].events = POLLIN;
ec863ba6
LP
542
543 for (;;) {
1d749d04
ZJS
544 r = show_passwords();
545 if (r < 0)
da927ba9 546 log_error_errno(r, "Failed to show password: %m");
ec863ba6 547
b9ba604e 548 if (poll(pollfd, _FD_MAX, -1) < 0) {
ec863ba6
LP
549 if (errno == EINTR)
550 continue;
551
1d749d04 552 return -errno;
ec863ba6
LP
553 }
554
b9ba604e 555 if (pollfd[FD_INOTIFY].revents != 0)
00843602 556 (void) flush_fd(notify);
b9ba604e
LP
557
558 if (pollfd[FD_SIGNAL].revents != 0)
559 break;
ec863ba6
LP
560 }
561
1d749d04 562 return 0;
ec863ba6
LP
563}
564
37ec0fdd
LP
565static int help(void) {
566 _cleanup_free_ char *link = NULL;
567 int r;
568
569 r = terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link);
570 if (r < 0)
571 return log_oom();
572
ec863ba6
LP
573 printf("%s [OPTIONS...]\n\n"
574 "Process system password requests.\n\n"
e5ebf783 575 " -h --help Show this help\n"
c52f663b 576 " --version Show package version\n"
e5ebf783
LP
577 " --list Show pending password requests\n"
578 " --query Process pending password requests\n"
35b8ca3a
HH
579 " --watch Continuously process password requests\n"
580 " --wall Continuously forward password requests to wall\n"
0cf84693 581 " --plymouth Ask question with Plymouth instead of on TTY\n"
37ec0fdd
LP
582 " --console Ask question on /dev/console instead of current TTY\n"
583 "\nSee the %s for details.\n"
584 , program_invocation_short_name
585 , link
586 );
587
588 return 0;
ec863ba6
LP
589}
590
591static int parse_argv(int argc, char *argv[]) {
592
593 enum {
594 ARG_LIST = 0x100,
595 ARG_QUERY,
596 ARG_WATCH,
597 ARG_WALL,
0cf84693 598 ARG_PLYMOUTH,
c52f663b
LP
599 ARG_CONSOLE,
600 ARG_VERSION
ec863ba6
LP
601 };
602
603 static const struct option options[] = {
6af62124
WF
604 { "help", no_argument, NULL, 'h' },
605 { "version", no_argument, NULL, ARG_VERSION },
606 { "list", no_argument, NULL, ARG_LIST },
607 { "query", no_argument, NULL, ARG_QUERY },
608 { "watch", no_argument, NULL, ARG_WATCH },
609 { "wall", no_argument, NULL, ARG_WALL },
610 { "plymouth", no_argument, NULL, ARG_PLYMOUTH },
611 { "console", optional_argument, NULL, ARG_CONSOLE },
eb9da376 612 {}
ec863ba6
LP
613 };
614
615 int c;
616
617 assert(argc >= 0);
618 assert(argv);
619
601185b4 620 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
ec863ba6
LP
621
622 switch (c) {
623
624 case 'h':
37ec0fdd 625 return help();
ec863ba6 626
c52f663b 627 case ARG_VERSION:
3f6fd1ba 628 return version();
c52f663b 629
ec863ba6
LP
630 case ARG_LIST:
631 arg_action = ACTION_LIST;
632 break;
633
634 case ARG_QUERY:
635 arg_action = ACTION_QUERY;
636 break;
637
638 case ARG_WATCH:
639 arg_action = ACTION_WATCH;
640 break;
641
642 case ARG_WALL:
643 arg_action = ACTION_WALL;
644 break;
645
e5ebf783
LP
646 case ARG_PLYMOUTH:
647 arg_plymouth = true;
648 break;
649
0cf84693
LP
650 case ARG_CONSOLE:
651 arg_console = true;
6af62124
WF
652 if (optarg) {
653
baaa35ad
ZJS
654 if (isempty(optarg))
655 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
656 "Empty console device path is not allowed.");
6af62124
WF
657
658 arg_device = optarg;
659 }
0cf84693
LP
660 break;
661
ec863ba6
LP
662 case '?':
663 return -EINVAL;
664
665 default:
eb9da376 666 assert_not_reached("Unhandled option");
ec863ba6 667 }
ec863ba6 668
baaa35ad
ZJS
669 if (optind != argc)
670 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
671 "%s takes no arguments.", program_invocation_short_name);
ec863ba6 672
6af62124
WF
673 if (arg_plymouth || arg_console) {
674
baaa35ad
ZJS
675 if (!IN_SET(arg_action, ACTION_QUERY, ACTION_WATCH))
676 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
677 "Options --query and --watch conflict.");
6af62124 678
baaa35ad
ZJS
679 if (arg_plymouth && arg_console)
680 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
681 "Options --plymouth and --console conflict.");
6af62124
WF
682 }
683
ec863ba6
LP
684 return 1;
685}
686
6af62124
WF
687/*
688 * To be able to ask on all terminal devices of /dev/console
689 * the devices are collected. If more than one device is found,
690 * then on each of the terminals a inquiring task is forked.
691 * Every task has its own session and its own controlling terminal.
692 * If one of the tasks does handle a password, the remaining tasks
693 * will be terminated.
694 */
4c253ed1 695static int ask_on_this_console(const char *tty, pid_t *ret_pid, int argc, char *argv[]) {
6af62124
WF
696 struct sigaction sig = {
697 .sa_handler = nop_signal_handler,
698 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
699 };
4c253ed1
LP
700 pid_t pid;
701 int r;
6af62124
WF
702
703 assert_se(sigprocmask_many(SIG_UNBLOCK, NULL, SIGHUP, SIGCHLD, -1) >= 0);
704
705 assert_se(sigemptyset(&sig.sa_mask) >= 0);
706 assert_se(sigaction(SIGCHLD, &sig, NULL) >= 0);
707
708 sig.sa_handler = SIG_DFL;
709 assert_se(sigaction(SIGHUP, &sig, NULL) >= 0);
710
b6e1fff1 711 r = safe_fork("(sd-passwd)", FORK_RESET_SIGNALS|FORK_LOG, &pid);
4c253ed1 712 if (r < 0)
b6e1fff1 713 return r;
4c253ed1 714 if (r == 0) {
6af62124
WF
715 int ac;
716
717 assert_se(prctl(PR_SET_PDEATHSIG, SIGHUP) >= 0);
718
6af62124
WF
719 for (ac = 0; ac < argc; ac++) {
720 if (streq(argv[ac], "--console")) {
421eaea0 721 argv[ac] = strjoina("--console=", tty);
6af62124
WF
722 break;
723 }
724 }
725
726 assert(ac < argc);
727
728 execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, argv);
729 _exit(EXIT_FAILURE);
730 }
4c253ed1
LP
731
732 *ret_pid = pid;
6af62124
WF
733 return 0;
734}
735
736static void terminate_agents(Set *pids) {
737 struct timespec ts;
738 siginfo_t status = {};
739 sigset_t set;
740 Iterator i;
741 void *p;
742 int r, signum;
743
744 /*
745 * Request termination of the remaining processes as those
746 * are not required anymore.
747 */
748 SET_FOREACH(p, pids, i)
749 (void) kill(PTR_TO_PID(p), SIGTERM);
750
751 /*
752 * Collect the processes which have go away.
753 */
754 assert_se(sigemptyset(&set) >= 0);
755 assert_se(sigaddset(&set, SIGCHLD) >= 0);
756 timespec_store(&ts, 50 * USEC_PER_MSEC);
757
758 while (!set_isempty(pids)) {
759
760 zero(status);
761 r = waitid(P_ALL, 0, &status, WEXITED|WNOHANG);
762 if (r < 0 && errno == EINTR)
763 continue;
764
765 if (r == 0 && status.si_pid > 0) {
766 set_remove(pids, PID_TO_PTR(status.si_pid));
767 continue;
768 }
769
770 signum = sigtimedwait(&set, NULL, &ts);
771 if (signum < 0) {
772 if (errno != EAGAIN)
773 log_error_errno(errno, "sigtimedwait() failed: %m");
774 break;
775 }
776 assert(signum == SIGCHLD);
777 }
778
779 /*
780 * Kill hanging processes.
781 */
782 SET_FOREACH(p, pids, i) {
783 log_warning("Failed to terminate child %d, killing it", PTR_TO_PID(p));
784 (void) kill(PTR_TO_PID(p), SIGKILL);
785 }
786}
787
788static int ask_on_consoles(int argc, char *argv[]) {
789 _cleanup_set_free_ Set *pids = NULL;
790 _cleanup_strv_free_ char **consoles = NULL;
791 siginfo_t status = {};
792 char **tty;
793 pid_t pid;
794 int r;
795
796 r = get_kernel_consoles(&consoles);
797 if (r < 0)
798 return log_error_errno(r, "Failed to determine devices of /dev/console: %m");
799
800 pids = set_new(NULL);
801 if (!pids)
802 return log_oom();
803
804 /* Start an agent on each console. */
805 STRV_FOREACH(tty, consoles) {
806 r = ask_on_this_console(*tty, &pid, argc, argv);
807 if (r < 0)
808 return r;
809
810 if (set_put(pids, PID_TO_PTR(pid)) < 0)
811 return log_oom();
812 }
813
814 /* Wait for an agent to exit. */
815 for (;;) {
816 zero(status);
817
818 if (waitid(P_ALL, 0, &status, WEXITED) < 0) {
819 if (errno == EINTR)
820 continue;
821
822 return log_error_errno(errno, "waitid() failed: %m");
823 }
824
825 set_remove(pids, PID_TO_PTR(status.si_pid));
826 break;
827 }
828
1f0958f6 829 if (!is_clean_exit(status.si_code, status.si_status, EXIT_CLEAN_DAEMON, NULL))
6af62124
WF
830 log_error("Password agent failed with: %d", status.si_status);
831
832 terminate_agents(pids);
833 return 0;
834}
835
0420d20d 836static int run(int argc, char *argv[]) {
ec863ba6
LP
837 int r;
838
6bf3c61c 839 log_setup_service();
ec863ba6 840
4c12626c
LP
841 umask(0022);
842
1d749d04
ZJS
843 r = parse_argv(argc, argv);
844 if (r <= 0)
0420d20d 845 return r;
ec863ba6 846
6af62124
WF
847 if (arg_console && !arg_device)
848 /*
0420d20d 849 * Spawn a separate process for each console device.
6af62124 850 */
0420d20d 851 return ask_on_consoles(argc, argv);
0cf84693 852
0420d20d
ZJS
853 if (arg_device) {
854 /*
855 * Later on, a controlling terminal will be acquired,
856 * therefore the current process has to become a session
857 * leader and should not have a controlling terminal already.
858 */
859 (void) setsid();
860 (void) release_terminal();
6af62124 861 }
96707269 862
0420d20d
ZJS
863 if (IN_SET(arg_action, ACTION_WATCH, ACTION_WALL))
864 return watch_passwords();
865 else
866 return show_passwords();
ec863ba6 867}
0420d20d
ZJS
868
869DEFINE_MAIN_FUNCTION(run);