2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <arpa/inet.h>
25 #define LOG_TAG "NatController"
26 #include <cutils/log.h>
28 #include "NatController.h"
30 extern "C" int logwrap(int argc, const char **argv, int background);
32 static char IPTABLES_PATH[] = "/system/bin/iptables";
34 NatController::NatController() {
38 NatController::~NatController() {
41 int NatController::runIptablesCmd(const char *cmd) {
44 strncpy(buffer, cmd, sizeof(buffer)-1);
50 args[0] = IPTABLES_PATH;
51 args[1] = "--verbose";
54 while ((tmp = strsep(&next, " "))) {
57 LOGE("iptables argument overflow");
64 return logwrap(i, args, 0);
67 int NatController::setDefaults() {
69 if (runIptablesCmd("-P INPUT ACCEPT"))
71 if (runIptablesCmd("-F INPUT"))
73 if (runIptablesCmd("-P OUTPUT ACCEPT"))
75 if (runIptablesCmd("-F OUTPUT"))
77 if (runIptablesCmd("-P FORWARD DROP"))
79 if (runIptablesCmd("-F FORWARD"))
81 if (runIptablesCmd("-t nat -F"))
86 bool NatController::interfaceExists(const char *iface) {
87 // XXX: STOPSHIP - Implement this
91 int NatController::doNatCommands(const char *intIface, const char *extIface, bool add) {
94 // handle decrement to 0 case (do reset to defaults) and erroneous dec below 0
97 int ret = setDefaults();
105 if (!interfaceExists(intIface) || !interfaceExists (extIface)) {
106 LOGE("Invalid interface specified");
111 snprintf(cmd, sizeof(cmd),
112 "-%s FORWARD -i %s -o %s -m state --state ESTABLISHED,RELATED -j ACCEPT",
115 if (runIptablesCmd(cmd)) {
119 snprintf(cmd, sizeof(cmd), "-%s FORWARD -i %s -o %s -j ACCEPT", (add ? "A" : "D"),
121 if (runIptablesCmd(cmd)) {
122 // unwind what's been done, but don't care about success - what more could we do?
123 snprintf(cmd, sizeof(cmd),
124 "-%s FORWARD -i %s -o %s -m state --state ESTABLISHED,RELATED -j ACCEPT",
130 // add this if we are the first added nat
131 if (add && natCount == 0) {
132 snprintf(cmd, sizeof(cmd), "-t nat -A POSTROUTING -o %s -j MASQUERADE", extIface);
133 if (runIptablesCmd(cmd)) {
134 // unwind what's been done, but don't care about success - what more could we do?
148 int NatController::enableNat(const char *intIface, const char *extIface) {
149 return doNatCommands(intIface, extIface, true);
152 int NatController::disableNat(const char *intIface, const char *extIface) {
153 return doNatCommands(intIface, extIface, false);