proxy.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. #!/usr/bin/env python
  2. #
  3. # Simple asynchronous HTTP proxy with tunnelling (CONNECT).
  4. #
  5. # GET/POST proxying based on
  6. # http://groups.google.com/group/python-tornado/msg/7bea08e7a049cf26
  7. #
  8. # Copyright (C) 2012 Senko Rasic <senko.rasic@dobarkod.hr>
  9. #
  10. # Permission is hereby granted, free of charge, to any person obtaining a copy
  11. # of this software and associated documentation files (the "Software"), to deal
  12. # in the Software without restriction, including without limitation the rights
  13. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. # copies of the Software, and to permit persons to whom the Software is
  15. # furnished to do so, subject to the following conditions:
  16. #
  17. # The above copyright notice and this permission notice shall be included in
  18. # all copies or substantial portions of the Software.
  19. #
  20. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. # THE SOFTWARE.
  27. import sys
  28. import socket
  29. import tornado.httpserver
  30. import tornado.ioloop
  31. import tornado.iostream
  32. import tornado.web
  33. import tornado.httpclient
  34. __all__ = ['ProxyHandler', 'run_proxy']
  35. class ProxyHandler(tornado.web.RequestHandler):
  36. SUPPORTED_METHODS = ['GET', 'POST', 'CONNECT']
  37. @tornado.web.asynchronous
  38. def get(self):
  39. def handle_response(response):
  40. if response.error and not isinstance(response.error,
  41. tornado.httpclient.HTTPError):
  42. self.set_status(500)
  43. self.write('Internal server error:\n' + str(response.error))
  44. self.finish()
  45. else:
  46. self.set_status(response.code)
  47. for header in ('Date', 'Cache-Control', 'Server',
  48. 'Content-Type', 'Location'):
  49. v = response.headers.get(header)
  50. if v:
  51. self.set_header(header, v)
  52. if response.body:
  53. self.write(response.body)
  54. self.finish()
  55. req = tornado.httpclient.HTTPRequest(
  56. url=self.request.uri,
  57. method=self.request.method, body=self.request.body,
  58. headers=self.request.headers, follow_redirects=False,
  59. allow_nonstandard_methods=True)
  60. client = tornado.httpclient.AsyncHTTPClient()
  61. try:
  62. client.fetch(req, handle_response)
  63. except tornado.httpclient.HTTPError as e:
  64. if hasattr(e, 'response') and e.response:
  65. self.handle_response(e.response)
  66. else:
  67. self.set_status(500)
  68. self.write('Internal server error:\n' + str(e))
  69. self.finish()
  70. @tornado.web.asynchronous
  71. def post(self):
  72. return self.get()
  73. @tornado.web.asynchronous
  74. def connect(self):
  75. host, port = self.request.uri.split(':')
  76. client = self.request.connection.stream
  77. def read_from_client(data):
  78. upstream.write(data)
  79. def read_from_upstream(data):
  80. client.write(data)
  81. def client_close(data=None):
  82. if upstream.closed():
  83. return
  84. if data:
  85. upstream.write(data)
  86. upstream.close()
  87. def upstream_close(data=None):
  88. if client.closed():
  89. return
  90. if data:
  91. client.write(data)
  92. client.close()
  93. def start_tunnel():
  94. client.read_until_close(client_close, read_from_client)
  95. upstream.read_until_close(upstream_close, read_from_upstream)
  96. client.write(b'HTTP/1.0 200 Connection established\r\n\r\n')
  97. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  98. upstream = tornado.iostream.IOStream(s)
  99. upstream.connect((host, int(port)), start_tunnel)
  100. def run_proxy(port, start_ioloop=True):
  101. """
  102. Run proxy on the specified port. If start_ioloop is True (default),
  103. the tornado IOLoop will be started immediately.
  104. """
  105. app = tornado.web.Application([
  106. (r'.*', ProxyHandler),
  107. ])
  108. app.listen(port)
  109. ioloop = tornado.ioloop.IOLoop.instance()
  110. if start_ioloop:
  111. ioloop.start()
  112. if __name__ == '__main__':
  113. port = 8888
  114. if len(sys.argv) > 1:
  115. port = int(sys.argv[1])
  116. print("Starting HTTP proxy on port %d" % port)
  117. run_proxy(port)