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