1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <poll.h>
5 #include <signal.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8
9 #include "exec-util.h"
10 #include "fd-util.h"
11 #include "io-util.h"
12 #include "log.h"
13 #include "macro.h"
14 #include "process-util.h"
15 #include "spawn-polkit-agent.h"
16 #include "stdio-util.h"
17 #include "time-util.h"
18 #include "util.h"
19
20 #if ENABLE_POLKIT
21 static pid_t agent_pid = 0;
22
polkit_agent_open(void)23 int polkit_agent_open(void) {
24 char notify_fd[DECIMAL_STR_MAX(int) + 1];
25 int pipe_fd[2], r;
26
27 if (agent_pid > 0)
28 return 0;
29
30 /* Clients that run as root don't need to activate/query polkit */
31 if (geteuid() == 0)
32 return 0;
33
34 /* We check STDIN here, not STDOUT, since this is about input, not output */
35 if (!isatty(STDIN_FILENO))
36 return 0;
37
38 if (!is_main_thread())
39 return -EPERM;
40
41 if (pipe2(pipe_fd, 0) < 0)
42 return -errno;
43
44 xsprintf(notify_fd, "%i", pipe_fd[1]);
45
46 r = fork_agent("(polkit-agent)",
47 &pipe_fd[1], 1,
48 &agent_pid,
49 POLKIT_AGENT_BINARY_PATH,
50 POLKIT_AGENT_BINARY_PATH, "--notify-fd", notify_fd, "--fallback", NULL);
51
52 /* Close the writing side, because that's the one for the agent */
53 safe_close(pipe_fd[1]);
54
55 if (r < 0)
56 log_error_errno(r, "Failed to fork TTY ask password agent: %m");
57 else
58 /* Wait until the agent closes the fd */
59 fd_wait_for_event(pipe_fd[0], POLLHUP, USEC_INFINITY);
60
61 safe_close(pipe_fd[0]);
62
63 return r;
64 }
65
polkit_agent_close(void)66 void polkit_agent_close(void) {
67
68 if (agent_pid <= 0)
69 return;
70
71 /* Inform agent that we are done */
72 sigterm_wait(TAKE_PID(agent_pid));
73 }
74
75 #else
76
polkit_agent_open(void)77 int polkit_agent_open(void) {
78 return 0;
79 }
80
polkit_agent_close(void)81 void polkit_agent_close(void) {
82 }
83
84 #endif
85
polkit_agent_open_if_enabled(BusTransport transport,bool ask_password)86 int polkit_agent_open_if_enabled(BusTransport transport, bool ask_password) {
87
88 /* Open the polkit agent as a child process if necessary */
89
90 if (transport != BUS_TRANSPORT_LOCAL)
91 return 0;
92
93 if (!ask_password)
94 return 0;
95
96 return polkit_agent_open();
97 }
98