1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <signal.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6
7 #include "exec-util.h"
8 #include "log.h"
9 #include "process-util.h"
10 #include "spawn-ask-password-agent.h"
11 #include "util.h"
12
13 static pid_t agent_pid = 0;
14
ask_password_agent_open(void)15 int ask_password_agent_open(void) {
16 int r;
17
18 if (agent_pid > 0)
19 return 0;
20
21 /* We check STDIN here, not STDOUT, since this is about input,
22 * not output */
23 if (!isatty(STDIN_FILENO))
24 return 0;
25
26 if (!is_main_thread())
27 return -EPERM;
28
29 r = fork_agent("(sd-askpwagent)",
30 NULL, 0,
31 &agent_pid,
32 SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH,
33 SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, "--watch", NULL);
34 if (r < 0)
35 return log_error_errno(r, "Failed to fork TTY ask password agent: %m");
36
37 return 1;
38 }
39
ask_password_agent_close(void)40 void ask_password_agent_close(void) {
41
42 if (agent_pid <= 0)
43 return;
44
45 /* Inform agent that we are done */
46 sigterm_wait(TAKE_PID(agent_pid));
47 }
48
ask_password_agent_open_if_enabled(BusTransport transport,bool ask_password)49 int ask_password_agent_open_if_enabled(BusTransport transport, bool ask_password) {
50
51 /* Open the ask password agent as a child process if necessary */
52
53 if (transport != BUS_TRANSPORT_LOCAL)
54 return 0;
55
56 if (!ask_password)
57 return 0;
58
59 return ask_password_agent_open();
60 }
61