blob: 7f54ea58b8f8b2a071657aac92bbab67e31337fb [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
235 // TODO: Investigate why this horrible hackery is necessary. We're currently
236 // sending iptables[6]-restore malformed commands. They appear to contain garbage
237 // after the last "\n". They obviously "work" because we fork a new process
238 // for every command so it doesn't matter whether the process chokes after
239 // the last successful COMMIT.
240 const std::string fixedCommand = fixCommandString(command);
241
242 if (!android::base::WriteFully((*process)->stdIn,
243 fixedCommand.data(),
244 fixedCommand.length())) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900245 ALOGE("Unable to send command: %s", strerror(errno));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900246 return -1;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000247 }
248
249 if (!android::base::WriteFully((*process)->stdIn, PING, PING_SIZE)) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900250 ALOGE("Unable to send ping command: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000251 return -1;
252 }
253
Lorenzo Colitti25091422017-02-03 16:05:28 +0900254 if (!drainAndWaitForAck(*process, fixedCommand, output)) {
Lorenzo Colitti173da322017-02-05 01:56:40 +0900255 // drainAndWaitForAck has already logged an error.
Narayan Kamatha5ace892017-01-06 15:10:02 +0000256 return -1;
257 }
258
259 return 0;
260}
261
262/* static */
263std::string IptablesRestoreController::fixCommandString(const std::string& command) {
264 std::string commandDup = command;
265 commandDup.erase(commandDup.find_last_of("\n") + 1);
266 return commandDup;
267}
268
269void IptablesRestoreController::maybeLogStderr(const std::unique_ptr<IptablesProcess> &process,
Lorenzo Colitti25091422017-02-03 16:05:28 +0900270 const std::string& command) {
271 if (process->errBuf.empty()) {
272 return;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000273 }
274
Lorenzo Colitti25091422017-02-03 16:05:28 +0900275 ALOGE("iptables error:\n"
276 "------- COMMAND -------\n"
277 "%s\n"
278 "------- ERROR -------\n"
279 "%s"
280 "----------------------\n",
281 command.c_str(), process->errBuf.c_str());
282 process->errBuf.clear();
Narayan Kamatha5ace892017-01-06 15:10:02 +0000283}
284
285// The maximum number of times we poll(2) for a response on our set of polled
286// fds. Chosen so that the overall timeout is 1s.
287static constexpr int MAX_RETRIES = 10;
288
289// The timeout (in millis) for each call to poll. The maximum wait is
290// |POLL_TIMEOUT_MS * MAX_RETRIES|. Chosen so that the overall timeout is 1s.
291static constexpr int POLL_TIMEOUT_MS = 100;
292
293/* static */
Lorenzo Colitticd283772017-01-31 19:00:49 +0900294bool IptablesRestoreController::drainAndWaitForAck(const std::unique_ptr<IptablesProcess> &process,
Lorenzo Colitti25091422017-02-03 16:05:28 +0900295 const std::string& command,
Lorenzo Colitticd283772017-01-31 19:00:49 +0900296 std::string *output) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000297 bool receivedAck = false;
298 int timeout = 0;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000299 while (!receivedAck && (timeout++ < MAX_RETRIES)) {
300 int numEvents = TEMP_FAILURE_RETRY(
301 poll(process->pollFds, ARRAY_SIZE(process->pollFds), POLL_TIMEOUT_MS));
302 if (numEvents == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900303 ALOGE("Poll failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000304 return false;
305 }
306
307 // We've timed out, which means something has gone wrong - we know that stdout should have
Lorenzo Colitti173da322017-02-05 01:56:40 +0900308 // become available to read with the ACK message, or that stderr should have been available
309 // to read with an error message.
Narayan Kamatha5ace892017-01-06 15:10:02 +0000310 if (numEvents == 0) {
311 continue;
312 }
313
Lorenzo Colitticd283772017-01-31 19:00:49 +0900314 char buffer[PIPE_BUF];
Narayan Kamatha5ace892017-01-06 15:10:02 +0000315 for (size_t i = 0; i < ARRAY_SIZE(process->pollFds); ++i) {
316 const struct pollfd &pollfd = process->pollFds[i];
317 if (pollfd.revents & POLLIN) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900318 ssize_t size;
319 do {
320 size = TEMP_FAILURE_RETRY(read(pollfd.fd, buffer, sizeof(buffer)));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000321
Lorenzo Colitticd283772017-01-31 19:00:49 +0900322 if (size == -1) {
323 if (errno != EAGAIN) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900324 ALOGE("Unable to read from descriptor: %s", strerror(errno));
Lorenzo Colitticd283772017-01-31 19:00:49 +0900325 }
326 break;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000327 }
Lorenzo Colitticd283772017-01-31 19:00:49 +0900328
329 if (i == IptablesProcess::STDOUT_IDX) {
330 // i == STDOUT_IDX: accumulate stdout into *output, and look
331 // for the ping response.
332 output->append(buffer, size);
333 size_t pos = output->find(PING);
334 if (pos != std::string::npos) {
335 if (output->size() > pos + PING_SIZE) {
336 size_t extra = output->size() - (pos + PING_SIZE);
337 ALOGW("%zd extra characters after iptables response: '%s...'",
338 extra, output->substr(pos + PING_SIZE, 128).c_str());
339 }
340 output->resize(pos);
341 receivedAck = true;
342 }
343 } else {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900344 // i == STDERR_IDX: accumulate stderr into errBuf.
345 process->errBuf.append(buffer, size);
Lorenzo Colitticd283772017-01-31 19:00:49 +0900346 }
347 } while (size > 0);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000348 }
Lorenzo Colitti173da322017-02-05 01:56:40 +0900349 if (pollfd.revents & POLLHUP) {
350 // The pipe was closed. This likely means the subprocess is exiting, since
351 // iptables-restore only closes stdin on error.
352 process->stop();
353 break;
354 }
Narayan Kamatha5ace892017-01-06 15:10:02 +0000355 }
356 }
357
Lorenzo Colitti25091422017-02-03 16:05:28 +0900358 if (!receivedAck && !process->processTerminated) {
359 ALOGE("Timed out waiting for response from iptables process %d", process->pid);
Lorenzo Colitti173da322017-02-05 01:56:40 +0900360 }
361
Lorenzo Colitti25091422017-02-03 16:05:28 +0900362 maybeLogStderr(process, command);
363
Narayan Kamatha5ace892017-01-06 15:10:02 +0000364 return receivedAck;
365}
366
Lorenzo Colitticd283772017-01-31 19:00:49 +0900367int IptablesRestoreController::execute(const IptablesTarget target, const std::string& command,
368 std::string *output) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000369 std::lock_guard<std::mutex> lock(mLock);
370
Lorenzo Colitticd283772017-01-31 19:00:49 +0900371 std::string buffer;
372 if (output == nullptr) {
373 output = &buffer;
374 }
375
Narayan Kamatha5ace892017-01-06 15:10:02 +0000376 int res = 0;
377 if (target == V4 || target == V4V6) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900378 res |= sendCommand(IPTABLES_PROCESS, command, output);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000379 }
380 if (target == V6 || target == V4V6) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900381 res |= sendCommand(IP6TABLES_PROCESS, command, output);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000382 }
383 return res;
384}
Lorenzo Colitti173da322017-02-05 01:56:40 +0900385
386int IptablesRestoreController::getIpRestorePid(const IptablesProcessType type) {
387 return type == IPTABLES_PROCESS ? mIpRestore->pid : mIp6Restore->pid;
388}