]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/tty-ask-password-agent/tty-ask-password-agent.c
log: introduce new helper call log_setup_service()
[thirdparty/systemd.git] / src / tty-ask-password-agent / tty-ask-password-agent.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright © 2015 Werner Fink
4 ***/
5
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <getopt.h>
9 #include <poll.h>
10 #include <signal.h>
11 #include <stdbool.h>
12 #include <stddef.h>
13 #include <string.h>
14 #include <sys/inotify.h>
15 #include <sys/prctl.h>
16 #include <sys/signalfd.h>
17 #include <sys/socket.h>
18 #include <sys/wait.h>
19 #include <sys/un.h>
20 #include <unistd.h>
21
22 #include "alloc-util.h"
23 #include "ask-password-api.h"
24 #include "conf-parser.h"
25 #include "def.h"
26 #include "dirent-util.h"
27 #include "exit-status.h"
28 #include "fd-util.h"
29 #include "fileio.h"
30 #include "hashmap.h"
31 #include "io-util.h"
32 #include "macro.h"
33 #include "main-func.h"
34 #include "mkdir.h"
35 #include "path-util.h"
36 #include "process-util.h"
37 #include "signal-util.h"
38 #include "socket-util.h"
39 #include "string-util.h"
40 #include "strv.h"
41 #include "terminal-util.h"
42 #include "util.h"
43 #include "utmp-wtmp.h"
44
45 static enum {
46 ACTION_LIST,
47 ACTION_QUERY,
48 ACTION_WATCH,
49 ACTION_WALL
50 } arg_action = ACTION_QUERY;
51
52 static bool arg_plymouth = false;
53 static bool arg_console = false;
54 static const char *arg_device = NULL;
55
56 static int ask_password_plymouth(
57 const char *message,
58 usec_t until,
59 AskPasswordFlags flags,
60 const char *flag_file,
61 char ***ret) {
62
63 static const union sockaddr_union sa = PLYMOUTH_SOCKET;
64 _cleanup_close_ int fd = -1, notify = -1;
65 _cleanup_free_ char *packet = NULL;
66 ssize_t k;
67 int r, n;
68 struct pollfd pollfd[2] = {};
69 char buffer[LINE_MAX];
70 size_t p = 0;
71 enum {
72 POLL_SOCKET,
73 POLL_INOTIFY
74 };
75
76 assert(ret);
77
78 if (flag_file) {
79 notify = inotify_init1(IN_CLOEXEC|IN_NONBLOCK);
80 if (notify < 0)
81 return -errno;
82
83 r = inotify_add_watch(notify, flag_file, IN_ATTRIB); /* for the link count */
84 if (r < 0)
85 return -errno;
86 }
87
88 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
89 if (fd < 0)
90 return -errno;
91
92 r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
93 if (r < 0)
94 return -errno;
95
96 if (flags & ASK_PASSWORD_ACCEPT_CACHED) {
97 packet = strdup("c");
98 n = 1;
99 } else if (asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n) < 0)
100 packet = NULL;
101 if (!packet)
102 return -ENOMEM;
103
104 r = loop_write(fd, packet, n + 1, true);
105 if (r < 0)
106 return r;
107
108 pollfd[POLL_SOCKET].fd = fd;
109 pollfd[POLL_SOCKET].events = POLLIN;
110 pollfd[POLL_INOTIFY].fd = notify;
111 pollfd[POLL_INOTIFY].events = POLLIN;
112
113 for (;;) {
114 int sleep_for = -1, j;
115
116 if (until > 0) {
117 usec_t y;
118
119 y = now(CLOCK_MONOTONIC);
120
121 if (y > until) {
122 r = -ETIME;
123 goto finish;
124 }
125
126 sleep_for = (int) ((until - y) / USEC_PER_MSEC);
127 }
128
129 if (flag_file && access(flag_file, F_OK) < 0) {
130 r = -errno;
131 goto finish;
132 }
133
134 j = poll(pollfd, notify >= 0 ? 2 : 1, sleep_for);
135 if (j < 0) {
136 if (errno == EINTR)
137 continue;
138
139 r = -errno;
140 goto finish;
141 } else if (j == 0) {
142 r = -ETIME;
143 goto finish;
144 }
145
146 if (notify >= 0 && pollfd[POLL_INOTIFY].revents != 0)
147 (void) flush_fd(notify);
148
149 if (pollfd[POLL_SOCKET].revents == 0)
150 continue;
151
152 k = read(fd, buffer + p, sizeof(buffer) - p);
153 if (k < 0) {
154 if (IN_SET(errno, EINTR, EAGAIN))
155 continue;
156
157 r = -errno;
158 goto finish;
159 } else if (k == 0) {
160 r = -EIO;
161 goto finish;
162 }
163
164 p += k;
165
166 if (p < 1)
167 continue;
168
169 if (buffer[0] == 5) {
170
171 if (flags & ASK_PASSWORD_ACCEPT_CACHED) {
172 /* Hmm, first try with cached
173 * passwords failed, so let's retry
174 * with a normal password request */
175 packet = mfree(packet);
176
177 if (asprintf(&packet, "*\002%c%s%n", (int) (strlen(message) + 1), message, &n) < 0) {
178 r = -ENOMEM;
179 goto finish;
180 }
181
182 r = loop_write(fd, packet, n+1, true);
183 if (r < 0)
184 goto finish;
185
186 flags &= ~ASK_PASSWORD_ACCEPT_CACHED;
187 p = 0;
188 continue;
189 }
190
191 /* No password, because UI not shown */
192 r = -ENOENT;
193 goto finish;
194
195 } else if (IN_SET(buffer[0], 2, 9)) {
196 uint32_t size;
197 char **l;
198
199 /* One or more answers */
200 if (p < 5)
201 continue;
202
203 memcpy(&size, buffer+1, sizeof(size));
204 size = le32toh(size);
205 if (size + 5 > sizeof(buffer)) {
206 r = -EIO;
207 goto finish;
208 }
209
210 if (p-5 < size)
211 continue;
212
213 l = strv_parse_nulstr(buffer + 5, size);
214 if (!l) {
215 r = -ENOMEM;
216 goto finish;
217 }
218
219 *ret = l;
220 break;
221
222 } else {
223 /* Unknown packet */
224 r = -EIO;
225 goto finish;
226 }
227 }
228
229 r = 0;
230
231 finish:
232 explicit_bzero_safe(buffer, sizeof(buffer));
233 return r;
234 }
235
236 static int send_passwords(const char *socket_name, char **passwords) {
237 _cleanup_free_ char *packet = NULL;
238 _cleanup_close_ int socket_fd = -1;
239 union sockaddr_union sa = {};
240 size_t packet_length = 1;
241 char **p, *d;
242 ssize_t n;
243 int r, salen;
244
245 assert(socket_name);
246
247 salen = sockaddr_un_set_path(&sa.un, socket_name);
248 if (salen < 0)
249 return salen;
250
251 STRV_FOREACH(p, passwords)
252 packet_length += strlen(*p) + 1;
253
254 packet = new(char, packet_length);
255 if (!packet)
256 return -ENOMEM;
257
258 packet[0] = '+';
259
260 d = packet + 1;
261 STRV_FOREACH(p, passwords)
262 d = stpcpy(d, *p) + 1;
263
264 socket_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
265 if (socket_fd < 0) {
266 r = log_debug_errno(errno, "socket(): %m");
267 goto finish;
268 }
269
270 n = sendto(socket_fd, packet, packet_length, MSG_NOSIGNAL, &sa.sa, salen);
271 if (n < 0) {
272 r = log_debug_errno(errno, "sendto(): %m");
273 goto finish;
274 }
275
276 r = (int) n;
277
278 finish:
279 explicit_bzero_safe(packet, packet_length);
280 return r;
281 }
282
283 static int parse_password(const char *filename, char **wall) {
284 _cleanup_free_ char *socket_name = NULL, *message = NULL;
285 bool accept_cached = false, echo = false;
286 uint64_t not_after = 0;
287 unsigned pid = 0;
288
289 const ConfigTableItem items[] = {
290 { "Ask", "Socket", config_parse_string, 0, &socket_name },
291 { "Ask", "NotAfter", config_parse_uint64, 0, &not_after },
292 { "Ask", "Message", config_parse_string, 0, &message },
293 { "Ask", "PID", config_parse_unsigned, 0, &pid },
294 { "Ask", "AcceptCached", config_parse_bool, 0, &accept_cached },
295 { "Ask", "Echo", config_parse_bool, 0, &echo },
296 {}
297 };
298
299 int r;
300
301 assert(filename);
302
303 r = config_parse(NULL, filename, NULL,
304 NULL,
305 config_item_table_lookup, items,
306 CONFIG_PARSE_RELAXED|CONFIG_PARSE_WARN, NULL);
307 if (r < 0)
308 return r;
309
310 if (!socket_name) {
311 log_error("Invalid password file %s", filename);
312 return -EBADMSG;
313 }
314
315 if (not_after > 0 && now(CLOCK_MONOTONIC) > not_after)
316 return 0;
317
318 if (pid > 0 && !pid_is_alive(pid))
319 return 0;
320
321 if (arg_action == ACTION_LIST)
322 printf("'%s' (PID %u)\n", message, pid);
323
324 else if (arg_action == ACTION_WALL) {
325 char *_wall;
326
327 if (asprintf(&_wall,
328 "%s%sPassword entry required for \'%s\' (PID %u).\r\n"
329 "Please enter password with the systemd-tty-ask-password-agent tool:",
330 strempty(*wall),
331 *wall ? "\r\n\r\n" : "",
332 message,
333 pid) < 0)
334 return log_oom();
335
336 free(*wall);
337 *wall = _wall;
338
339 } else {
340 _cleanup_strv_free_erase_ char **passwords = NULL;
341
342 assert(IN_SET(arg_action, ACTION_QUERY, ACTION_WATCH));
343
344 if (access(socket_name, W_OK) < 0) {
345 if (arg_action == ACTION_QUERY)
346 log_info("Not querying '%s' (PID %u), lacking privileges.", message, pid);
347
348 return 0;
349 }
350
351 if (arg_plymouth)
352 r = ask_password_plymouth(message, not_after, accept_cached ? ASK_PASSWORD_ACCEPT_CACHED : 0, filename, &passwords);
353 else {
354 int tty_fd = -1;
355
356 if (arg_console) {
357 const char *con = arg_device ?: "/dev/console";
358
359 tty_fd = acquire_terminal(con, ACQUIRE_TERMINAL_WAIT, USEC_INFINITY);
360 if (tty_fd < 0)
361 return log_error_errno(tty_fd, "Failed to acquire %s: %m", con);
362
363 r = reset_terminal_fd(tty_fd, true);
364 if (r < 0)
365 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
366 }
367
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),
371 filename, &passwords);
372
373 if (arg_console) {
374 tty_fd = safe_close(tty_fd);
375 release_terminal();
376 }
377 }
378
379 /* If the query went away, that's OK */
380 if (IN_SET(r, -ETIME, -ENOENT))
381 return 0;
382
383 if (r < 0)
384 return log_error_errno(r, "Failed to query password: %m");
385
386 r = send_passwords(socket_name, passwords);
387 if (r < 0)
388 return log_error_errno(r, "Failed to send: %m");
389 }
390
391 return 0;
392 }
393
394 static int wall_tty_block(void) {
395 _cleanup_free_ char *p = NULL;
396 dev_t devnr;
397 int fd, r;
398
399 r = get_ctty_devnr(0, &devnr);
400 if (r == -ENXIO) /* We have no controlling tty */
401 return -ENOTTY;
402 if (r < 0)
403 return log_error_errno(r, "Failed to get controlling TTY: %m");
404
405 if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(devnr), minor(devnr)) < 0)
406 return log_oom();
407
408 (void) mkdir_parents_label(p, 0700);
409 (void) mkfifo(p, 0600);
410
411 fd = open(p, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
412 if (fd < 0)
413 return log_debug_errno(errno, "Failed to open %s: %m", p);
414
415 return fd;
416 }
417
418 static bool wall_tty_match(const char *path, void *userdata) {
419 _cleanup_free_ char *p = NULL;
420 _cleanup_close_ int fd = -1;
421 struct stat st;
422
423 if (!path_is_absolute(path))
424 path = strjoina("/dev/", path);
425
426 if (lstat(path, &st) < 0) {
427 log_debug_errno(errno, "Failed to stat %s: %m", path);
428 return true;
429 }
430
431 if (!S_ISCHR(st.st_mode)) {
432 log_debug("%s is not a character device.", path);
433 return true;
434 }
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
444 if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(st.st_rdev), minor(st.st_rdev)) < 0) {
445 log_oom();
446 return true;
447 }
448
449 fd = open(p, O_WRONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
450 if (fd < 0) {
451 log_debug_errno(errno, "Failed to open the wall pipe: %m");
452 return 1;
453 }
454
455 /* What, we managed to open the pipe? Then this tty is filtered. */
456 return 0;
457 }
458
459 static int show_passwords(void) {
460 _cleanup_closedir_ DIR *d;
461 struct dirent *de;
462 int r = 0;
463
464 d = opendir("/run/systemd/ask-password");
465 if (!d) {
466 if (errno == ENOENT)
467 return 0;
468
469 return log_error_errno(errno, "Failed to open /run/systemd/ask-password: %m");
470 }
471
472 FOREACH_DIRENT_ALL(de, d, return log_error_errno(errno, "Failed to read directory: %m")) {
473 _cleanup_free_ char *p = NULL, *wall = NULL;
474 int q;
475
476 /* We only support /dev on tmpfs, hence we can rely on
477 * d_type to be reliable */
478
479 if (de->d_type != DT_REG)
480 continue;
481
482 if (hidden_or_backup_file(de->d_name))
483 continue;
484
485 if (!startswith(de->d_name, "ask."))
486 continue;
487
488 p = strappend("/run/systemd/ask-password/", de->d_name);
489 if (!p)
490 return log_oom();
491
492 q = parse_password(p, &wall);
493 if (q < 0 && r == 0)
494 r = q;
495
496 if (wall)
497 (void) utmp_wall(wall, NULL, NULL, wall_tty_match, NULL);
498 }
499
500 return r;
501 }
502
503 static int watch_passwords(void) {
504 enum {
505 FD_INOTIFY,
506 FD_SIGNAL,
507 _FD_MAX
508 };
509
510 _cleanup_close_ int notify = -1, signal_fd = -1, tty_block_fd = -1;
511 struct pollfd pollfd[_FD_MAX] = {};
512 sigset_t mask;
513 int r;
514
515 tty_block_fd = wall_tty_block();
516
517 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
518
519 notify = inotify_init1(IN_CLOEXEC);
520 if (notify < 0)
521 return log_error_errno(errno, "Failed to allocate directory watch: %m");
522
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 }
529
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);
533
534 signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
535 if (signal_fd < 0)
536 return log_error_errno(errno, "Failed to allocate signal file descriptor: %m");
537
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;
542
543 for (;;) {
544 r = show_passwords();
545 if (r < 0)
546 log_error_errno(r, "Failed to show password: %m");
547
548 if (poll(pollfd, _FD_MAX, -1) < 0) {
549 if (errno == EINTR)
550 continue;
551
552 return -errno;
553 }
554
555 if (pollfd[FD_INOTIFY].revents != 0)
556 (void) flush_fd(notify);
557
558 if (pollfd[FD_SIGNAL].revents != 0)
559 break;
560 }
561
562 return 0;
563 }
564
565 static 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
573 printf("%s [OPTIONS...]\n\n"
574 "Process system password requests.\n\n"
575 " -h --help Show this help\n"
576 " --version Show package version\n"
577 " --list Show pending password requests\n"
578 " --query Process pending password requests\n"
579 " --watch Continuously process password requests\n"
580 " --wall Continuously forward password requests to wall\n"
581 " --plymouth Ask question with Plymouth instead of on TTY\n"
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;
589 }
590
591 static int parse_argv(int argc, char *argv[]) {
592
593 enum {
594 ARG_LIST = 0x100,
595 ARG_QUERY,
596 ARG_WATCH,
597 ARG_WALL,
598 ARG_PLYMOUTH,
599 ARG_CONSOLE,
600 ARG_VERSION
601 };
602
603 static const struct option options[] = {
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 },
612 {}
613 };
614
615 int c;
616
617 assert(argc >= 0);
618 assert(argv);
619
620 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
621
622 switch (c) {
623
624 case 'h':
625 return help();
626
627 case ARG_VERSION:
628 return version();
629
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
646 case ARG_PLYMOUTH:
647 arg_plymouth = true;
648 break;
649
650 case ARG_CONSOLE:
651 arg_console = true;
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 }
661 break;
662
663 case '?':
664 return -EINVAL;
665
666 default:
667 assert_not_reached("Unhandled option");
668 }
669
670 if (optind != argc) {
671 log_error("%s takes no arguments.", program_invocation_short_name);
672 return -EINVAL;
673 }
674
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
688 return 1;
689 }
690
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 */
699 static int ask_on_this_console(const char *tty, pid_t *ret_pid, int argc, char *argv[]) {
700 struct sigaction sig = {
701 .sa_handler = nop_signal_handler,
702 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
703 };
704 pid_t pid;
705 int r;
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
715 r = safe_fork("(sd-passwd)", FORK_RESET_SIGNALS|FORK_LOG, &pid);
716 if (r < 0)
717 return r;
718 if (r == 0) {
719 int ac;
720
721 assert_se(prctl(PR_SET_PDEATHSIG, SIGHUP) >= 0);
722
723 for (ac = 0; ac < argc; ac++) {
724 if (streq(argv[ac], "--console")) {
725 argv[ac] = strjoina("--console=", tty);
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 }
735
736 *ret_pid = pid;
737 return 0;
738 }
739
740 static 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
792 static 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
833 if (!is_clean_exit(status.si_code, status.si_status, EXIT_CLEAN_DAEMON, NULL))
834 log_error("Password agent failed with: %d", status.si_status);
835
836 terminate_agents(pids);
837 return 0;
838 }
839
840 static int run(int argc, char *argv[]) {
841 int r;
842
843 log_setup_service();
844
845 umask(0022);
846
847 r = parse_argv(argc, argv);
848 if (r <= 0)
849 return r;
850
851 if (arg_console && !arg_device)
852 /*
853 * Spawn a separate process for each console device.
854 */
855 return ask_on_consoles(argc, argv);
856
857 if (arg_device) {
858 /*
859 * Later on, a controlling terminal will be acquired,
860 * therefore the current process has to become a session
861 * leader and should not have a controlling terminal already.
862 */
863 (void) setsid();
864 (void) release_terminal();
865 }
866
867 if (IN_SET(arg_action, ACTION_WATCH, ACTION_WALL))
868 return watch_passwords();
869 else
870 return show_passwords();
871 }
872
873 DEFINE_MAIN_FUNCTION(run);