tcpserver.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. #
  2. # Copyright 2011 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """A non-blocking, single-threaded TCP server."""
  16. import errno
  17. import os
  18. import socket
  19. import ssl
  20. from tornado import gen
  21. from tornado.log import app_log
  22. from tornado.ioloop import IOLoop
  23. from tornado.iostream import IOStream, SSLIOStream
  24. from tornado.netutil import bind_sockets, add_accept_handler, ssl_wrap_socket
  25. from tornado import process
  26. from tornado.util import errno_from_exception
  27. import typing
  28. from typing import Union, Dict, Any, Iterable, Optional, Awaitable
  29. if typing.TYPE_CHECKING:
  30. from typing import Callable, List # noqa: F401
  31. class TCPServer(object):
  32. r"""A non-blocking, single-threaded TCP server.
  33. To use `TCPServer`, define a subclass which overrides the `handle_stream`
  34. method. For example, a simple echo server could be defined like this::
  35. from tornado.tcpserver import TCPServer
  36. from tornado.iostream import StreamClosedError
  37. from tornado import gen
  38. class EchoServer(TCPServer):
  39. async def handle_stream(self, stream, address):
  40. while True:
  41. try:
  42. data = await stream.read_until(b"\n")
  43. await stream.write(data)
  44. except StreamClosedError:
  45. break
  46. To make this server serve SSL traffic, send the ``ssl_options`` keyword
  47. argument with an `ssl.SSLContext` object. For compatibility with older
  48. versions of Python ``ssl_options`` may also be a dictionary of keyword
  49. arguments for the `ssl.wrap_socket` method.::
  50. ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  51. ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"),
  52. os.path.join(data_dir, "mydomain.key"))
  53. TCPServer(ssl_options=ssl_ctx)
  54. `TCPServer` initialization follows one of three patterns:
  55. 1. `listen`: simple single-process::
  56. server = TCPServer()
  57. server.listen(8888)
  58. IOLoop.current().start()
  59. 2. `bind`/`start`: simple multi-process::
  60. server = TCPServer()
  61. server.bind(8888)
  62. server.start(0) # Forks multiple sub-processes
  63. IOLoop.current().start()
  64. When using this interface, an `.IOLoop` must *not* be passed
  65. to the `TCPServer` constructor. `start` will always start
  66. the server on the default singleton `.IOLoop`.
  67. 3. `add_sockets`: advanced multi-process::
  68. sockets = bind_sockets(8888)
  69. tornado.process.fork_processes(0)
  70. server = TCPServer()
  71. server.add_sockets(sockets)
  72. IOLoop.current().start()
  73. The `add_sockets` interface is more complicated, but it can be
  74. used with `tornado.process.fork_processes` to give you more
  75. flexibility in when the fork happens. `add_sockets` can
  76. also be used in single-process servers if you want to create
  77. your listening sockets in some way other than
  78. `~tornado.netutil.bind_sockets`.
  79. .. versionadded:: 3.1
  80. The ``max_buffer_size`` argument.
  81. .. versionchanged:: 5.0
  82. The ``io_loop`` argument has been removed.
  83. """
  84. def __init__(
  85. self,
  86. ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None,
  87. max_buffer_size: int = None,
  88. read_chunk_size: int = None,
  89. ) -> None:
  90. self.ssl_options = ssl_options
  91. self._sockets = {} # type: Dict[int, socket.socket]
  92. self._handlers = {} # type: Dict[int, Callable[[], None]]
  93. self._pending_sockets = [] # type: List[socket.socket]
  94. self._started = False
  95. self._stopped = False
  96. self.max_buffer_size = max_buffer_size
  97. self.read_chunk_size = read_chunk_size
  98. # Verify the SSL options. Otherwise we don't get errors until clients
  99. # connect. This doesn't verify that the keys are legitimate, but
  100. # the SSL module doesn't do that until there is a connected socket
  101. # which seems like too much work
  102. if self.ssl_options is not None and isinstance(self.ssl_options, dict):
  103. # Only certfile is required: it can contain both keys
  104. if "certfile" not in self.ssl_options:
  105. raise KeyError('missing key "certfile" in ssl_options')
  106. if not os.path.exists(self.ssl_options["certfile"]):
  107. raise ValueError(
  108. 'certfile "%s" does not exist' % self.ssl_options["certfile"]
  109. )
  110. if "keyfile" in self.ssl_options and not os.path.exists(
  111. self.ssl_options["keyfile"]
  112. ):
  113. raise ValueError(
  114. 'keyfile "%s" does not exist' % self.ssl_options["keyfile"]
  115. )
  116. def listen(self, port: int, address: str = "") -> None:
  117. """Starts accepting connections on the given port.
  118. This method may be called more than once to listen on multiple ports.
  119. `listen` takes effect immediately; it is not necessary to call
  120. `TCPServer.start` afterwards. It is, however, necessary to start
  121. the `.IOLoop`.
  122. """
  123. sockets = bind_sockets(port, address=address)
  124. self.add_sockets(sockets)
  125. def add_sockets(self, sockets: Iterable[socket.socket]) -> None:
  126. """Makes this server start accepting connections on the given sockets.
  127. The ``sockets`` parameter is a list of socket objects such as
  128. those returned by `~tornado.netutil.bind_sockets`.
  129. `add_sockets` is typically used in combination with that
  130. method and `tornado.process.fork_processes` to provide greater
  131. control over the initialization of a multi-process server.
  132. """
  133. for sock in sockets:
  134. self._sockets[sock.fileno()] = sock
  135. self._handlers[sock.fileno()] = add_accept_handler(
  136. sock, self._handle_connection
  137. )
  138. def add_socket(self, socket: socket.socket) -> None:
  139. """Singular version of `add_sockets`. Takes a single socket object."""
  140. self.add_sockets([socket])
  141. def bind(
  142. self,
  143. port: int,
  144. address: str = None,
  145. family: socket.AddressFamily = socket.AF_UNSPEC,
  146. backlog: int = 128,
  147. reuse_port: bool = False,
  148. ) -> None:
  149. """Binds this server to the given port on the given address.
  150. To start the server, call `start`. If you want to run this server
  151. in a single process, you can call `listen` as a shortcut to the
  152. sequence of `bind` and `start` calls.
  153. Address may be either an IP address or hostname. If it's a hostname,
  154. the server will listen on all IP addresses associated with the
  155. name. Address may be an empty string or None to listen on all
  156. available interfaces. Family may be set to either `socket.AF_INET`
  157. or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
  158. both will be used if available.
  159. The ``backlog`` argument has the same meaning as for
  160. `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument
  161. has the same meaning as for `.bind_sockets`.
  162. This method may be called multiple times prior to `start` to listen
  163. on multiple ports or interfaces.
  164. .. versionchanged:: 4.4
  165. Added the ``reuse_port`` argument.
  166. """
  167. sockets = bind_sockets(
  168. port, address=address, family=family, backlog=backlog, reuse_port=reuse_port
  169. )
  170. if self._started:
  171. self.add_sockets(sockets)
  172. else:
  173. self._pending_sockets.extend(sockets)
  174. def start(self, num_processes: Optional[int] = 1, max_restarts: int = None) -> None:
  175. """Starts this server in the `.IOLoop`.
  176. By default, we run the server in this process and do not fork any
  177. additional child process.
  178. If num_processes is ``None`` or <= 0, we detect the number of cores
  179. available on this machine and fork that number of child
  180. processes. If num_processes is given and > 1, we fork that
  181. specific number of sub-processes.
  182. Since we use processes and not threads, there is no shared memory
  183. between any server code.
  184. Note that multiple processes are not compatible with the autoreload
  185. module (or the ``autoreload=True`` option to `tornado.web.Application`
  186. which defaults to True when ``debug=True``).
  187. When using multiple processes, no IOLoops can be created or
  188. referenced until after the call to ``TCPServer.start(n)``.
  189. The ``max_restarts`` argument is passed to `.fork_processes`.
  190. .. versionchanged:: 6.0
  191. Added ``max_restarts`` argument.
  192. """
  193. assert not self._started
  194. self._started = True
  195. if num_processes != 1:
  196. process.fork_processes(num_processes, max_restarts)
  197. sockets = self._pending_sockets
  198. self._pending_sockets = []
  199. self.add_sockets(sockets)
  200. def stop(self) -> None:
  201. """Stops listening for new connections.
  202. Requests currently in progress may still continue after the
  203. server is stopped.
  204. """
  205. if self._stopped:
  206. return
  207. self._stopped = True
  208. for fd, sock in self._sockets.items():
  209. assert sock.fileno() == fd
  210. # Unregister socket from IOLoop
  211. self._handlers.pop(fd)()
  212. sock.close()
  213. def handle_stream(
  214. self, stream: IOStream, address: tuple
  215. ) -> Optional[Awaitable[None]]:
  216. """Override to handle a new `.IOStream` from an incoming connection.
  217. This method may be a coroutine; if so any exceptions it raises
  218. asynchronously will be logged. Accepting of incoming connections
  219. will not be blocked by this coroutine.
  220. If this `TCPServer` is configured for SSL, ``handle_stream``
  221. may be called before the SSL handshake has completed. Use
  222. `.SSLIOStream.wait_for_handshake` if you need to verify the client's
  223. certificate or use NPN/ALPN.
  224. .. versionchanged:: 4.2
  225. Added the option for this method to be a coroutine.
  226. """
  227. raise NotImplementedError()
  228. def _handle_connection(self, connection: socket.socket, address: Any) -> None:
  229. if self.ssl_options is not None:
  230. assert ssl, "Python 2.6+ and OpenSSL required for SSL"
  231. try:
  232. connection = ssl_wrap_socket(
  233. connection,
  234. self.ssl_options,
  235. server_side=True,
  236. do_handshake_on_connect=False,
  237. )
  238. except ssl.SSLError as err:
  239. if err.args[0] == ssl.SSL_ERROR_EOF:
  240. return connection.close()
  241. else:
  242. raise
  243. except socket.error as err:
  244. # If the connection is closed immediately after it is created
  245. # (as in a port scan), we can get one of several errors.
  246. # wrap_socket makes an internal call to getpeername,
  247. # which may return either EINVAL (Mac OS X) or ENOTCONN
  248. # (Linux). If it returns ENOTCONN, this error is
  249. # silently swallowed by the ssl module, so we need to
  250. # catch another error later on (AttributeError in
  251. # SSLIOStream._do_ssl_handshake).
  252. # To test this behavior, try nmap with the -sT flag.
  253. # https://github.com/tornadoweb/tornado/pull/750
  254. if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):
  255. return connection.close()
  256. else:
  257. raise
  258. try:
  259. if self.ssl_options is not None:
  260. stream = SSLIOStream(
  261. connection,
  262. max_buffer_size=self.max_buffer_size,
  263. read_chunk_size=self.read_chunk_size,
  264. ) # type: IOStream
  265. else:
  266. stream = IOStream(
  267. connection,
  268. max_buffer_size=self.max_buffer_size,
  269. read_chunk_size=self.read_chunk_size,
  270. )
  271. future = self.handle_stream(stream, address)
  272. if future is not None:
  273. IOLoop.current().add_future(
  274. gen.convert_yielded(future), lambda f: f.result()
  275. )
  276. except Exception:
  277. app_log.error("Error in connection callback", exc_info=True)