7 # - Doesn't understand chunked data
8 # - Try: www.wikipedia.org
10 # Luiz Capitulino <lcapitulino@gmail.com>
13 from sys
import argv
, exit
, stderr
17 uri
= self
.header
.split()[1]
18 sub
= uri
[uri
.find('//') + 2:]
19 return sub
[:sub
.find('/')]
22 for line
in self
.header
.split('\n'):
23 if line
.startswith('Connection') and line
.find('close') != -1:
30 def __init__(self
, header
, body
):
33 self
.message
= self
.header
35 self
.message
+= self
.body
39 def __read_header(self
, sock
):
57 def __get_content_length(self
, header
):
58 for line
in header
.split('\n'):
59 if line
.startswith('Content-Length'):
60 return int(line
[line
.find(' '):])
63 def __read_body(self
, header
, sock
):
65 len = self
.__get
_content
_length
(header
)
70 def __read_message(self
, sock
):
71 header
= self
.__read
_header
(sock
)
74 body
= self
.__read
_body
(header
, sock
)
75 return HttpMessage(header
, body
)
77 def __create_proxy_sock(self
, domain
, port
):
78 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
79 s
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
, 1)
80 s
.bind((domain
, port
))
84 def __server_connect(self
, server
, port
):
85 ssock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
86 ssock
.connect((server
, port
))
92 (csock
, addr
) = self
.sock
.accept()
93 req
= self
.__read
_message
(csock
)
96 ssock
= self
.__server
_connect
(req
.get_server(), 80)
97 ssock
.sendall(req
.message
)
98 resp
= self
.__read
_message
(ssock
)
103 csock
.sendall(resp
.message
)
104 req
= self
.__read
_message
(csock
)
105 if resp
.conn_close():
110 def __init__(self
, domain
, port
):
111 self
.sock
= self
.__create
_proxy
_sock
(domain
, port
)
115 print 'tiny-http-proxy <domain> <port>'
118 server
= TinyHttpProxy(argv
[1], int(argv
[2]))
121 if __name__
== '__main__':