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 return uri
[uri
.find('//') + 2:uri
.rfind('/')]
21 for line
in self
.header
.split('\n'):
22 if line
.startswith('Connection') and line
.find('close') != -1:
29 def __init__(self
, header
, body
):
32 self
.message
= self
.header
34 self
.message
+= self
.body
38 def __read_header(self
, sock
):
56 def __get_content_length(self
, header
):
57 for line
in header
.split('\n'):
58 if line
.startswith('Content-Length'):
59 return int(line
[line
.find(' '):])
62 def __read_body(self
, header
, sock
):
64 len = self
.__get
_content
_length
(header
)
69 def __read_message(self
, sock
):
70 header
= self
.__read
_header
(sock
)
73 body
= self
.__read
_body
(header
, sock
)
74 return HttpMessage(header
, body
)
76 def __create_proxy_sock(self
, domain
, port
):
77 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
78 s
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
, 1)
79 s
.bind((domain
, port
))
83 def __server_connect(self
, server
, port
):
84 ssock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
85 ssock
.connect((server
, port
))
91 (csock
, addr
) = self
.sock
.accept()
92 req
= self
.__read
_message
(csock
)
95 ssock
= self
.__server
_connect
(req
.get_server(), 80)
96 ssock
.sendall(req
.message
)
97 resp
= self
.__read
_message
(ssock
)
102 csock
.sendall(resp
.message
)
103 req
= self
.__read
_message
(csock
)
104 if resp
.conn_close():
109 def __init__(self
, domain
, port
):
110 self
.sock
= self
.__create
_proxy
_sock
(domain
, port
)
114 print 'tiny-http-proxy <domain> <port>'
117 server
= TinyHttpProxy(argv
[1], int(argv
[2]))
120 if __name__
== '__main__':