Implementing HTTP proxies with tornado

Source: Internet
Author: User
0x00 HTTP Proxy

HTTP proxy is very useful, there are open agents, but sometimes for work needs, such as analysis of application layer traffic, Do data access control, and even do monitoring and so on. Tornado provides a number of convenient environments and APIs, and we can easily implement an HTTP proxy based on tornado. 0x01 Realization Principle

The HTTP proxy mainly does the forwarding between the client and the Web server, which is familiar to the scene, but only to the HTTP protocol situation. For HTTPS, the proxy is only relayed as a TCP relay and needs to be handled separately.
0x02 Tornado Implementation

Based on tornado can implement an asynchronous HTTP proxy, superior performance, implementation is also simple, the main use of the class is Asynchttpclient,iostream. Students who have read the tornado source code may not be unfamiliar with these two classes. Here or simply, Asynchttpclient, as the name suggests, is used to do asynchronous HTTP client requests, and iostream is a layer of socket encapsulation.
Asynchttpclient is used to handle ordinary HTTP requests, RequestHandler after obtaining the client request, the proxy needs to parse the client's request and use this class to request the server, get response, then write to the client and finish the call.
For a proxy as a TCP relay, you can actually use the original socket two to read and write data, but too much trouble. Tornado provides a iostream class, which can be seen as the wrapper class for the socket, which is much simpler to use than the socket, and the socket is asynchronous and non-blocking.
Talk is cheap, show me the code, not to say, look at the codes well, here for some reason, I can only post the key parts of the code, I hope that reading this article students can write their own to use, in fact, it is not difficult. Processing HTTP Requests

 @tornado. Web.asynchronous def get (self): # getting request BODY = Self.request.body
                    If not body:body = None Try: # Proxy send Request Render_request (
                    Self.request.uri, Callback=self.on_response, Method=self.request.method, Body=body, Headers=self.request.headers, Follow_redirects=false
            , allow_nonstandard_methods=true) except Tornado.httpclient.HTTPError as Httperror:
            If Hasattr (httperror, ' response ') and Httperror.response:self.on_response (Httperror.response)
                Else:self.set_status (Self.write) (' Internal server error:\n ' + str (httperror)) Self.finish () 

There is nothing to say, received the client request, directly to request the server on the line. The asynchronous callback function is On_response, which handles proxy and client interaction, Self.write (Response.body) you know.
Here is a hole, that is, when writing headers, the response of the headers copy of the set is a mistake, resulting in access failure. My approach here is to write only the head of the self._headers presence in the RequestHandler. TCP Relay Implementation

For 443-port or browser connect request, the agent can only start from the TCP layer, forwarding the entire HTTP message, here is used in the HTTP protocol connect method, in the RequestHandler to implement this method on the line.
Note here that tornado does not support the HTTP Connect method by default, so modify the Supported_methods parameter to do so:

Here, add a supported_methods in RequestHandler to replace the parent class:

Supported_methods.append (' CONNECT ')

By the way, connect method, this method is called, the agent does not need to have the content of the HTTP layer request, but directly from the TCP layer forward this message to the server. When received, the same is forwarded to the client.

CONNECT www.web-tinker.com:80 http/1.1
host:www.web-tinker.com:80
proxy-connection:keep-alive
Proxy-authorization:basic *
content-length:0

The code for the implementation is as follows:

    @tornado. Web.asynchronous def Connect (self): ' For HTTPS connections, the proxy should act as a TCP relay ' def req _close (data): If Conn_stream.closed (): Return ELSE:CONN_STREAM.WR
            ITE (data) def write_to_server (data): Conn_stream.write (data) def proxy_close (data): If req_stream.closed (): Return Else:req_stream.close (data) def W 
            Rite_to_client (data): Req_stream.write (data) def on_connect (): "" To create a callback for a TCP relay "" Req_stream.read_until_close (Req_close, Write_to_server) conn_stream.read_until_cl OSE (Proxy_close, write_to_client) req_stream.write (b ' http/1.0 Connection ') pr int ' starting Conntect to%s '% Self.request.uri # get the socket req_stream of request = Self.request.connection.s Tream # Find the host port,Generally 443 host, Port = (None, 443) Netloc = Self.request.uri.split (': ') If Len (netloc) = = 2: Host, port = Netloc elif len (netloc) = = 1:host = netloc[0] # create iostream s = Sock Et.socket (socket.af_inet, socket. Sock_stream, 0) Conn_stream = Tornado.iostream.IOStream (s) conn_stream.connect (host, port, On_connect)

I explain these two sentences:

Req_stream.read_until_close (Req_close, Write_to_server)
conn_stream.read_until_close (Proxy_close, Write_to_ Client

Just two lines of code, plus 4 callback functions, completes the data relay.
First, Req_stream is the socket between proxy and client, which can be created by httprequest the socket between the corresponding iostream,proxy and the server, this is Conn_stream.
The Read_until_close method is provided in iostream to read the data until the socket is closed.
The first line reads the data from the socket between the client and the proxy, reads it, writes it to the socket between the proxy and the server, and forwards it by proxy.
The second line of the function is to write the server data to the client socket, and as above, there is nothing to say, write function in four callback functions.
Some people wonder why Read_until_close has two callback functions, and my understanding is that the first callback is invoked at shutdown time, and the second callback is invoked when the data is read.
Write to use the effect is also OK:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.