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