forked from ravinet/mahimahi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnat.cc
45 lines (36 loc) · 1.4 KB
/
nat.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* -*-mode:c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* RAII class to make connections coming from the ingress address
look like they're coming from the output device's address.
We mark the connections on entry from the ingress address (with our PID),
and then look for the mark on output. */
#include <unistd.h>
#include "nat.hh"
#include "exception.hh"
using namespace std;
NATRule::NATRule( const vector< string > & s_args )
: arguments( s_args )
{
vector< string > command = { IPTABLES, "-t", "nat", "-A" };
command.insert( command.end(), arguments.begin(), arguments.end() );
run( command );
}
NATRule::~NATRule()
{
try {
vector< string > command = { IPTABLES, "-t", "nat", "-D" };
command.insert( command.end(), arguments.begin(), arguments.end() );
run( command );
} catch ( const Exception & e ) { /* don't throw from destructor */
e.perror();
}
}
NAT::NAT( const Address & ingress_addr )
: pre_( { "PREROUTING", "-s", ingress_addr.ip(), "-j", "CONNMARK",
"--set-mark", to_string( getpid() ) } ),
post_( { "POSTROUTING", "-j", "MASQUERADE", "-m", "connmark",
"--mark", to_string( getpid() ) } )
{}
DNAT::DNAT( const Address & listener, const string & interface )
: rule_( { "PREROUTING", "-p", "TCP", "-i", interface, "-j", "DNAT",
"--to-destination", listener.str() } )
{}