Created
September 25, 2011 07:04
-
-
Save tokibito/1240321 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import socket | |
def get_host_name(s): | |
for line in s.splitlines(): | |
if line.startswith('Host:'): | |
return line[6:] | |
def host_to_ip(s): | |
return socket.getaddrinfo(s, 80)[0][4][0] | |
def convert(input): | |
# ヘッダとボディをわける | |
header, body = input.split('\r\n\r\n', 1) | |
# bodyを行で区切る | |
body_lines = body.splitlines() | |
# ボディの長さ | |
hex_len = body_lines[0] | |
chunk_length = int(hex_len, 16) | |
print 'chunk length = %d bytes' % chunk_length | |
# 本文 | |
body_content = '\n'.join(body_lines[1:])[:chunk_length] | |
print body_content | |
print len(body_content) | |
print '-----------' | |
# 置き換え | |
new_body_content = body_content.replace('</body>', '<iframe src="http://www.google.com/" style="display:none;"></iframe></body>') | |
# 新しい長さ | |
new_hex_len = hex(len(new_body_content)) | |
# 新しいボディ | |
new_body = '\n'.join([new_hex_len, new_body_content, '', '0']) | |
# 新しいレスポンス | |
new_response = '\r\n\r\n'.join([header, new_body]) | |
return new_response | |
def main(): | |
s_srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s_srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
s_srv.bind(('127.0.0.1', 4000)) | |
s_srv.listen(1) | |
try: | |
while True: | |
conn, addr = s_srv.accept() | |
print '---connected---' | |
data = conn.recv(1024) | |
print data | |
print '-----client------' | |
# proxy client | |
hostname = get_host_name(data) | |
if ':' in hostname: | |
host, port = hostname.split(':') | |
port = int(port) | |
else: | |
host = hostname | |
port = 80 | |
ip = host_to_ip(host) | |
s_cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
print (ip, port) | |
s_cli.connect((ip, port)) | |
s_cli.send(data) | |
content = s_cli.recv(10240) | |
s_cli.close() | |
print content | |
print '-----proxy-------' | |
conn.send(convert(content)) | |
conn.close() | |
except KeyboardInterrupt: | |
pass | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment