diff options
Diffstat (limited to 'redirecting_proxy.py')
-rwxr-xr-x | redirecting_proxy.py | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/redirecting_proxy.py b/redirecting_proxy.py new file mode 100755 index 0000000..29f5df4 --- /dev/null +++ b/redirecting_proxy.py | |||
@@ -0,0 +1,84 @@ | |||
1 | #!/usr/bin/python | ||
2 | import time | ||
3 | import select | ||
4 | import socket | ||
5 | |||
6 | |||
7 | class Proxy: | ||
8 | |||
9 | buffer_size = 4096 * 2 | ||
10 | delay = 0.0001 | ||
11 | |||
12 | def __init__(self, host_port, to_host_port): | ||
13 | self.forward_to = to_host_port | ||
14 | self.input_list = [] | ||
15 | self.channel = {} | ||
16 | |||
17 | self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
18 | self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
19 | self.server.bind(host_port) | ||
20 | self.server.listen(200) | ||
21 | |||
22 | def main_loop(self): | ||
23 | self.input_list.append(self.server) | ||
24 | |||
25 | while time.sleep(self.delay) or True: | ||
26 | for self.s in select.select(self.input_list, [], [])[0]: | ||
27 | if self.s == self.server: | ||
28 | self.on_accept() | ||
29 | break | ||
30 | |||
31 | self.data = self.s.recv(self.buffer_size) | ||
32 | if len(self.data) == 0: | ||
33 | self.on_close() | ||
34 | break | ||
35 | else: | ||
36 | self.on_recv() | ||
37 | |||
38 | def on_accept(self): | ||
39 | forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
40 | clientsock, clientaddr = self.server.accept() | ||
41 | try: | ||
42 | forward.connect(self.forward_to) | ||
43 | |||
44 | self.input_list.append(clientsock) | ||
45 | self.input_list.append(forward) | ||
46 | self.channel[clientsock] = forward | ||
47 | self.channel[forward] = clientsock | ||
48 | except Exception: | ||
49 | clientsock.close() | ||
50 | |||
51 | def on_close(self): | ||
52 | out = self.channel[self.s] | ||
53 | |||
54 | self.input_list.remove(self.s) | ||
55 | self.input_list.remove(self.channel[self.s]) | ||
56 | |||
57 | self.channel[out].close() | ||
58 | self.channel[self.s].close() | ||
59 | |||
60 | del self.channel[out] | ||
61 | del self.channel[self.s] | ||
62 | |||
63 | def on_recv(self): | ||
64 | if self.allow_data(): | ||
65 | print repr(self.data) | ||
66 | self.channel[self.s].send(self.data) | ||
67 | |||
68 | def allow_data(self): | ||
69 | return not ("admin.$cmd" in self.data and "shutdown" in self.data) | ||
70 | |||
71 | |||
72 | if __name__ == '__main__': | ||
73 | import os, sys | ||
74 | |||
75 | if len(sys.argv) < 3 or ":" not in sys.argv[2]: | ||
76 | program = os.path.basename(sys.argv[0]) | ||
77 | print "usage: {} <port> <to_host>:<to_port>".format(program) | ||
78 | sys.exit(1) | ||
79 | |||
80 | try: | ||
81 | to_host, to_port = sys.argv[2].split(":") | ||
82 | Proxy(('', int(sys.argv[1])), (to_host, int(to_port))).main_loop() | ||
83 | except KeyboardInterrupt: | ||
84 | sys.exit(1) | ||