Bridge thingy TCP middle thing
bridge.py
114 lines 2.9 kB view raw
1#!/usr/bin/python3 2from twisted.internet import reactor, protocol 3import sys 4 5class Client(protocol.Protocol): 6 7 def __init__(self, s): 8 self.server = s 9 self.connected = 0 10 self.data = [] 11 12 def connectionMade(self): 13 self.connected = 1 14 for a in self.data: 15 self.transport.write(a) 16 self.data = [] 17 18 def write(self, a): 19 if self.connected: 20 self.transport.write(a) 21 else: 22 self.data.append(a) 23 24 def dataReceived(self, a): 25 self.server.write(a) 26 print(self.server.i, 'S', formatbytes(a)) 27 28 def connectionLost(self, reason=''): 29 if self.server.client: 30 print('Connection', self.server.i, 'lost from server') 31 self.server.transport.loseConnection() 32 self.server = None 33 34class ClientFactory(protocol.ClientFactory): 35 36 def __init__(self, c): 37 self.client = c 38 39 def buildProtocol(self, a): 40 return self.client 41 42class Server(protocol.Protocol): 43 44 def __init__(self): 45 global i 46 self.i = i = i + 1 47 self.client = Client(self) 48 print('Connection', i, 'initialized') 49 50 def connectionMade(self): 51 reactor.connectTCP(sys.argv[1], int(sys.argv[2]), ClientFactory(self.client)) 52 53 def dataReceived(self, a): 54 self.client.write(a) 55 print(self.i, 'C', formatbytes(a)) 56 57 def write(self, a): 58 self.transport.write(a) 59 60 def connectionLost(self,reason=1): 61 if self.client.server: 62 print('Connection', self.i, 'lost from client') 63 self.client.transport.loseConnection() 64 self.client = None 65 66class ServerFactory(protocol.ServerFactory): 67 protocol = Server 68 69def highlight(byt): 70 table = {0:'000', 1:'001', 2:'002', 3:'003', 4:'004', 5:'005', 6:'006', 7:'a', 8:'b', 9:'t', 10:'n', 11:'v', 12:'f', 13:'r'} 71 i = 0 72 out = 'b\'' 73 pb = False 74 for a in byt: 75 if a >= 32 and a <= 126: 76 if pb: 77 out += '\033[39m' 78 pb = False 79 if a == 39: # ' 80 out += '\\\'' 81 elif a == 92: # \ 82 out += '\\\\' 83 else: 84 out += chr(a) 85 else: 86 i += 1 87 pb = True 88 out += '\033[9%sm' % ((i % 2) + 1) 89 t = table.get(a) 90 if t: 91 out += '\\%s' % t 92 else: 93 out += '\\x%02x' % a 94 95 if pb: 96 out += '\033[39m' 97 out += "'" 98 return out 99 100def formatbytes(d): 101 if isatty: 102 return (highlight(d)) 103 else: 104 return (ascii(d)) 105 106i = 0 107isatty = sys.stdout.isatty() 108if __name__ == '__main__': 109 if len(sys.argv) not in (4, 5): 110 exit('Usage %s host connectPort listenPort' % sys.argv[0]); 111 112 interface = sys.argv[4] if len(sys.argv) == 5 else '127.0.0.1' 113 reactor.listenTCP(int(sys.argv[3]), ServerFactory(), interface=interface) 114 reactor.run()