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