##// END OF EJS Templates
tests: sort import lines in tinyproxy.py
Yuya Nishihara -
r28773:0023a6e1 default
parent child Browse files
Show More
@@ -1,157 +1,157 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
2
3 from __future__ import absolute_import, print_function
3 from __future__ import absolute_import, print_function
4
4
5 __doc__ = """Tiny HTTP Proxy.
5 __doc__ = """Tiny HTTP Proxy.
6
6
7 This module implements GET, HEAD, POST, PUT and DELETE methods
7 This module implements GET, HEAD, POST, PUT and DELETE methods
8 on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT
8 on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT
9 method is also implemented experimentally, but has not been
9 method is also implemented experimentally, but has not been
10 tested yet.
10 tested yet.
11
11
12 Any help will be greatly appreciated. SUZUKI Hisao
12 Any help will be greatly appreciated. SUZUKI Hisao
13 """
13 """
14
14
15 __version__ = "0.2.1"
15 __version__ = "0.2.1"
16
16
17 import BaseHTTPServer
17 import BaseHTTPServer
18 import SocketServer
18 import os
19 import os
19 import select
20 import select
20 import socket
21 import socket
21 import SocketServer
22 import urlparse
22 import urlparse
23
23
24 class ProxyHandler (BaseHTTPServer.BaseHTTPRequestHandler):
24 class ProxyHandler (BaseHTTPServer.BaseHTTPRequestHandler):
25 __base = BaseHTTPServer.BaseHTTPRequestHandler
25 __base = BaseHTTPServer.BaseHTTPRequestHandler
26 __base_handle = __base.handle
26 __base_handle = __base.handle
27
27
28 server_version = "TinyHTTPProxy/" + __version__
28 server_version = "TinyHTTPProxy/" + __version__
29 rbufsize = 0 # self.rfile Be unbuffered
29 rbufsize = 0 # self.rfile Be unbuffered
30
30
31 def handle(self):
31 def handle(self):
32 (ip, port) = self.client_address
32 (ip, port) = self.client_address
33 allowed = getattr(self, 'allowed_clients', None)
33 allowed = getattr(self, 'allowed_clients', None)
34 if allowed is not None and ip not in allowed:
34 if allowed is not None and ip not in allowed:
35 self.raw_requestline = self.rfile.readline()
35 self.raw_requestline = self.rfile.readline()
36 if self.parse_request():
36 if self.parse_request():
37 self.send_error(403)
37 self.send_error(403)
38 else:
38 else:
39 self.__base_handle()
39 self.__base_handle()
40
40
41 def log_request(self, code='-', size='-'):
41 def log_request(self, code='-', size='-'):
42 xheaders = [h for h in self.headers.items() if h[0].startswith('x-')]
42 xheaders = [h for h in self.headers.items() if h[0].startswith('x-')]
43 self.log_message('"%s" %s %s%s',
43 self.log_message('"%s" %s %s%s',
44 self.requestline, str(code), str(size),
44 self.requestline, str(code), str(size),
45 ''.join([' %s:%s' % h for h in sorted(xheaders)]))
45 ''.join([' %s:%s' % h for h in sorted(xheaders)]))
46
46
47 def _connect_to(self, netloc, soc):
47 def _connect_to(self, netloc, soc):
48 i = netloc.find(':')
48 i = netloc.find(':')
49 if i >= 0:
49 if i >= 0:
50 host_port = netloc[:i], int(netloc[i + 1:])
50 host_port = netloc[:i], int(netloc[i + 1:])
51 else:
51 else:
52 host_port = netloc, 80
52 host_port = netloc, 80
53 print("\t" "connect to %s:%d" % host_port)
53 print("\t" "connect to %s:%d" % host_port)
54 try: soc.connect(host_port)
54 try: soc.connect(host_port)
55 except socket.error as arg:
55 except socket.error as arg:
56 try: msg = arg[1]
56 try: msg = arg[1]
57 except (IndexError, TypeError): msg = arg
57 except (IndexError, TypeError): msg = arg
58 self.send_error(404, msg)
58 self.send_error(404, msg)
59 return 0
59 return 0
60 return 1
60 return 1
61
61
62 def do_CONNECT(self):
62 def do_CONNECT(self):
63 soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
63 soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
64 try:
64 try:
65 if self._connect_to(self.path, soc):
65 if self._connect_to(self.path, soc):
66 self.log_request(200)
66 self.log_request(200)
67 self.wfile.write(self.protocol_version +
67 self.wfile.write(self.protocol_version +
68 " 200 Connection established\r\n")
68 " 200 Connection established\r\n")
69 self.wfile.write("Proxy-agent: %s\r\n" % self.version_string())
69 self.wfile.write("Proxy-agent: %s\r\n" % self.version_string())
70 self.wfile.write("\r\n")
70 self.wfile.write("\r\n")
71 self._read_write(soc, 300)
71 self._read_write(soc, 300)
72 finally:
72 finally:
73 print("\t" "bye")
73 print("\t" "bye")
74 soc.close()
74 soc.close()
75 self.connection.close()
75 self.connection.close()
76
76
77 def do_GET(self):
77 def do_GET(self):
78 (scm, netloc, path, params, query, fragment) = urlparse.urlparse(
78 (scm, netloc, path, params, query, fragment) = urlparse.urlparse(
79 self.path, 'http')
79 self.path, 'http')
80 if scm != 'http' or fragment or not netloc:
80 if scm != 'http' or fragment or not netloc:
81 self.send_error(400, "bad url %s" % self.path)
81 self.send_error(400, "bad url %s" % self.path)
82 return
82 return
83 soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
83 soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
84 try:
84 try:
85 if self._connect_to(netloc, soc):
85 if self._connect_to(netloc, soc):
86 self.log_request()
86 self.log_request()
87 soc.send("%s %s %s\r\n" % (
87 soc.send("%s %s %s\r\n" % (
88 self.command,
88 self.command,
89 urlparse.urlunparse(('', '', path, params, query, '')),
89 urlparse.urlunparse(('', '', path, params, query, '')),
90 self.request_version))
90 self.request_version))
91 self.headers['Connection'] = 'close'
91 self.headers['Connection'] = 'close'
92 del self.headers['Proxy-Connection']
92 del self.headers['Proxy-Connection']
93 for key_val in self.headers.items():
93 for key_val in self.headers.items():
94 soc.send("%s: %s\r\n" % key_val)
94 soc.send("%s: %s\r\n" % key_val)
95 soc.send("\r\n")
95 soc.send("\r\n")
96 self._read_write(soc)
96 self._read_write(soc)
97 finally:
97 finally:
98 print("\t" "bye")
98 print("\t" "bye")
99 soc.close()
99 soc.close()
100 self.connection.close()
100 self.connection.close()
101
101
102 def _read_write(self, soc, max_idling=20):
102 def _read_write(self, soc, max_idling=20):
103 iw = [self.connection, soc]
103 iw = [self.connection, soc]
104 ow = []
104 ow = []
105 count = 0
105 count = 0
106 while True:
106 while True:
107 count += 1
107 count += 1
108 (ins, _, exs) = select.select(iw, ow, iw, 3)
108 (ins, _, exs) = select.select(iw, ow, iw, 3)
109 if exs:
109 if exs:
110 break
110 break
111 if ins:
111 if ins:
112 for i in ins:
112 for i in ins:
113 if i is soc:
113 if i is soc:
114 out = self.connection
114 out = self.connection
115 else:
115 else:
116 out = soc
116 out = soc
117 try:
117 try:
118 data = i.recv(8192)
118 data = i.recv(8192)
119 except socket.error:
119 except socket.error:
120 break
120 break
121 if data:
121 if data:
122 out.send(data)
122 out.send(data)
123 count = 0
123 count = 0
124 else:
124 else:
125 print("\t" "idle", count)
125 print("\t" "idle", count)
126 if count == max_idling:
126 if count == max_idling:
127 break
127 break
128
128
129 do_HEAD = do_GET
129 do_HEAD = do_GET
130 do_POST = do_GET
130 do_POST = do_GET
131 do_PUT = do_GET
131 do_PUT = do_GET
132 do_DELETE = do_GET
132 do_DELETE = do_GET
133
133
134 class ThreadingHTTPServer (SocketServer.ThreadingMixIn,
134 class ThreadingHTTPServer (SocketServer.ThreadingMixIn,
135 BaseHTTPServer.HTTPServer):
135 BaseHTTPServer.HTTPServer):
136 def __init__(self, *args, **kwargs):
136 def __init__(self, *args, **kwargs):
137 BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)
137 BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)
138 a = open("proxy.pid", "w")
138 a = open("proxy.pid", "w")
139 a.write(str(os.getpid()) + "\n")
139 a.write(str(os.getpid()) + "\n")
140 a.close()
140 a.close()
141
141
142 if __name__ == '__main__':
142 if __name__ == '__main__':
143 from sys import argv
143 from sys import argv
144 if argv[1:] and argv[1] in ('-h', '--help'):
144 if argv[1:] and argv[1] in ('-h', '--help'):
145 print(argv[0], "[port [allowed_client_name ...]]")
145 print(argv[0], "[port [allowed_client_name ...]]")
146 else:
146 else:
147 if argv[2:]:
147 if argv[2:]:
148 allowed = []
148 allowed = []
149 for name in argv[2:]:
149 for name in argv[2:]:
150 client = socket.gethostbyname(name)
150 client = socket.gethostbyname(name)
151 allowed.append(client)
151 allowed.append(client)
152 print("Accept: %s (%s)" % (client, name))
152 print("Accept: %s (%s)" % (client, name))
153 ProxyHandler.allowed_clients = allowed
153 ProxyHandler.allowed_clients = allowed
154 del argv[2:]
154 del argv[2:]
155 else:
155 else:
156 print("Any clients will be served...")
156 print("Any clients will be served...")
157 BaseHTTPServer.test(ProxyHandler, ThreadingHTTPServer)
157 BaseHTTPServer.test(ProxyHandler, ThreadingHTTPServer)
General Comments 0
You need to be logged in to leave comments. Login now