| 1 |
|
|---|
| 2 |
|
|---|
| 3 |
|
|---|
| 4 |
|
|---|
| 5 |
""" |
|---|
| 6 |
A simple port forwarder. |
|---|
| 7 |
""" |
|---|
| 8 |
|
|---|
| 9 |
|
|---|
| 10 |
from twisted.internet import protocol |
|---|
| 11 |
from twisted.python import log |
|---|
| 12 |
|
|---|
| 13 |
class Proxy(protocol.Protocol): |
|---|
| 14 |
noisy = True |
|---|
| 15 |
|
|---|
| 16 |
peer = None |
|---|
| 17 |
|
|---|
| 18 |
def setPeer(self, peer): |
|---|
| 19 |
self.peer = peer |
|---|
| 20 |
|
|---|
| 21 |
def connectionLost(self, reason): |
|---|
| 22 |
if self.peer is not None: |
|---|
| 23 |
self.peer.transport.loseConnection() |
|---|
| 24 |
self.peer = None |
|---|
| 25 |
elif self.noisy: |
|---|
| 26 |
log.msg("Unable to connect to peer: %s" % (reason,)) |
|---|
| 27 |
|
|---|
| 28 |
def dataReceived(self, data): |
|---|
| 29 |
self.peer.transport.write(data) |
|---|
| 30 |
|
|---|
| 31 |
class ProxyClient(Proxy): |
|---|
| 32 |
def connectionMade(self): |
|---|
| 33 |
self.peer.setPeer(self) |
|---|
| 34 |
|
|---|
| 35 |
self.peer.transport.resumeProducing() |
|---|
| 36 |
|
|---|
| 37 |
class ProxyClientFactory(protocol.ClientFactory): |
|---|
| 38 |
|
|---|
| 39 |
protocol = ProxyClient |
|---|
| 40 |
|
|---|
| 41 |
def setServer(self, server): |
|---|
| 42 |
self.server = server |
|---|
| 43 |
|
|---|
| 44 |
def buildProtocol(self, *args, **kw): |
|---|
| 45 |
prot = protocol.ClientFactory.buildProtocol(self, *args, **kw) |
|---|
| 46 |
prot.setPeer(self.server) |
|---|
| 47 |
return prot |
|---|
| 48 |
|
|---|
| 49 |
def clientConnectionFailed(self, connector, reason): |
|---|
| 50 |
self.server.transport.loseConnection() |
|---|
| 51 |
|
|---|
| 52 |
|
|---|
| 53 |
class ProxyServer(Proxy): |
|---|
| 54 |
|
|---|
| 55 |
clientProtocolFactory = ProxyClientFactory |
|---|
| 56 |
|
|---|
| 57 |
def connectionMade(self): |
|---|
| 58 |
|
|---|
| 59 |
|
|---|
| 60 |
self.transport.pauseProducing() |
|---|
| 61 |
|
|---|
| 62 |
client = self.clientProtocolFactory() |
|---|
| 63 |
client.setServer(self) |
|---|
| 64 |
|
|---|
| 65 |
from twisted.internet import reactor |
|---|
| 66 |
reactor.connectTCP(self.factory.host, self.factory.port, client) |
|---|
| 67 |
|
|---|
| 68 |
|
|---|
| 69 |
class ProxyFactory(protocol.Factory): |
|---|
| 70 |
"""Factory for port forwarder.""" |
|---|
| 71 |
|
|---|
| 72 |
protocol = ProxyServer |
|---|
| 73 |
|
|---|
| 74 |
def __init__(self, host, port): |
|---|
| 75 |
self.host = host |
|---|
| 76 |
self.port = port |
|---|