]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/spawn-polkit-agent.c
Add SPDX license identifiers to source files under the LGPL
[thirdparty/systemd.git] / src / shared / spawn-polkit-agent.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2011 Lennart Poettering
6
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #include <errno.h>
22 #include <poll.h>
23 #include <signal.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26
27 #include "fd-util.h"
28 #include "io-util.h"
29 #include "log.h"
30 #include "macro.h"
31 #include "process-util.h"
32 #include "spawn-polkit-agent.h"
33 #include "stdio-util.h"
34 #include "time-util.h"
35 #include "util.h"
36
37 #if ENABLE_POLKIT
38 static pid_t agent_pid = 0;
39
40 int polkit_agent_open(void) {
41 int r;
42 int pipe_fd[2];
43 char notify_fd[DECIMAL_STR_MAX(int) + 1];
44
45 if (agent_pid > 0)
46 return 0;
47
48 /* Clients that run as root don't need to activate/query polkit */
49 if (geteuid() == 0)
50 return 0;
51
52 /* We check STDIN here, not STDOUT, since this is about input,
53 * not output */
54 if (!isatty(STDIN_FILENO))
55 return 0;
56
57 if (pipe2(pipe_fd, 0) < 0)
58 return -errno;
59
60 xsprintf(notify_fd, "%i", pipe_fd[1]);
61
62 r = fork_agent(&agent_pid,
63 &pipe_fd[1], 1,
64 POLKIT_AGENT_BINARY_PATH,
65 POLKIT_AGENT_BINARY_PATH, "--notify-fd", notify_fd, "--fallback", NULL);
66
67 /* Close the writing side, because that's the one for the agent */
68 safe_close(pipe_fd[1]);
69
70 if (r < 0)
71 log_error_errno(r, "Failed to fork TTY ask password agent: %m");
72 else
73 /* Wait until the agent closes the fd */
74 fd_wait_for_event(pipe_fd[0], POLLHUP, USEC_INFINITY);
75
76 safe_close(pipe_fd[0]);
77
78 return r;
79 }
80
81 void polkit_agent_close(void) {
82
83 if (agent_pid <= 0)
84 return;
85
86 /* Inform agent that we are done */
87 (void) kill(agent_pid, SIGTERM);
88 (void) kill(agent_pid, SIGCONT);
89
90 (void) wait_for_terminate(agent_pid, NULL);
91 agent_pid = 0;
92 }
93
94 #else
95
96 int polkit_agent_open(void) {
97 return 0;
98 }
99
100 void polkit_agent_close(void) {
101 }
102
103 #endif