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>
26 #define LOG_TAG "NatController"
27 #include <cutils/log.h>
29 #include "NatController.h"
31 extern "C" int logwrap(int argc, const char **argv, int background);
33 static char IPTABLES_PATH[] = "/system/bin/iptables";
35 NatController::NatController() {
39 NatController::~NatController() {
42 int NatController::runIptablesCmd(const char *cmd) {
45 strncpy(buffer, cmd, sizeof(buffer)-1);
51 args[0] = IPTABLES_PATH;
52 args[1] = "--verbose";
55 while ((tmp = strsep(&next, " "))) {
58 LOGE("iptables argument overflow");
65 return logwrap(i, args, 0);
68 int NatController::setDefaults() {
70 if (runIptablesCmd("-P INPUT ACCEPT"))
72 if (runIptablesCmd("-F INPUT"))
74 if (runIptablesCmd("-P OUTPUT ACCEPT"))
76 if (runIptablesCmd("-F OUTPUT"))
78 if (runIptablesCmd("-P FORWARD DROP"))
80 if (runIptablesCmd("-F FORWARD"))
82 if (runIptablesCmd("-t nat -F"))
87 bool NatController::interfaceExists(const char *iface) {
88 // XXX: Implement this
92 int NatController::doNatCommands(const char *intIface, const char *extIface, bool add) {
95 // handle decrement to 0 case (do reset to defaults) and erroneous dec below 0
98 int ret = setDefaults();
106 if (!interfaceExists(intIface) || !interfaceExists (extIface)) {
107 LOGE("Invalid interface specified");
112 snprintf(cmd, sizeof(cmd),
113 "-%s FORWARD -i %s -o %s -m state --state ESTABLISHED,RELATED -j ACCEPT",
116 if (runIptablesCmd(cmd)) {
120 snprintf(cmd, sizeof(cmd), "-%s FORWARD -i %s -o %s -j ACCEPT", (add ? "A" : "D"),
122 if (runIptablesCmd(cmd)) {
123 // unwind what's been done, but don't care about success - what more could we do?
124 snprintf(cmd, sizeof(cmd),
125 "-%s FORWARD -i %s -o %s -m state --state ESTABLISHED,RELATED -j ACCEPT",
131 // add this if we are the first added nat
132 if (add && natCount == 0) {
133 snprintf(cmd, sizeof(cmd), "-t nat -A POSTROUTING -o %s -j MASQUERADE", extIface);
134 if (runIptablesCmd(cmd)) {
135 // unwind what's been done, but don't care about success - what more could we do?
149 int NatController::enableNat(const char *intIface, const char *extIface) {
150 return doNatCommands(intIface, extIface, true);
153 int NatController::disableNat(const char *intIface, const char *extIface) {
154 return doNatCommands(intIface, extIface, false);