proxy.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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 socket
  28. import ssl
  29. import sys
  30. import tornado.gen
  31. import tornado.httpclient
  32. import tornado.httpserver
  33. import tornado.ioloop
  34. import tornado.iostream
  35. import tornado.web
  36. __all__ = ["ProxyHandler", "run_proxy"]
  37. class ProxyHandler(tornado.web.RequestHandler):
  38. SUPPORTED_METHODS = ["GET", "POST", "CONNECT"]
  39. @tornado.gen.coroutine
  40. def get(self):
  41. def handle_response(response):
  42. if response.error and not isinstance(
  43. response.error, tornado.httpclient.HTTPError
  44. ):
  45. self.set_status(500)
  46. self.write("Internal server error:\n" + str(response.error))
  47. self.finish()
  48. else:
  49. self.set_status(response.code)
  50. for header in (
  51. "Date",
  52. "Cache-Control",
  53. "Server",
  54. "Content-Type",
  55. "Location",
  56. ):
  57. v = response.headers.get(header)
  58. if v:
  59. self.set_header(header, v)
  60. if response.body:
  61. self.write(response.body)
  62. self.finish()
  63. upstream_ca_certs = self.application.settings.get("upstream_ca_certs", None)
  64. ssl_options = None
  65. if upstream_ca_certs:
  66. ssl_options = ssl.create_default_context(cafile=upstream_ca_certs)
  67. req = tornado.httpclient.HTTPRequest(
  68. url=self.request.uri,
  69. method=self.request.method,
  70. body=self.request.body,
  71. headers=self.request.headers,
  72. follow_redirects=False,
  73. allow_nonstandard_methods=True,
  74. ssl_options=ssl_options,
  75. )
  76. client = tornado.httpclient.AsyncHTTPClient()
  77. try:
  78. response = yield client.fetch(req)
  79. yield handle_response(response)
  80. except tornado.httpclient.HTTPError as e:
  81. if hasattr(e, "response") and e.response:
  82. yield handle_response(e.response)
  83. else:
  84. self.set_status(500)
  85. self.write("Internal server error:\n" + str(e))
  86. self.finish()
  87. @tornado.gen.coroutine
  88. def post(self):
  89. yield self.get()
  90. @tornado.gen.coroutine
  91. def connect(self):
  92. host, port = self.request.uri.split(":")
  93. client = self.request.connection.stream
  94. @tornado.gen.coroutine
  95. def start_forward(reader, writer):
  96. while True:
  97. try:
  98. data = yield reader.read_bytes(4096, partial=True)
  99. except tornado.iostream.StreamClosedError:
  100. break
  101. if not data:
  102. break
  103. writer.write(data)
  104. writer.close()
  105. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  106. upstream = tornado.iostream.IOStream(s)
  107. yield upstream.connect((host, int(port)))
  108. client.write(b"HTTP/1.0 200 Connection established\r\n\r\n")
  109. fu1 = start_forward(client, upstream)
  110. fu2 = start_forward(upstream, client)
  111. yield [fu1, fu2]
  112. def run_proxy(port, start_ioloop=True):
  113. """
  114. Run proxy on the specified port. If start_ioloop is True (default),
  115. the tornado IOLoop will be started immediately.
  116. """
  117. app = tornado.web.Application([(r".*", ProxyHandler)])
  118. app.listen(port)
  119. ioloop = tornado.ioloop.IOLoop.instance()
  120. if start_ioloop:
  121. ioloop.start()
  122. if __name__ == "__main__":
  123. port = 8888
  124. if len(sys.argv) > 1:
  125. port = int(sys.argv[1])
  126. print("Starting HTTP proxy on port %d" % port)
  127. run_proxy(port)