httpserver.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2009 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """A non-blocking, single-threaded HTTP server.
  17. Typical applications have little direct interaction with the `HTTPServer`
  18. class except to start a server at the beginning of the process
  19. (and even that is often done indirectly via `tornado.web.Application.listen`).
  20. .. versionchanged:: 4.0
  21. The ``HTTPRequest`` class that used to live in this module has been moved
  22. to `tornado.httputil.HTTPServerRequest`. The old name remains as an alias.
  23. """
  24. from __future__ import absolute_import, division, print_function, with_statement
  25. import socket
  26. from tornado.escape import native_str
  27. from tornado.http1connection import HTTP1ServerConnection, HTTP1ConnectionParameters
  28. from tornado import gen
  29. from tornado import httputil
  30. from tornado import iostream
  31. from tornado import netutil
  32. from tornado.tcpserver import TCPServer
  33. from tornado.util import Configurable
  34. class HTTPServer(TCPServer, Configurable,
  35. httputil.HTTPServerConnectionDelegate):
  36. r"""A non-blocking, single-threaded HTTP server.
  37. A server is defined by a subclass of `.HTTPServerConnectionDelegate`,
  38. or, for backwards compatibility, a callback that takes an
  39. `.HTTPServerRequest` as an argument. The delegate is usually a
  40. `tornado.web.Application`.
  41. `HTTPServer` supports keep-alive connections by default
  42. (automatically for HTTP/1.1, or for HTTP/1.0 when the client
  43. requests ``Connection: keep-alive``).
  44. If ``xheaders`` is ``True``, we support the
  45. ``X-Real-Ip``/``X-Forwarded-For`` and
  46. ``X-Scheme``/``X-Forwarded-Proto`` headers, which override the
  47. remote IP and URI scheme/protocol for all requests. These headers
  48. are useful when running Tornado behind a reverse proxy or load
  49. balancer. The ``protocol`` argument can also be set to ``https``
  50. if Tornado is run behind an SSL-decoding proxy that does not set one of
  51. the supported ``xheaders``.
  52. To make this server serve SSL traffic, send the ``ssl_options`` keyword
  53. argument with an `ssl.SSLContext` object. For compatibility with older
  54. versions of Python ``ssl_options`` may also be a dictionary of keyword
  55. arguments for the `ssl.wrap_socket` method.::
  56. ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  57. ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"),
  58. os.path.join(data_dir, "mydomain.key"))
  59. HTTPServer(applicaton, ssl_options=ssl_ctx)
  60. `HTTPServer` initialization follows one of three patterns (the
  61. initialization methods are defined on `tornado.tcpserver.TCPServer`):
  62. 1. `~tornado.tcpserver.TCPServer.listen`: simple single-process::
  63. server = HTTPServer(app)
  64. server.listen(8888)
  65. IOLoop.current().start()
  66. In many cases, `tornado.web.Application.listen` can be used to avoid
  67. the need to explicitly create the `HTTPServer`.
  68. 2. `~tornado.tcpserver.TCPServer.bind`/`~tornado.tcpserver.TCPServer.start`:
  69. simple multi-process::
  70. server = HTTPServer(app)
  71. server.bind(8888)
  72. server.start(0) # Forks multiple sub-processes
  73. IOLoop.current().start()
  74. When using this interface, an `.IOLoop` must *not* be passed
  75. to the `HTTPServer` constructor. `~.TCPServer.start` will always start
  76. the server on the default singleton `.IOLoop`.
  77. 3. `~tornado.tcpserver.TCPServer.add_sockets`: advanced multi-process::
  78. sockets = tornado.netutil.bind_sockets(8888)
  79. tornado.process.fork_processes(0)
  80. server = HTTPServer(app)
  81. server.add_sockets(sockets)
  82. IOLoop.current().start()
  83. The `~.TCPServer.add_sockets` interface is more complicated,
  84. but it can be used with `tornado.process.fork_processes` to
  85. give you more flexibility in when the fork happens.
  86. `~.TCPServer.add_sockets` can also be used in single-process
  87. servers if you want to create your listening sockets in some
  88. way other than `tornado.netutil.bind_sockets`.
  89. .. versionchanged:: 4.0
  90. Added ``decompress_request``, ``chunk_size``, ``max_header_size``,
  91. ``idle_connection_timeout``, ``body_timeout``, ``max_body_size``
  92. arguments. Added support for `.HTTPServerConnectionDelegate`
  93. instances as ``request_callback``.
  94. .. versionchanged:: 4.1
  95. `.HTTPServerConnectionDelegate.start_request` is now called with
  96. two arguments ``(server_conn, request_conn)`` (in accordance with the
  97. documentation) instead of one ``(request_conn)``.
  98. .. versionchanged:: 4.2
  99. `HTTPServer` is now a subclass of `tornado.util.Configurable`.
  100. """
  101. def __init__(self, *args, **kwargs):
  102. # Ignore args to __init__; real initialization belongs in
  103. # initialize since we're Configurable. (there's something
  104. # weird in initialization order between this class,
  105. # Configurable, and TCPServer so we can't leave __init__ out
  106. # completely)
  107. pass
  108. def initialize(self, request_callback, no_keep_alive=False, io_loop=None,
  109. xheaders=False, ssl_options=None, protocol=None,
  110. decompress_request=False,
  111. chunk_size=None, max_header_size=None,
  112. idle_connection_timeout=None, body_timeout=None,
  113. max_body_size=None, max_buffer_size=None):
  114. self.request_callback = request_callback
  115. self.no_keep_alive = no_keep_alive
  116. self.xheaders = xheaders
  117. self.protocol = protocol
  118. self.conn_params = HTTP1ConnectionParameters(
  119. decompress=decompress_request,
  120. chunk_size=chunk_size,
  121. max_header_size=max_header_size,
  122. header_timeout=idle_connection_timeout or 3600,
  123. max_body_size=max_body_size,
  124. body_timeout=body_timeout)
  125. TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options,
  126. max_buffer_size=max_buffer_size,
  127. read_chunk_size=chunk_size)
  128. self._connections = set()
  129. @classmethod
  130. def configurable_base(cls):
  131. return HTTPServer
  132. @classmethod
  133. def configurable_default(cls):
  134. return HTTPServer
  135. @gen.coroutine
  136. def close_all_connections(self):
  137. while self._connections:
  138. # Peek at an arbitrary element of the set
  139. conn = next(iter(self._connections))
  140. yield conn.close()
  141. def handle_stream(self, stream, address):
  142. context = _HTTPRequestContext(stream, address,
  143. self.protocol)
  144. conn = HTTP1ServerConnection(
  145. stream, self.conn_params, context)
  146. self._connections.add(conn)
  147. conn.start_serving(self)
  148. def start_request(self, server_conn, request_conn):
  149. return _ServerRequestAdapter(self, server_conn, request_conn)
  150. def on_close(self, server_conn):
  151. self._connections.remove(server_conn)
  152. class _HTTPRequestContext(object):
  153. def __init__(self, stream, address, protocol):
  154. self.address = address
  155. # Save the socket's address family now so we know how to
  156. # interpret self.address even after the stream is closed
  157. # and its socket attribute replaced with None.
  158. if stream.socket is not None:
  159. self.address_family = stream.socket.family
  160. else:
  161. self.address_family = None
  162. # In HTTPServerRequest we want an IP, not a full socket address.
  163. if (self.address_family in (socket.AF_INET, socket.AF_INET6) and
  164. address is not None):
  165. self.remote_ip = address[0]
  166. else:
  167. # Unix (or other) socket; fake the remote address.
  168. self.remote_ip = '0.0.0.0'
  169. if protocol:
  170. self.protocol = protocol
  171. elif isinstance(stream, iostream.SSLIOStream):
  172. self.protocol = "https"
  173. else:
  174. self.protocol = "http"
  175. self._orig_remote_ip = self.remote_ip
  176. self._orig_protocol = self.protocol
  177. def __str__(self):
  178. if self.address_family in (socket.AF_INET, socket.AF_INET6):
  179. return self.remote_ip
  180. elif isinstance(self.address, bytes):
  181. # Python 3 with the -bb option warns about str(bytes),
  182. # so convert it explicitly.
  183. # Unix socket addresses are str on mac but bytes on linux.
  184. return native_str(self.address)
  185. else:
  186. return str(self.address)
  187. def _apply_xheaders(self, headers):
  188. """Rewrite the ``remote_ip`` and ``protocol`` fields."""
  189. # Squid uses X-Forwarded-For, others use X-Real-Ip
  190. ip = headers.get("X-Forwarded-For", self.remote_ip)
  191. ip = ip.split(',')[-1].strip()
  192. ip = headers.get("X-Real-Ip", ip)
  193. if netutil.is_valid_ip(ip):
  194. self.remote_ip = ip
  195. # AWS uses X-Forwarded-Proto
  196. proto_header = headers.get(
  197. "X-Scheme", headers.get("X-Forwarded-Proto",
  198. self.protocol))
  199. if proto_header in ("http", "https"):
  200. self.protocol = proto_header
  201. def _unapply_xheaders(self):
  202. """Undo changes from `_apply_xheaders`.
  203. Xheaders are per-request so they should not leak to the next
  204. request on the same connection.
  205. """
  206. self.remote_ip = self._orig_remote_ip
  207. self.protocol = self._orig_protocol
  208. class _ServerRequestAdapter(httputil.HTTPMessageDelegate):
  209. """Adapts the `HTTPMessageDelegate` interface to the interface expected
  210. by our clients.
  211. """
  212. def __init__(self, server, server_conn, request_conn):
  213. self.server = server
  214. self.connection = request_conn
  215. self.request = None
  216. if isinstance(server.request_callback,
  217. httputil.HTTPServerConnectionDelegate):
  218. self.delegate = server.request_callback.start_request(
  219. server_conn, request_conn)
  220. self._chunks = None
  221. else:
  222. self.delegate = None
  223. self._chunks = []
  224. def headers_received(self, start_line, headers):
  225. if self.server.xheaders:
  226. self.connection.context._apply_xheaders(headers)
  227. if self.delegate is None:
  228. self.request = httputil.HTTPServerRequest(
  229. connection=self.connection, start_line=start_line,
  230. headers=headers)
  231. else:
  232. return self.delegate.headers_received(start_line, headers)
  233. def data_received(self, chunk):
  234. if self.delegate is None:
  235. self._chunks.append(chunk)
  236. else:
  237. return self.delegate.data_received(chunk)
  238. def finish(self):
  239. if self.delegate is None:
  240. self.request.body = b''.join(self._chunks)
  241. self.request._parse_body()
  242. self.server.request_callback(self.request)
  243. else:
  244. self.delegate.finish()
  245. self._cleanup()
  246. def on_connection_close(self):
  247. if self.delegate is None:
  248. self._chunks = None
  249. else:
  250. self.delegate.on_connection_close()
  251. self._cleanup()
  252. def _cleanup(self):
  253. if self.server.xheaders:
  254. self.connection.context._unapply_xheaders()
  255. HTTPRequest = httputil.HTTPServerRequest