blob: 9eb023bb0ec684ec3db902e20536d0142934cd2a [file] [log] [blame]
Narayan Kamatha5ace892017-01-06 15:10:02 +00001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "IptablesRestoreController.h"
18
19#include <poll.h>
20#include <signal.h>
21#include <sys/wait.h>
22#include <unistd.h>
23
Lorenzo Colitti173da322017-02-05 01:56:40 +090024#define LOG_TAG "IptablesRestoreController"
Narayan Kamatha5ace892017-01-06 15:10:02 +000025#include <android-base/logging.h>
26#include <android-base/file.h>
27
28#include "Controllers.h"
29
30constexpr char IPTABLES_RESTORE_PATH[] = "/system/bin/iptables-restore";
31constexpr char IP6TABLES_RESTORE_PATH[] = "/system/bin/ip6tables-restore";
32
33constexpr char PING[] = "#PING\n";
34
35constexpr size_t PING_SIZE = sizeof(PING) - 1;
36
37// TODO: This mirrors &gCtls.iptablesRestoreCtrl in production and is duplicated
38// here to aid testing. It allows us to unit-test IptablesRestoreController without
39// needing to construct a fully fledged Controllers object.
40/* static */ IptablesRestoreController* sInstance = nullptr;
41
42class IptablesProcess {
43public:
44 IptablesProcess(pid_t pid, int stdIn, int stdOut, int stdErr) :
45 pid(pid),
46 stdIn(stdIn),
47 processTerminated(false) {
48
49 pollFds[STDOUT_IDX] = { .fd = stdOut, .events = POLLIN };
50 pollFds[STDERR_IDX] = { .fd = stdErr, .events = POLLIN };
51 }
52
53 ~IptablesProcess() {
54 close(stdIn);
55 close(pollFds[STDOUT_IDX].fd);
56 close(pollFds[STDERR_IDX].fd);
57 }
58
Lorenzo Colitti173da322017-02-05 01:56:40 +090059 bool outputReady() {
60 struct pollfd pollfd = { .fd = stdIn, .events = POLLOUT };
61 int ret = poll(&pollfd, 1, 0);
62 if (ret == -1) {
63 ALOGE("outputReady poll failed: %s", strerror(errno));
64 return false;
65 }
66 return (ret == 1) && !(pollfd.revents & POLLERR);
67 }
68
69 void stop() {
70 if (processTerminated) return;
71
72 // This can be called by drainAndWaitForAck (after a POLLHUP) or by sendCommand (if the
73 // process was killed by something else on the system). In both cases, it's safe to send the
74 // PID a SIGTERM, because the PID continues to exist until its parent (i.e., us) calls
75 // waitpid on it, so there's no risk that the PID is reused.
76 int err = kill(pid, SIGTERM);
77 if (err) {
78 err = errno;
79 }
80
81 if (err == ESRCH) {
82 // This means that someone else inside netd but outside this class called waitpid(),
83 // which is a programming error. There's no point in calling waitpid() here since we
84 // know that the process is gone.
85 ALOGE("iptables child process %d unexpectedly disappeared", pid);
86 processTerminated = true;
87 return;
88 }
89
90 if (err) {
91 ALOGE("Error killing iptables child process %d: %s", pid, strerror(err));
92 }
93
Lorenzo Colitti25091422017-02-03 16:05:28 +090094 int status;
95 if (waitpid(pid, &status, 0) == -1) {
Lorenzo Colitti173da322017-02-05 01:56:40 +090096 ALOGE("Error waiting for iptables child process %d: %s", pid, strerror(errno));
Lorenzo Colitti25091422017-02-03 16:05:28 +090097 } else {
98 ALOGW("iptables-restore process %d terminated status=%d", pid, status);
Lorenzo Colitti173da322017-02-05 01:56:40 +090099 }
100
101 processTerminated = true;
102 }
103
Narayan Kamatha5ace892017-01-06 15:10:02 +0000104 const pid_t pid;
105 const int stdIn;
106
107 struct pollfd pollFds[2];
108 std::string errBuf;
109
Lorenzo Colitti173da322017-02-05 01:56:40 +0900110 std::atomic_bool processTerminated;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000111
112 static constexpr size_t STDOUT_IDX = 0;
113 static constexpr size_t STDERR_IDX = 1;
114};
115
116IptablesRestoreController::IptablesRestoreController() :
117 mIpRestore(nullptr),
118 mIp6Restore(nullptr) {
119}
120
121IptablesRestoreController::~IptablesRestoreController() {
122}
123
124/* static */
125IptablesProcess* IptablesRestoreController::forkAndExec(const IptablesProcessType type) {
126 const char* const cmd = (type == IPTABLES_PROCESS) ?
127 IPTABLES_RESTORE_PATH : IP6TABLES_RESTORE_PATH;
128
129 // Create the pipes we'll use for communication with the child
130 // process. One each for the child's in, out and err files.
131 int stdin_pipe[2];
132 int stdout_pipe[2];
133 int stderr_pipe[2];
134
135 if (pipe2(stdin_pipe, 0) == -1 ||
Lorenzo Colitticd283772017-01-31 19:00:49 +0900136 pipe2(stdout_pipe, O_NONBLOCK) == -1 ||
137 pipe2(stderr_pipe, O_NONBLOCK) == -1) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000138
Lorenzo Colitti25091422017-02-03 16:05:28 +0900139 ALOGE("pipe2() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000140 return nullptr;
141 }
142
143 pid_t child_pid = fork();
144 if (child_pid == 0) {
145 // The child process. Reads from stdin, writes to stderr and stdout.
146
147 // stdin_pipe[1] : The write end of the stdin pipe.
148 // stdout_pipe[0] : The read end of the stdout pipe.
149 // stderr_pipe[0] : The read end of the stderr pipe.
150 if (close(stdin_pipe[1]) == -1 ||
151 close(stdout_pipe[0]) == -1 ||
152 close(stderr_pipe[0]) == -1) {
153
Lorenzo Colitti25091422017-02-03 16:05:28 +0900154 ALOGW("close() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000155 }
156
157 // stdin_pipe[0] : The read end of the stdin pipe.
158 // stdout_pipe[1] : The write end of the stdout pipe.
159 // stderr_pipe[1] : The write end of the stderr pipe.
160 if (dup2(stdin_pipe[0], 0) == -1 ||
161 dup2(stdout_pipe[1], 1) == -1 ||
162 dup2(stderr_pipe[1], 2) == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900163 ALOGE("dup2() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000164 abort();
165 }
166
167 if (execl(cmd,
168 cmd,
169 "--noflush", // Don't flush the whole table.
170 "-w", // Wait instead of failing if the lock is held.
171 "-v", // Verbose mode, to make sure our ping is echoed
172 // back to us.
173 nullptr) == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900174 ALOGE("execl(%s, ...) failed: %s", cmd, strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000175 abort();
176 }
177
178 // This statement is unreachable. We abort() upon error, and execl
179 // if everything goes well.
180 return nullptr;
181 }
182
183 // The parent process. Writes to stdout and stderr and reads from stdin.
184 if (child_pid == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900185 ALOGE("fork() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000186 return nullptr;
187 }
188
189 // stdin_pipe[0] : The read end of the stdin pipe.
190 // stdout_pipe[1] : The write end of the stdout pipe.
191 // stderr_pipe[1] : The write end of the stderr pipe.
192 if (close(stdin_pipe[0]) == -1 ||
193 close(stdout_pipe[1]) == -1 ||
194 close(stderr_pipe[1]) == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900195 ALOGW("close() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000196 }
197
198 return new IptablesProcess(child_pid, stdin_pipe[1], stdout_pipe[0], stderr_pipe[0]);
199}
200
Narayan Kamatha5ace892017-01-06 15:10:02 +0000201// TODO: Return -errno on failure instead of -1.
202// TODO: Maybe we should keep a rotating buffer of the last N commands
203// so that they can be dumped on dumpsys.
204int IptablesRestoreController::sendCommand(const IptablesProcessType type,
Lorenzo Colitticd283772017-01-31 19:00:49 +0900205 const std::string& command,
206 std::string *output) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000207 std::unique_ptr<IptablesProcess> *process =
208 (type == IPTABLES_PROCESS) ? &mIpRestore : &mIp6Restore;
209
Lorenzo Colitti173da322017-02-05 01:56:40 +0900210
Narayan Kamatha5ace892017-01-06 15:10:02 +0000211 // We might need to fork a new process if we haven't forked one yet, or
212 // if the forked process terminated.
213 //
214 // NOTE: For a given command, this is the last point at which we try to
215 // recover from a child death. If the child dies at some later point during
216 // the execution of this method, we will receive an EPIPE and return an
217 // error. The command will then need to be retried at a higher level.
Lorenzo Colitti173da322017-02-05 01:56:40 +0900218 IptablesProcess *existingProcess = process->get();
219 if (existingProcess != nullptr && !existingProcess->outputReady()) {
220 existingProcess->stop();
221 existingProcess = nullptr;
222 }
223
224 if (existingProcess == nullptr) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000225 // Fork a new iptables[6]-restore process.
226 IptablesProcess *newProcess = IptablesRestoreController::forkAndExec(type);
227 if (newProcess == nullptr) {
228 LOG(ERROR) << "Unable to fork ip[6]tables-restore, type: " << type;
229 return -1;
230 }
231
232 process->reset(newProcess);
233 }
234
Lorenzo Colitti20b128b2017-02-10 11:01:08 +0900235 if (!android::base::WriteFully((*process)->stdIn, command.data(), command.length())) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900236 ALOGE("Unable to send command: %s", strerror(errno));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900237 return -1;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000238 }
239
240 if (!android::base::WriteFully((*process)->stdIn, PING, PING_SIZE)) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900241 ALOGE("Unable to send ping command: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000242 return -1;
243 }
244
Lorenzo Colitti20b128b2017-02-10 11:01:08 +0900245 if (!drainAndWaitForAck(*process, command, output)) {
Lorenzo Colitti173da322017-02-05 01:56:40 +0900246 // drainAndWaitForAck has already logged an error.
Narayan Kamatha5ace892017-01-06 15:10:02 +0000247 return -1;
248 }
249
250 return 0;
251}
252
Narayan Kamatha5ace892017-01-06 15:10:02 +0000253void IptablesRestoreController::maybeLogStderr(const std::unique_ptr<IptablesProcess> &process,
Lorenzo Colitti25091422017-02-03 16:05:28 +0900254 const std::string& command) {
255 if (process->errBuf.empty()) {
256 return;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000257 }
258
Lorenzo Colitti25091422017-02-03 16:05:28 +0900259 ALOGE("iptables error:\n"
260 "------- COMMAND -------\n"
261 "%s\n"
262 "------- ERROR -------\n"
263 "%s"
264 "----------------------\n",
265 command.c_str(), process->errBuf.c_str());
266 process->errBuf.clear();
Narayan Kamatha5ace892017-01-06 15:10:02 +0000267}
268
269// The maximum number of times we poll(2) for a response on our set of polled
270// fds. Chosen so that the overall timeout is 1s.
271static constexpr int MAX_RETRIES = 10;
272
273// The timeout (in millis) for each call to poll. The maximum wait is
274// |POLL_TIMEOUT_MS * MAX_RETRIES|. Chosen so that the overall timeout is 1s.
275static constexpr int POLL_TIMEOUT_MS = 100;
276
277/* static */
Lorenzo Colitticd283772017-01-31 19:00:49 +0900278bool IptablesRestoreController::drainAndWaitForAck(const std::unique_ptr<IptablesProcess> &process,
Lorenzo Colitti25091422017-02-03 16:05:28 +0900279 const std::string& command,
Lorenzo Colitticd283772017-01-31 19:00:49 +0900280 std::string *output) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000281 bool receivedAck = false;
282 int timeout = 0;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000283 while (!receivedAck && (timeout++ < MAX_RETRIES)) {
284 int numEvents = TEMP_FAILURE_RETRY(
285 poll(process->pollFds, ARRAY_SIZE(process->pollFds), POLL_TIMEOUT_MS));
286 if (numEvents == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900287 ALOGE("Poll failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000288 return false;
289 }
290
291 // We've timed out, which means something has gone wrong - we know that stdout should have
Lorenzo Colitti173da322017-02-05 01:56:40 +0900292 // become available to read with the ACK message, or that stderr should have been available
293 // to read with an error message.
Narayan Kamatha5ace892017-01-06 15:10:02 +0000294 if (numEvents == 0) {
295 continue;
296 }
297
Lorenzo Colitticd283772017-01-31 19:00:49 +0900298 char buffer[PIPE_BUF];
Narayan Kamatha5ace892017-01-06 15:10:02 +0000299 for (size_t i = 0; i < ARRAY_SIZE(process->pollFds); ++i) {
300 const struct pollfd &pollfd = process->pollFds[i];
301 if (pollfd.revents & POLLIN) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900302 ssize_t size;
303 do {
304 size = TEMP_FAILURE_RETRY(read(pollfd.fd, buffer, sizeof(buffer)));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000305
Lorenzo Colitticd283772017-01-31 19:00:49 +0900306 if (size == -1) {
307 if (errno != EAGAIN) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900308 ALOGE("Unable to read from descriptor: %s", strerror(errno));
Lorenzo Colitticd283772017-01-31 19:00:49 +0900309 }
310 break;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000311 }
Lorenzo Colitticd283772017-01-31 19:00:49 +0900312
313 if (i == IptablesProcess::STDOUT_IDX) {
314 // i == STDOUT_IDX: accumulate stdout into *output, and look
315 // for the ping response.
316 output->append(buffer, size);
317 size_t pos = output->find(PING);
318 if (pos != std::string::npos) {
319 if (output->size() > pos + PING_SIZE) {
320 size_t extra = output->size() - (pos + PING_SIZE);
321 ALOGW("%zd extra characters after iptables response: '%s...'",
322 extra, output->substr(pos + PING_SIZE, 128).c_str());
323 }
324 output->resize(pos);
325 receivedAck = true;
326 }
327 } else {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900328 // i == STDERR_IDX: accumulate stderr into errBuf.
329 process->errBuf.append(buffer, size);
Lorenzo Colitticd283772017-01-31 19:00:49 +0900330 }
331 } while (size > 0);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000332 }
Lorenzo Colitti173da322017-02-05 01:56:40 +0900333 if (pollfd.revents & POLLHUP) {
334 // The pipe was closed. This likely means the subprocess is exiting, since
335 // iptables-restore only closes stdin on error.
336 process->stop();
337 break;
338 }
Narayan Kamatha5ace892017-01-06 15:10:02 +0000339 }
340 }
341
Lorenzo Colitti25091422017-02-03 16:05:28 +0900342 if (!receivedAck && !process->processTerminated) {
343 ALOGE("Timed out waiting for response from iptables process %d", process->pid);
Lorenzo Colitti173da322017-02-05 01:56:40 +0900344 }
345
Lorenzo Colitti25091422017-02-03 16:05:28 +0900346 maybeLogStderr(process, command);
347
Narayan Kamatha5ace892017-01-06 15:10:02 +0000348 return receivedAck;
349}
350
Lorenzo Colitticd283772017-01-31 19:00:49 +0900351int IptablesRestoreController::execute(const IptablesTarget target, const std::string& command,
352 std::string *output) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000353 std::lock_guard<std::mutex> lock(mLock);
354
Lorenzo Colitticd283772017-01-31 19:00:49 +0900355 std::string buffer;
356 if (output == nullptr) {
357 output = &buffer;
358 }
359
Narayan Kamatha5ace892017-01-06 15:10:02 +0000360 int res = 0;
361 if (target == V4 || target == V4V6) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900362 res |= sendCommand(IPTABLES_PROCESS, command, output);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000363 }
364 if (target == V6 || target == V4V6) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900365 res |= sendCommand(IP6TABLES_PROCESS, command, output);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000366 }
367 return res;
368}
Lorenzo Colitti173da322017-02-05 01:56:40 +0900369
370int IptablesRestoreController::getIpRestorePid(const IptablesProcessType type) {
371 return type == IPTABLES_PROCESS ? mIpRestore->pid : mIp6Restore->pid;
372}