Fix shebang.
[wank.git] / wank.py
blob3b0a5f8b957869bff3c5540fd04a30649e459bbd
1 #!/usr/bin/env python
3 import BaseHTTPServer
4 import SocketServer
5 import select
6 import socket
7 import urlparse
9 import socks
11 LISTEN_ADDR = '127.0.0.1'
12 LISTEN_PORT = 8123
14 TOR_ADDR = '127.0.0.1'
15 TOR_PORT = 9050
17 TIMEOUT = 20
19 class ProxyHandler (BaseHTTPServer.BaseHTTPRequestHandler):
20 rbufsize = 0 # self.rfile Be unbuffered
22 def _connect_to(self, netloc, soc):
23 i = netloc.find(':')
24 if i >= 0:
25 host_port = netloc[:i], int(netloc[i+1:])
26 else:
27 host_port = netloc, 80
28 #print "connect to %s:%d" % host_port
29 try:
30 soc.connect(host_port)
31 except Exception:
32 #self.send_error(502)
33 return False
34 return True
36 def do_CONNECT(self):
37 soc = socks.socksocket()
38 soc.setproxy(socks.PROXY_TYPE_SOCKS5, TOR_ADDR, TOR_PORT)
39 try:
40 if self._connect_to(self.path, soc):
41 #self.log_request(200)
42 self.wfile.write(self.protocol_version +
43 " 200 Connection established\r\n")
44 self.wfile.write("\r\n")
45 self._read_write(soc, 300)
46 finally:
47 #print "bye"
48 soc.close()
49 self.connection.close()
51 def do_GET(self):
52 (scm, netloc, path, params, query, fragment) = urlparse.urlparse(
53 self.path, 'http')
54 if scm != 'http' or fragment or not netloc:
55 self.send_error(400, "bad url %s" % self.path)
56 return
57 soc = socks.socksocket()
58 soc.setproxy(socks.PROXY_TYPE_SOCKS5, TOR_ADDR, TOR_PORT)
59 try:
60 if self._connect_to(netloc, soc):
61 #self.log_request()
62 soc.send("%s %s %s\r\n" % (
63 self.command,
64 urlparse.urlunparse(('', '', path, params, query, '')),
65 self.request_version))
66 self.headers['Connection'] = 'close'
67 del self.headers['Proxy-Connection']
68 for header in self.headers.headers:
69 soc.send(header.strip() + '\r\n')
70 soc.send("\r\n")
71 self._read_write(soc)
72 finally:
73 #print "bye"
74 soc.close()
75 self.connection.close()
77 def _read_write(self, soc, max_idling=TIMEOUT):
78 iw = [self.connection, soc]
79 count = 0
80 while True:
81 count += 1
82 (ins, _, exs) = select.select(iw, [], iw, 3)
83 if ins:
84 for i in ins:
85 if i is soc:
86 out = self.connection
87 else:
88 out = soc
89 data = i.recv(8192)
90 if data:
91 out.send(data)
92 count = 0
93 else:
94 print "idle", count
95 if exs:
96 break
97 if count == max_idling:
98 #self.send_error(504, "Connection timed out")
99 break
101 do_HEAD = do_GET
102 do_POST = do_GET
103 do_PUT = do_GET
104 do_DELETE = do_GET
106 class WankProxy(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
107 def __init__(self):
108 BaseHTTPServer.HTTPServer.__init__(self,
109 (LISTEN_ADDR, LISTEN_PORT),
110 ProxyHandler)
112 if __name__ == '__main__':
113 try:
114 print "Listening on %s:%s..." % (LISTEN_ADDR, LISTEN_PORT)
115 httpd = WankProxy()
116 httpd.serve_forever()
117 except KeyboardInterrupt:
118 print "Exiting on ^C..."