209d5106f661bbed52611cf5d3e318ff1feefbe6
[quix0rs-apt-p2p.git] / airproxy.py
1 from airhook import listenAirhookStream, StreamConnection
2
3 from twisted.internet import protocol, reactor
4 import sys
5 from random import randrange
6
7 #### airhook -> tcp
8 class UDPListener(protocol.Protocol):
9     started = 0
10     def makeConnection(self, connection):
11         self.conn = connection
12     def dataReceived(self, data):
13         if not self.started:
14             if data == '\03BAP':
15                 self.started = 1
16         else:
17             self.out.transport.write(data)
18         
19 class TCPReceiver(protocol.Protocol):
20     def dataReceived(self, data):
21         self.out.conn.write(data)
22
23 class TCPOutFactory(protocol.ClientFactory):
24     protocol = TCPReceiver
25     def __init__(self, out):
26         self.out = out
27     def buildProtocol(self, addr):
28         p = protocol.ClientFactory.buildProtocol(self, addr)
29         p.out = self.out
30         p.out.out = p
31         return p
32
33 class AirUDPProxyFactory(protocol.ServerFactory):
34     oport = 0
35     protocol = UDPListener
36     def __init__(self, out):
37         self.out = out
38     def buildProtocol(self, addr):
39         p = protocol.ServerFactory.buildProtocol(self, addr)
40         reactor.connectTCP('localhost', self.out, TCPOutFactory(p))
41         return p
42
43 def remote(udp, tcp):
44     f = AirUDPProxyFactory(tcp)
45     ah = listenAirhookStream(udp, f)
46
47
48 ######  tcp -> airhook
49 class UDPReceiver(protocol.Protocol):
50     def __init__(self, tcp):
51         self.tcp = tcp
52     def dataReceived(self, data):
53         self.tcp.transport.write(data)
54     def makeConnection(self, conn):
55         self.tcp.out = conn
56         conn.write("\03BAP")
57
58 class TCPListener(protocol.Protocol):
59     def dataReceived(self, data):
60         self.out.write(data)
61
62 class UDPOutFactory(protocol.ClientFactory):
63     protocol = UDPReceiver
64     def __init__(self, out):
65         self.out = out
66     def buildProtocol(self, addr):
67         p = UDPReceiver(self.out)
68         return p
69         
70 class AirTCPProxyFactory(protocol.ServerFactory):
71     oaddr = ('',0)
72     protocol = TCPListener
73     def __init__(self, oaddr):
74         self.oaddr = oaddr
75     def buildProtocol(self, addr):
76         p = TCPListener()
77         ah = listenAirhookStream(randrange(10000,12000), UDPOutFactory(p))
78         reactor.iterate()
79         c = ah.connectionForAddr(self.oaddr)
80         #c.noisy= 1 
81         return p
82         
83 def local(tcp, udp):
84     f = AirTCPProxyFactory(('64.81.64.214', udp))
85     reactor.listenTCP(tcp, f)
86     
87 if __name__ == '__main__':
88     if sys.argv[1] == '-l':
89         local(int(sys.argv[2]), int(sys.argv[3]))
90     else:
91         remote(int(sys.argv[2]), int(sys.argv[3]))
92     reactor.run()