1 # vim: set encoding=utf-8 et sw=4 sts=4 :
3 from pymin.seqtools import Sequence
4 from pymin.service.util import ListSubHandler
6 __all__ = ('PortForwardHandler',)
9 class PortForward(Sequence):
10 r"""PortForward(dev, protocol, port, dst[, dst_port[, ...]]) -> PortForward.
12 dev - Netword device to use.
13 protocol - TCP or UDP.
14 port - Port to forward.
15 dst - Destination IP address.
16 dst_port - Destination port (at dst).
17 src_net - Source network to apply the forward (as IP/mask).
18 dst_net - Source network to apply the forward (as IP/mask).
21 def __init__(self, dev, protocol, port, dst, dst_port=None, src_net=None,
23 r"Initialize object, see class documentation for details."
26 self.protocol = protocol
29 self.dst_port = dst_port
30 self.src_net = src_net
31 self.dst_net = dst_net
33 def update(self, dev=None, protocol=None, port=None, dst=None,
34 dst_port=None, src_net=None, dst_net=None):
35 r"update([dev[, ...]]) -> Update the values of a port (see class doc)."
37 if dev is not None: self.dev = dev
38 if protocol is not None: self.protocol = protocol
39 if port is not None: self.port = port
40 if dst is not None: self.dst = dst
41 if dst_port is not None: self.dst_port = dst_port
42 if src_net is not None: self.src_net = src_net
43 if dst_net is not None: self.dst_net = dst_net
46 r"Return a tuple representing the port forward."
47 return (self.dev, self.protocol, self.port, self.dst, self.dst_port,
48 self.src_net, self.dst_net)
50 def as_call_list(self, index=None):
51 if self.dst_port is not None:
52 self.dst = self.dst + ':' + self.dst_port
53 cmd = ['-t', 'nat', '-I', 'PREROUTING']
55 cmd.append(str(index))
56 cmd.extend(('-i', self.dev, '-j', 'DNAT', '--to', self.dst,
57 '-p', self.protocol, '--dport', self.port))
58 if self.src_net is not None:
59 cmd.extend(('-s', self.src_net))
60 if self.dst_net is not None:
61 cmd.extend(('-d', self.dst_net))
64 class PortForwardHandler(ListSubHandler):
65 r"""PortForwardHandler(parent) -> PortForwardHandler instance.
67 This class is a helper for NatHandler to do all the work related to port
70 parent - The parent service handler.
73 handler_help = u"Manage NAT port forwarding."
75 _cont_subhandler_attr = 'ports'
76 _cont_subhandler_class = PortForward