Debian Codegraph @

tests/tinyproxy.py

raw
1 #!/usr/bin/env python3
2
3
4 __doc__ = """Tiny HTTP Proxy.
5
6 This module implements GET, HEAD, POST, PUT and DELETE methods
7 on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT
8 method is also implemented experimentally, but has not been
9 tested yet.
10
11 Any help will be greatly appreciated. SUZUKI Hisao
12 """
13
14 __version__ = "0.2.1"
15
16 import optparse
17 import os
18 import select
19 import socket
20 import sys
21
22 from mercurial import (
23 pycompat,
24 util,
25 )
26
27 httpserver = util.httpserver
28 socketserver = util.socketserver
29 urlreq = util.urlreq
30
31 if os.environ.get('HGIPV6', '0') == '1':
32 family = socket.AF_INET6
33 else:
34 family = socket.AF_INET
35
36
37 class ProxyHandler(httpserver.basehttprequesthandler):
38 __base = httpserver.basehttprequesthandler
39 __base_handle = __base.handle
40
41 server_version = "TinyHTTPProxy/" + __version__
42 rbufsize = 0 # self.rfile Be unbuffered
43
44 def handle(self):
45 (ip, port) = self.client_address
46 allowed = getattr(self, 'allowed_clients', None)
47 if allowed is not None and ip not in allowed:
48 self.raw_requestline = self.rfile.readline()
49 if self.parse_request():
50 self.send_error(403)
51 else:
52 self.__base_handle()
53
54 def log_request(self, code='-', size='-'):
55 xheaders = [h for h in self.headers.items() if h[0].startswith('x-')]
56 self.log_message(
57 '"%s" %s %s%s',
58 self.requestline,
59 str(code),
60 str(size),
61 ''.join([' %s:%s' % h for h in sorted(xheaders)]),
62 )
63 # Flush for Windows, so output isn't lost on TerminateProcess()
64 sys.stdout.flush()
65 sys.stderr.flush()
66
67 def _connect_to(self, netloc, soc):
68 i = netloc.find(':')
69 if i >= 0:
70 host_port = netloc[:i], int(netloc[i + 1 :])
71 else:
72 host_port = netloc, 80
73 print("\t" "connect to %s:%d" % host_port)
74 try:
75 soc.connect(host_port)
76 except OSError as e:
77 self.send_error(404, e.strerror)
78 return 0
79 return 1
80
81 def do_CONNECT(self):
82 soc = socket.socket(family, socket.SOCK_STREAM)
83 try:
84 if self._connect_to(self.path, soc):
85 self.log_request(200)
86 self.wfile.write(
87 pycompat.bytestr(self.protocol_version)
88 + b" 200 Connection established\r\n"
89 )
90 self.wfile.write(
91 b"Proxy-agent: %s\r\n"
92 % pycompat.bytestr(self.version_string())
93 )
94 self.wfile.write(b"\r\n")
95 self._read_write(soc, 300)
96 finally:
97 print("\t" "bye")
98 soc.close()
99 self.connection.close()
100
101 def do_GET(self):
102 (scm, netloc, path, params, query, fragment) = urlreq.urlparse(
103 self.path, 'http'
104 )
105 if scm != 'http' or fragment or not netloc:
106 self.send_error(400, "bad url %s" % self.path)
107 return
108 soc = socket.socket(family, socket.SOCK_STREAM)
109 try:
110 if self._connect_to(netloc, soc):
111 self.log_request()
112 url = urlreq.urlunparse(('', '', path, params, query, ''))
113 soc.send(
114 b"%s %s %s\r\n"
115 % (
116 pycompat.bytestr(self.command),
117 pycompat.bytestr(url),
118 pycompat.bytestr(self.request_version),
119 )
120 )
121 self.headers['Connection'] = 'close'
122 del self.headers['Proxy-Connection']
123 for key, val in self.headers.items():
124 soc.send(
125 b"%s: %s\r\n"
126 % (pycompat.bytestr(key), pycompat.bytestr(val))
127 )
128 soc.send(b"\r\n")
129 self._read_write(soc)
130 finally:
131 print("\t" "bye")
132 soc.close()
133 self.connection.close()
134
135 def _read_write(self, soc, max_idling=20):
136 iw = [self.connection, soc]
137 ow = []
138 count = 0
139 while True:
140 count += 1
141 (ins, _, exs) = select.select(iw, ow, iw, 3)
142 if exs:
143 break
144 if ins:
145 for i in ins:
146 if i is soc:
147 out = self.connection
148 else:
149 out = soc
150 try:
151 data = i.recv(8192)
152 except OSError:
153 break
154 if data:
155 out.send(data)
156 count = 0
157 else:
158 print("\t" "idle", count)
159 if count == max_idling:
160 break
161
162 do_HEAD = do_GET
163 do_POST = do_GET
164 do_PUT = do_GET
165 do_DELETE = do_GET
166
167
168 class ThreadingHTTPServer(socketserver.ThreadingMixIn, httpserver.httpserver):
169 def __init__(self, *args, **kwargs):
170 httpserver.httpserver.__init__(self, *args, **kwargs)
171 a = open("proxy.pid", "w")
172 a.write(str(os.getpid()) + "\n")
173 a.close()
174
175
176 def runserver(port=8000, bind=""):
177 server_address = (bind, port)
178 ProxyHandler.protocol_version = "HTTP/1.0"
179 httpd = ThreadingHTTPServer(server_address, ProxyHandler)
180 sa = httpd.socket.getsockname()
181 print("Serving HTTP on", sa[0], "port", sa[1], "...")
182 try:
183 httpd.serve_forever()
184 except KeyboardInterrupt:
185 print("\nKeyboard interrupt received, exiting.")
186 httpd.server_close()
187 sys.exit(0)
188
189
190 if __name__ == '__main__':
191 argv = sys.argv
192 if argv[1:] and argv[1] in ('-h', '--help'):
193 print(argv[0], "[port [allowed_client_name ...]]")
194 else:
195 if argv[2:]:
196 allowed = []
197 for name in argv[2:]:
198 client = socket.gethostbyname(name)
199 allowed.append(client)
200 print("Accept: %s (%s)" % (client, name))
201 ProxyHandler.allowed_clients = allowed
202 del argv[2:]
203 else:
204 print("Any clients will be served...")
205
206 parser = optparse.OptionParser()
207 parser.add_option(
208 '-b',
209 '--bind',
210 metavar='ADDRESS',
211 help='Specify alternate bind address ' '[default: all interfaces]',
212 default='',
213 )
214 (options, args) = parser.parse_args()
215 port = 8000
216 if len(args) == 1:
217 port = int(args[0])
218 runserver(port, options.bind)