blob: a90224a970de1551741e1a6e7ab7f773274dc9c2 [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>
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +090027#include <netdutils/Syscalls.h>
Narayan Kamatha5ace892017-01-06 15:10:02 +000028
29#include "Controllers.h"
30
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +090031using android::netdutils::StatusOr;
32using android::netdutils::sSyscalls;
33
Narayan Kamatha5ace892017-01-06 15:10:02 +000034constexpr char IPTABLES_RESTORE_PATH[] = "/system/bin/iptables-restore";
35constexpr char IP6TABLES_RESTORE_PATH[] = "/system/bin/ip6tables-restore";
36
37constexpr char PING[] = "#PING\n";
38
39constexpr size_t PING_SIZE = sizeof(PING) - 1;
40
Lorenzo Colittia701afb2017-02-28 01:47:11 +090041// Not compile-time constants because they are changed by the unit tests.
42int IptablesRestoreController::MAX_RETRIES = 50;
43int IptablesRestoreController::POLL_TIMEOUT_MS = 100;
Narayan Kamatha5ace892017-01-06 15:10:02 +000044
45class IptablesProcess {
46public:
47 IptablesProcess(pid_t pid, int stdIn, int stdOut, int stdErr) :
48 pid(pid),
49 stdIn(stdIn),
50 processTerminated(false) {
51
52 pollFds[STDOUT_IDX] = { .fd = stdOut, .events = POLLIN };
53 pollFds[STDERR_IDX] = { .fd = stdErr, .events = POLLIN };
54 }
55
56 ~IptablesProcess() {
57 close(stdIn);
58 close(pollFds[STDOUT_IDX].fd);
59 close(pollFds[STDERR_IDX].fd);
60 }
61
Lorenzo Colitti173da322017-02-05 01:56:40 +090062 bool outputReady() {
63 struct pollfd pollfd = { .fd = stdIn, .events = POLLOUT };
64 int ret = poll(&pollfd, 1, 0);
65 if (ret == -1) {
66 ALOGE("outputReady poll failed: %s", strerror(errno));
67 return false;
68 }
69 return (ret == 1) && !(pollfd.revents & POLLERR);
70 }
71
72 void stop() {
73 if (processTerminated) return;
74
75 // This can be called by drainAndWaitForAck (after a POLLHUP) or by sendCommand (if the
76 // process was killed by something else on the system). In both cases, it's safe to send the
77 // PID a SIGTERM, because the PID continues to exist until its parent (i.e., us) calls
78 // waitpid on it, so there's no risk that the PID is reused.
79 int err = kill(pid, SIGTERM);
80 if (err) {
81 err = errno;
82 }
83
84 if (err == ESRCH) {
85 // This means that someone else inside netd but outside this class called waitpid(),
86 // which is a programming error. There's no point in calling waitpid() here since we
87 // know that the process is gone.
88 ALOGE("iptables child process %d unexpectedly disappeared", pid);
89 processTerminated = true;
90 return;
91 }
92
93 if (err) {
94 ALOGE("Error killing iptables child process %d: %s", pid, strerror(err));
95 }
96
Lorenzo Colitti25091422017-02-03 16:05:28 +090097 int status;
98 if (waitpid(pid, &status, 0) == -1) {
Lorenzo Colitti173da322017-02-05 01:56:40 +090099 ALOGE("Error waiting for iptables child process %d: %s", pid, strerror(errno));
Lorenzo Colitti25091422017-02-03 16:05:28 +0900100 } else {
101 ALOGW("iptables-restore process %d terminated status=%d", pid, status);
Lorenzo Colitti173da322017-02-05 01:56:40 +0900102 }
103
104 processTerminated = true;
105 }
106
Narayan Kamatha5ace892017-01-06 15:10:02 +0000107 const pid_t pid;
108 const int stdIn;
109
110 struct pollfd pollFds[2];
111 std::string errBuf;
112
Lorenzo Colitti173da322017-02-05 01:56:40 +0900113 std::atomic_bool processTerminated;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000114
115 static constexpr size_t STDOUT_IDX = 0;
116 static constexpr size_t STDERR_IDX = 1;
117};
118
Lorenzo Colitti4e9ffd62017-08-09 16:45:19 +0900119IptablesRestoreController::IptablesRestoreController() {
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +0900120 Init();
121}
122
123IptablesRestoreController::~IptablesRestoreController() {
124}
125
126void IptablesRestoreController::Init() {
Lorenzo Colitti4e9ffd62017-08-09 16:45:19 +0900127 // Start the IPv4 and IPv6 processes in parallel, since each one takes 20-30ms.
128 std::thread v4([this] () { mIpRestore.reset(forkAndExec(IPTABLES_PROCESS)); });
129 std::thread v6([this] () { mIp6Restore.reset(forkAndExec(IP6TABLES_PROCESS)); });
130 v4.join();
131 v6.join();
Narayan Kamatha5ace892017-01-06 15:10:02 +0000132}
133
Narayan Kamatha5ace892017-01-06 15:10:02 +0000134/* static */
135IptablesProcess* IptablesRestoreController::forkAndExec(const IptablesProcessType type) {
136 const char* const cmd = (type == IPTABLES_PROCESS) ?
137 IPTABLES_RESTORE_PATH : IP6TABLES_RESTORE_PATH;
138
139 // Create the pipes we'll use for communication with the child
140 // process. One each for the child's in, out and err files.
141 int stdin_pipe[2];
142 int stdout_pipe[2];
143 int stderr_pipe[2];
144
145 if (pipe2(stdin_pipe, 0) == -1 ||
Lorenzo Colitticd283772017-01-31 19:00:49 +0900146 pipe2(stdout_pipe, O_NONBLOCK) == -1 ||
147 pipe2(stderr_pipe, O_NONBLOCK) == -1) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000148
Lorenzo Colitti25091422017-02-03 16:05:28 +0900149 ALOGE("pipe2() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000150 return nullptr;
151 }
152
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +0900153 const auto& sys = sSyscalls.get();
154 StatusOr<pid_t> child_pid = sys.fork();
155 if (!isOk(child_pid)) {
156 ALOGE("fork() failed: %s", strerror(child_pid.status().code()));
157 return nullptr;
158 }
159
160 if (child_pid.value() == 0) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000161 // The child process. Reads from stdin, writes to stderr and stdout.
162
163 // stdin_pipe[1] : The write end of the stdin pipe.
164 // stdout_pipe[0] : The read end of the stdout pipe.
165 // stderr_pipe[0] : The read end of the stderr pipe.
166 if (close(stdin_pipe[1]) == -1 ||
167 close(stdout_pipe[0]) == -1 ||
168 close(stderr_pipe[0]) == -1) {
169
Lorenzo Colitti25091422017-02-03 16:05:28 +0900170 ALOGW("close() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000171 }
172
173 // stdin_pipe[0] : The read end of the stdin pipe.
174 // stdout_pipe[1] : The write end of the stdout pipe.
175 // stderr_pipe[1] : The write end of the stderr pipe.
176 if (dup2(stdin_pipe[0], 0) == -1 ||
177 dup2(stdout_pipe[1], 1) == -1 ||
178 dup2(stderr_pipe[1], 2) == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900179 ALOGE("dup2() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000180 abort();
181 }
182
183 if (execl(cmd,
184 cmd,
185 "--noflush", // Don't flush the whole table.
186 "-w", // Wait instead of failing if the lock is held.
187 "-v", // Verbose mode, to make sure our ping is echoed
188 // back to us.
189 nullptr) == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900190 ALOGE("execl(%s, ...) failed: %s", cmd, strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000191 abort();
192 }
193
194 // This statement is unreachable. We abort() upon error, and execl
195 // if everything goes well.
196 return nullptr;
197 }
198
199 // The parent process. Writes to stdout and stderr and reads from stdin.
Narayan Kamatha5ace892017-01-06 15:10:02 +0000200 // stdin_pipe[0] : The read end of the stdin pipe.
201 // stdout_pipe[1] : The write end of the stdout pipe.
202 // stderr_pipe[1] : The write end of the stderr pipe.
203 if (close(stdin_pipe[0]) == -1 ||
204 close(stdout_pipe[1]) == -1 ||
205 close(stderr_pipe[1]) == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900206 ALOGW("close() failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000207 }
208
Lorenzo Colitti2103b6b2017-08-14 11:38:18 +0900209 return new IptablesProcess(child_pid.value(), stdin_pipe[1], stdout_pipe[0], stderr_pipe[0]);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000210}
211
Narayan Kamatha5ace892017-01-06 15:10:02 +0000212// TODO: Return -errno on failure instead of -1.
213// TODO: Maybe we should keep a rotating buffer of the last N commands
214// so that they can be dumped on dumpsys.
215int IptablesRestoreController::sendCommand(const IptablesProcessType type,
Lorenzo Colitticd283772017-01-31 19:00:49 +0900216 const std::string& command,
217 std::string *output) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000218 std::unique_ptr<IptablesProcess> *process =
219 (type == IPTABLES_PROCESS) ? &mIpRestore : &mIp6Restore;
220
Lorenzo Colitti173da322017-02-05 01:56:40 +0900221
Narayan Kamatha5ace892017-01-06 15:10:02 +0000222 // We might need to fork a new process if we haven't forked one yet, or
223 // if the forked process terminated.
224 //
225 // NOTE: For a given command, this is the last point at which we try to
226 // recover from a child death. If the child dies at some later point during
227 // the execution of this method, we will receive an EPIPE and return an
228 // error. The command will then need to be retried at a higher level.
Lorenzo Colitti173da322017-02-05 01:56:40 +0900229 IptablesProcess *existingProcess = process->get();
230 if (existingProcess != nullptr && !existingProcess->outputReady()) {
231 existingProcess->stop();
232 existingProcess = nullptr;
233 }
234
235 if (existingProcess == nullptr) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000236 // Fork a new iptables[6]-restore process.
237 IptablesProcess *newProcess = IptablesRestoreController::forkAndExec(type);
238 if (newProcess == nullptr) {
239 LOG(ERROR) << "Unable to fork ip[6]tables-restore, type: " << type;
240 return -1;
241 }
242
243 process->reset(newProcess);
244 }
245
Lorenzo Colitti20b128b2017-02-10 11:01:08 +0900246 if (!android::base::WriteFully((*process)->stdIn, command.data(), command.length())) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900247 ALOGE("Unable to send command: %s", strerror(errno));
Lorenzo Colitti173da322017-02-05 01:56:40 +0900248 return -1;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000249 }
250
251 if (!android::base::WriteFully((*process)->stdIn, PING, PING_SIZE)) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900252 ALOGE("Unable to send ping command: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000253 return -1;
254 }
255
Lorenzo Colitti20b128b2017-02-10 11:01:08 +0900256 if (!drainAndWaitForAck(*process, command, output)) {
Lorenzo Colitti173da322017-02-05 01:56:40 +0900257 // drainAndWaitForAck has already logged an error.
Narayan Kamatha5ace892017-01-06 15:10:02 +0000258 return -1;
259 }
260
261 return 0;
262}
263
Narayan Kamatha5ace892017-01-06 15:10:02 +0000264void IptablesRestoreController::maybeLogStderr(const std::unique_ptr<IptablesProcess> &process,
Lorenzo Colitti25091422017-02-03 16:05:28 +0900265 const std::string& command) {
266 if (process->errBuf.empty()) {
267 return;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000268 }
269
Lorenzo Colitti25091422017-02-03 16:05:28 +0900270 ALOGE("iptables error:\n"
271 "------- COMMAND -------\n"
272 "%s\n"
273 "------- ERROR -------\n"
274 "%s"
275 "----------------------\n",
276 command.c_str(), process->errBuf.c_str());
277 process->errBuf.clear();
Narayan Kamatha5ace892017-01-06 15:10:02 +0000278}
279
Narayan Kamatha5ace892017-01-06 15:10:02 +0000280/* static */
Lorenzo Colitticd283772017-01-31 19:00:49 +0900281bool IptablesRestoreController::drainAndWaitForAck(const std::unique_ptr<IptablesProcess> &process,
Lorenzo Colitti25091422017-02-03 16:05:28 +0900282 const std::string& command,
Lorenzo Colitticd283772017-01-31 19:00:49 +0900283 std::string *output) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000284 bool receivedAck = false;
285 int timeout = 0;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000286 while (!receivedAck && (timeout++ < MAX_RETRIES)) {
287 int numEvents = TEMP_FAILURE_RETRY(
288 poll(process->pollFds, ARRAY_SIZE(process->pollFds), POLL_TIMEOUT_MS));
289 if (numEvents == -1) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900290 ALOGE("Poll failed: %s", strerror(errno));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000291 return false;
292 }
293
294 // We've timed out, which means something has gone wrong - we know that stdout should have
Lorenzo Colitti173da322017-02-05 01:56:40 +0900295 // become available to read with the ACK message, or that stderr should have been available
296 // to read with an error message.
Narayan Kamatha5ace892017-01-06 15:10:02 +0000297 if (numEvents == 0) {
298 continue;
299 }
300
Lorenzo Colitticd283772017-01-31 19:00:49 +0900301 char buffer[PIPE_BUF];
Narayan Kamatha5ace892017-01-06 15:10:02 +0000302 for (size_t i = 0; i < ARRAY_SIZE(process->pollFds); ++i) {
303 const struct pollfd &pollfd = process->pollFds[i];
304 if (pollfd.revents & POLLIN) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900305 ssize_t size;
306 do {
307 size = TEMP_FAILURE_RETRY(read(pollfd.fd, buffer, sizeof(buffer)));
Narayan Kamatha5ace892017-01-06 15:10:02 +0000308
Lorenzo Colitticd283772017-01-31 19:00:49 +0900309 if (size == -1) {
310 if (errno != EAGAIN) {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900311 ALOGE("Unable to read from descriptor: %s", strerror(errno));
Lorenzo Colitticd283772017-01-31 19:00:49 +0900312 }
313 break;
Narayan Kamatha5ace892017-01-06 15:10:02 +0000314 }
Lorenzo Colitticd283772017-01-31 19:00:49 +0900315
316 if (i == IptablesProcess::STDOUT_IDX) {
317 // i == STDOUT_IDX: accumulate stdout into *output, and look
318 // for the ping response.
319 output->append(buffer, size);
320 size_t pos = output->find(PING);
321 if (pos != std::string::npos) {
322 if (output->size() > pos + PING_SIZE) {
323 size_t extra = output->size() - (pos + PING_SIZE);
324 ALOGW("%zd extra characters after iptables response: '%s...'",
325 extra, output->substr(pos + PING_SIZE, 128).c_str());
326 }
327 output->resize(pos);
328 receivedAck = true;
329 }
330 } else {
Lorenzo Colitti25091422017-02-03 16:05:28 +0900331 // i == STDERR_IDX: accumulate stderr into errBuf.
332 process->errBuf.append(buffer, size);
Lorenzo Colitticd283772017-01-31 19:00:49 +0900333 }
334 } while (size > 0);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000335 }
Lorenzo Colitti173da322017-02-05 01:56:40 +0900336 if (pollfd.revents & POLLHUP) {
337 // The pipe was closed. This likely means the subprocess is exiting, since
338 // iptables-restore only closes stdin on error.
339 process->stop();
340 break;
341 }
Narayan Kamatha5ace892017-01-06 15:10:02 +0000342 }
343 }
344
Lorenzo Colitti25091422017-02-03 16:05:28 +0900345 if (!receivedAck && !process->processTerminated) {
346 ALOGE("Timed out waiting for response from iptables process %d", process->pid);
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900347 // Kill the process so that if it eventually recovers, we don't misinterpret the ping
348 // response (or any output) of the command we just sent as coming from future commands.
349 process->stop();
Lorenzo Colitti173da322017-02-05 01:56:40 +0900350 }
351
Lorenzo Colitti25091422017-02-03 16:05:28 +0900352 maybeLogStderr(process, command);
353
Narayan Kamatha5ace892017-01-06 15:10:02 +0000354 return receivedAck;
355}
356
Lorenzo Colitticd283772017-01-31 19:00:49 +0900357int IptablesRestoreController::execute(const IptablesTarget target, const std::string& command,
358 std::string *output) {
Narayan Kamatha5ace892017-01-06 15:10:02 +0000359 std::lock_guard<std::mutex> lock(mLock);
360
Lorenzo Colitticd283772017-01-31 19:00:49 +0900361 std::string buffer;
362 if (output == nullptr) {
363 output = &buffer;
Lorenzo Colittia701afb2017-02-28 01:47:11 +0900364 } else {
365 output->clear();
Lorenzo Colitticd283772017-01-31 19:00:49 +0900366 }
367
Narayan Kamatha5ace892017-01-06 15:10:02 +0000368 int res = 0;
369 if (target == V4 || target == V4V6) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900370 res |= sendCommand(IPTABLES_PROCESS, command, output);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000371 }
372 if (target == V6 || target == V4V6) {
Lorenzo Colitticd283772017-01-31 19:00:49 +0900373 res |= sendCommand(IP6TABLES_PROCESS, command, output);
Narayan Kamatha5ace892017-01-06 15:10:02 +0000374 }
375 return res;
376}
Lorenzo Colitti173da322017-02-05 01:56:40 +0900377
378int IptablesRestoreController::getIpRestorePid(const IptablesProcessType type) {
379 return type == IPTABLES_PROCESS ? mIpRestore->pid : mIp6Restore->pid;
380}