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