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