http.py
1 import socket 2 3 from .advanceddispatcher import AdvancedDispatcher 4 from . import asyncore_pollchoose as asyncore 5 from .proxy import ProxyError 6 from .socks5 import Socks5Connection, Socks5Resolver 7 from .socks4a import Socks4aConnection, Socks4aResolver 8 9 10 class HttpError(ProxyError): 11 pass 12 13 14 class HttpConnection(AdvancedDispatcher): 15 def __init__(self, host, path="/"): # pylint: disable=redefined-outer-name 16 AdvancedDispatcher.__init__(self) 17 self.path = path 18 self.destination = (host, 80) 19 self.create_socket(socket.AF_INET, socket.SOCK_STREAM) 20 self.connect(self.destination) 21 print(("connecting in background to %s:%i" % self.destination)) 22 23 def state_init(self): 24 self.append_write_buf( 25 "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" % ( 26 self.path, self.destination[0])) 27 print(("Sending %ib" % len(self.write_buf))) 28 self.set_state("http_request_sent", 0) 29 return False 30 31 def state_http_request_sent(self): 32 if self.read_buf: 33 print(("Received %ib" % len(self.read_buf))) 34 self.read_buf = b"" 35 if not self.connected: 36 self.set_state("close", 0) 37 return False 38 39 40 class Socks5HttpConnection(Socks5Connection, HttpConnection): 41 def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name 42 self.path = path 43 Socks5Connection.__init__(self, address=(host, 80)) 44 45 def state_socks_handshake_done(self): 46 HttpConnection.state_init(self) 47 return False 48 49 50 class Socks4aHttpConnection(Socks4aConnection, HttpConnection): 51 def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name 52 Socks4aConnection.__init__(self, address=(host, 80)) 53 self.path = path 54 55 def state_socks_handshake_done(self): 56 HttpConnection.state_init(self) 57 return False 58 59 60 if __name__ == "__main__": 61 # initial fill 62 for host in ("bootstrap8080.bitmessage.org", "bootstrap8444.bitmessage.org"): 63 proxy = Socks5Resolver(host=host) 64 while asyncore.socket_map: 65 print(("loop %s, len %i" % (proxy.state, len(asyncore.socket_map)))) 66 asyncore.loop(timeout=1, count=1) 67 proxy.resolved() 68 69 proxy = Socks4aResolver(host=host) 70 while asyncore.socket_map: 71 print(("loop %s, len %i" % (proxy.state, len(asyncore.socket_map)))) 72 asyncore.loop(timeout=1, count=1) 73 proxy.resolved() 74 75 for host in ("bitmessage.org",): 76 direct = HttpConnection(host) 77 while asyncore.socket_map: 78 # print "loop, state = %s" % (direct.state) 79 asyncore.loop(timeout=1, count=1) 80 81 proxy = Socks5HttpConnection(host) 82 while asyncore.socket_map: 83 # print "loop, state = %s" % (proxy.state) 84 asyncore.loop(timeout=1, count=1) 85 86 proxy = Socks4aHttpConnection(host) 87 while asyncore.socket_map: 88 # print "loop, state = %s" % (proxy.state) 89 asyncore.loop(timeout=1, count=1)