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