tcpserver.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2011 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 TCP server."""
  17. from __future__ import absolute_import, division, print_function, with_statement
  18. import errno
  19. import os
  20. import socket
  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. try:
  28. import ssl
  29. except ImportError:
  30. # ssl is not available on Google App Engine.
  31. ssl = None
  32. class TCPServer(object):
  33. r"""A non-blocking, single-threaded TCP server.
  34. To use `TCPServer`, define a subclass which overrides the `handle_stream`
  35. method.
  36. To make this server serve SSL traffic, send the ``ssl_options`` keyword
  37. argument with an `ssl.SSLContext` object. For compatibility with older
  38. versions of Python ``ssl_options`` may also be a dictionary of keyword
  39. arguments for the `ssl.wrap_socket` method.::
  40. ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  41. ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"),
  42. os.path.join(data_dir, "mydomain.key"))
  43. TCPServer(ssl_options=ssl_ctx)
  44. `TCPServer` initialization follows one of three patterns:
  45. 1. `listen`: simple single-process::
  46. server = TCPServer()
  47. server.listen(8888)
  48. IOLoop.current().start()
  49. 2. `bind`/`start`: simple multi-process::
  50. server = TCPServer()
  51. server.bind(8888)
  52. server.start(0) # Forks multiple sub-processes
  53. IOLoop.current().start()
  54. When using this interface, an `.IOLoop` must *not* be passed
  55. to the `TCPServer` constructor. `start` will always start
  56. the server on the default singleton `.IOLoop`.
  57. 3. `add_sockets`: advanced multi-process::
  58. sockets = bind_sockets(8888)
  59. tornado.process.fork_processes(0)
  60. server = TCPServer()
  61. server.add_sockets(sockets)
  62. IOLoop.current().start()
  63. The `add_sockets` interface is more complicated, but it can be
  64. used with `tornado.process.fork_processes` to give you more
  65. flexibility in when the fork happens. `add_sockets` can
  66. also be used in single-process servers if you want to create
  67. your listening sockets in some way other than
  68. `~tornado.netutil.bind_sockets`.
  69. .. versionadded:: 3.1
  70. The ``max_buffer_size`` argument.
  71. """
  72. def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,
  73. read_chunk_size=None):
  74. self.io_loop = io_loop
  75. self.ssl_options = ssl_options
  76. self._sockets = {} # fd -> socket object
  77. self._pending_sockets = []
  78. self._started = False
  79. self.max_buffer_size = max_buffer_size
  80. self.read_chunk_size = read_chunk_size
  81. # Verify the SSL options. Otherwise we don't get errors until clients
  82. # connect. This doesn't verify that the keys are legitimate, but
  83. # the SSL module doesn't do that until there is a connected socket
  84. # which seems like too much work
  85. if self.ssl_options is not None and isinstance(self.ssl_options, dict):
  86. # Only certfile is required: it can contain both keys
  87. if 'certfile' not in self.ssl_options:
  88. raise KeyError('missing key "certfile" in ssl_options')
  89. if not os.path.exists(self.ssl_options['certfile']):
  90. raise ValueError('certfile "%s" does not exist' %
  91. self.ssl_options['certfile'])
  92. if ('keyfile' in self.ssl_options and
  93. not os.path.exists(self.ssl_options['keyfile'])):
  94. raise ValueError('keyfile "%s" does not exist' %
  95. self.ssl_options['keyfile'])
  96. def listen(self, port, address=""):
  97. """Starts accepting connections on the given port.
  98. This method may be called more than once to listen on multiple ports.
  99. `listen` takes effect immediately; it is not necessary to call
  100. `TCPServer.start` afterwards. It is, however, necessary to start
  101. the `.IOLoop`.
  102. """
  103. sockets = bind_sockets(port, address=address)
  104. self.add_sockets(sockets)
  105. def add_sockets(self, sockets):
  106. """Makes this server start accepting connections on the given sockets.
  107. The ``sockets`` parameter is a list of socket objects such as
  108. those returned by `~tornado.netutil.bind_sockets`.
  109. `add_sockets` is typically used in combination with that
  110. method and `tornado.process.fork_processes` to provide greater
  111. control over the initialization of a multi-process server.
  112. """
  113. if self.io_loop is None:
  114. self.io_loop = IOLoop.current()
  115. for sock in sockets:
  116. self._sockets[sock.fileno()] = sock
  117. add_accept_handler(sock, self._handle_connection,
  118. io_loop=self.io_loop)
  119. def add_socket(self, socket):
  120. """Singular version of `add_sockets`. Takes a single socket object."""
  121. self.add_sockets([socket])
  122. def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128):
  123. """Binds this server to the given port on the given address.
  124. To start the server, call `start`. If you want to run this server
  125. in a single process, you can call `listen` as a shortcut to the
  126. sequence of `bind` and `start` calls.
  127. Address may be either an IP address or hostname. If it's a hostname,
  128. the server will listen on all IP addresses associated with the
  129. name. Address may be an empty string or None to listen on all
  130. available interfaces. Family may be set to either `socket.AF_INET`
  131. or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
  132. both will be used if available.
  133. The ``backlog`` argument has the same meaning as for
  134. `socket.listen <socket.socket.listen>`.
  135. This method may be called multiple times prior to `start` to listen
  136. on multiple ports or interfaces.
  137. """
  138. sockets = bind_sockets(port, address=address, family=family,
  139. backlog=backlog)
  140. if self._started:
  141. self.add_sockets(sockets)
  142. else:
  143. self._pending_sockets.extend(sockets)
  144. def start(self, num_processes=1):
  145. """Starts this server in the `.IOLoop`.
  146. By default, we run the server in this process and do not fork any
  147. additional child process.
  148. If num_processes is ``None`` or <= 0, we detect the number of cores
  149. available on this machine and fork that number of child
  150. processes. If num_processes is given and > 1, we fork that
  151. specific number of sub-processes.
  152. Since we use processes and not threads, there is no shared memory
  153. between any server code.
  154. Note that multiple processes are not compatible with the autoreload
  155. module (or the ``autoreload=True`` option to `tornado.web.Application`
  156. which defaults to True when ``debug=True``).
  157. When using multiple processes, no IOLoops can be created or
  158. referenced until after the call to ``TCPServer.start(n)``.
  159. """
  160. assert not self._started
  161. self._started = True
  162. if num_processes != 1:
  163. process.fork_processes(num_processes)
  164. sockets = self._pending_sockets
  165. self._pending_sockets = []
  166. self.add_sockets(sockets)
  167. def stop(self):
  168. """Stops listening for new connections.
  169. Requests currently in progress may still continue after the
  170. server is stopped.
  171. """
  172. for fd, sock in self._sockets.items():
  173. self.io_loop.remove_handler(fd)
  174. sock.close()
  175. def handle_stream(self, stream, address):
  176. """Override to handle a new `.IOStream` from an incoming connection.
  177. This method may be a coroutine; if so any exceptions it raises
  178. asynchronously will be logged. Accepting of incoming connections
  179. will not be blocked by this coroutine.
  180. If this `TCPServer` is configured for SSL, ``handle_stream``
  181. may be called before the SSL handshake has completed. Use
  182. `.SSLIOStream.wait_for_handshake` if you need to verify the client's
  183. certificate or use NPN/ALPN.
  184. .. versionchanged:: 4.2
  185. Added the option for this method to be a coroutine.
  186. """
  187. raise NotImplementedError()
  188. def _handle_connection(self, connection, address):
  189. if self.ssl_options is not None:
  190. assert ssl, "Python 2.6+ and OpenSSL required for SSL"
  191. try:
  192. connection = ssl_wrap_socket(connection,
  193. self.ssl_options,
  194. server_side=True,
  195. do_handshake_on_connect=False)
  196. except ssl.SSLError as err:
  197. if err.args[0] == ssl.SSL_ERROR_EOF:
  198. return connection.close()
  199. else:
  200. raise
  201. except socket.error as err:
  202. # If the connection is closed immediately after it is created
  203. # (as in a port scan), we can get one of several errors.
  204. # wrap_socket makes an internal call to getpeername,
  205. # which may return either EINVAL (Mac OS X) or ENOTCONN
  206. # (Linux). If it returns ENOTCONN, this error is
  207. # silently swallowed by the ssl module, so we need to
  208. # catch another error later on (AttributeError in
  209. # SSLIOStream._do_ssl_handshake).
  210. # To test this behavior, try nmap with the -sT flag.
  211. # https://github.com/tornadoweb/tornado/pull/750
  212. if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):
  213. return connection.close()
  214. else:
  215. raise
  216. try:
  217. if self.ssl_options is not None:
  218. stream = SSLIOStream(connection, io_loop=self.io_loop,
  219. max_buffer_size=self.max_buffer_size,
  220. read_chunk_size=self.read_chunk_size)
  221. else:
  222. stream = IOStream(connection, io_loop=self.io_loop,
  223. max_buffer_size=self.max_buffer_size,
  224. read_chunk_size=self.read_chunk_size)
  225. future = self.handle_stream(stream, address)
  226. if future is not None:
  227. self.io_loop.add_future(future, lambda f: f.result())
  228. except Exception:
  229. app_log.error("Error in connection callback", exc_info=True)