iostream.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. #
  2. # Copyright 2009 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. """Utility classes to write to and read from non-blocking files and sockets.
  16. Contents:
  17. * `BaseIOStream`: Generic interface for reading and writing.
  18. * `IOStream`: Implementation of BaseIOStream using non-blocking sockets.
  19. * `SSLIOStream`: SSL-aware version of IOStream.
  20. * `PipeIOStream`: Pipe-based IOStream implementation.
  21. """
  22. import asyncio
  23. import collections
  24. import errno
  25. import io
  26. import numbers
  27. import os
  28. import socket
  29. import ssl
  30. import sys
  31. import re
  32. from tornado.concurrent import Future, future_set_result_unless_cancelled
  33. from tornado import ioloop
  34. from tornado.log import gen_log
  35. from tornado.netutil import ssl_wrap_socket, _client_ssl_defaults, _server_ssl_defaults
  36. from tornado.util import errno_from_exception
  37. import typing
  38. from typing import (
  39. Union,
  40. Optional,
  41. Awaitable,
  42. Callable,
  43. Pattern,
  44. Any,
  45. Dict,
  46. TypeVar,
  47. Tuple,
  48. )
  49. from types import TracebackType
  50. if typing.TYPE_CHECKING:
  51. from typing import Deque, List, Type # noqa: F401
  52. _IOStreamType = TypeVar("_IOStreamType", bound="IOStream")
  53. # These errnos indicate that a connection has been abruptly terminated.
  54. # They should be caught and handled less noisily than other errors.
  55. _ERRNO_CONNRESET = (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE, errno.ETIMEDOUT)
  56. if hasattr(errno, "WSAECONNRESET"):
  57. _ERRNO_CONNRESET += ( # type: ignore
  58. errno.WSAECONNRESET, # type: ignore
  59. errno.WSAECONNABORTED, # type: ignore
  60. errno.WSAETIMEDOUT, # type: ignore
  61. )
  62. if sys.platform == "darwin":
  63. # OSX appears to have a race condition that causes send(2) to return
  64. # EPROTOTYPE if called while a socket is being torn down:
  65. # http://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
  66. # Since the socket is being closed anyway, treat this as an ECONNRESET
  67. # instead of an unexpected error.
  68. _ERRNO_CONNRESET += (errno.EPROTOTYPE,) # type: ignore
  69. _WINDOWS = sys.platform.startswith("win")
  70. class StreamClosedError(IOError):
  71. """Exception raised by `IOStream` methods when the stream is closed.
  72. Note that the close callback is scheduled to run *after* other
  73. callbacks on the stream (to allow for buffered data to be processed),
  74. so you may see this error before you see the close callback.
  75. The ``real_error`` attribute contains the underlying error that caused
  76. the stream to close (if any).
  77. .. versionchanged:: 4.3
  78. Added the ``real_error`` attribute.
  79. """
  80. def __init__(self, real_error: Optional[BaseException] = None) -> None:
  81. super().__init__("Stream is closed")
  82. self.real_error = real_error
  83. class UnsatisfiableReadError(Exception):
  84. """Exception raised when a read cannot be satisfied.
  85. Raised by ``read_until`` and ``read_until_regex`` with a ``max_bytes``
  86. argument.
  87. """
  88. pass
  89. class StreamBufferFullError(Exception):
  90. """Exception raised by `IOStream` methods when the buffer is full."""
  91. class _StreamBuffer:
  92. """
  93. A specialized buffer that tries to avoid copies when large pieces
  94. of data are encountered.
  95. """
  96. def __init__(self) -> None:
  97. # A sequence of (False, bytearray) and (True, memoryview) objects
  98. self._buffers = (
  99. collections.deque()
  100. ) # type: Deque[Tuple[bool, Union[bytearray, memoryview]]]
  101. # Position in the first buffer
  102. self._first_pos = 0
  103. self._size = 0
  104. def __len__(self) -> int:
  105. return self._size
  106. # Data above this size will be appended separately instead
  107. # of extending an existing bytearray
  108. _large_buf_threshold = 2048
  109. def append(self, data: Union[bytes, bytearray, memoryview]) -> None:
  110. """
  111. Append the given piece of data (should be a buffer-compatible object).
  112. """
  113. size = len(data)
  114. if size > self._large_buf_threshold:
  115. if not isinstance(data, memoryview):
  116. data = memoryview(data)
  117. self._buffers.append((True, data))
  118. elif size > 0:
  119. if self._buffers:
  120. is_memview, b = self._buffers[-1]
  121. new_buf = is_memview or len(b) >= self._large_buf_threshold
  122. else:
  123. new_buf = True
  124. if new_buf:
  125. self._buffers.append((False, bytearray(data)))
  126. else:
  127. b += data # type: ignore
  128. self._size += size
  129. def peek(self, size: int) -> memoryview:
  130. """
  131. Get a view over at most ``size`` bytes (possibly fewer) at the
  132. current buffer position.
  133. """
  134. assert size > 0
  135. try:
  136. is_memview, b = self._buffers[0]
  137. except IndexError:
  138. return memoryview(b"")
  139. pos = self._first_pos
  140. if is_memview:
  141. return typing.cast(memoryview, b[pos : pos + size])
  142. else:
  143. return memoryview(b)[pos : pos + size]
  144. def advance(self, size: int) -> None:
  145. """
  146. Advance the current buffer position by ``size`` bytes.
  147. """
  148. assert 0 < size <= self._size
  149. self._size -= size
  150. pos = self._first_pos
  151. buffers = self._buffers
  152. while buffers and size > 0:
  153. is_large, b = buffers[0]
  154. b_remain = len(b) - size - pos
  155. if b_remain <= 0:
  156. buffers.popleft()
  157. size -= len(b) - pos
  158. pos = 0
  159. elif is_large:
  160. pos += size
  161. size = 0
  162. else:
  163. pos += size
  164. del typing.cast(bytearray, b)[:pos]
  165. pos = 0
  166. size = 0
  167. assert size == 0
  168. self._first_pos = pos
  169. class BaseIOStream:
  170. """A utility class to write to and read from a non-blocking file or socket.
  171. We support a non-blocking ``write()`` and a family of ``read_*()``
  172. methods. When the operation completes, the ``Awaitable`` will resolve
  173. with the data read (or ``None`` for ``write()``). All outstanding
  174. ``Awaitables`` will resolve with a `StreamClosedError` when the
  175. stream is closed; `.BaseIOStream.set_close_callback` can also be used
  176. to be notified of a closed stream.
  177. When a stream is closed due to an error, the IOStream's ``error``
  178. attribute contains the exception object.
  179. Subclasses must implement `fileno`, `close_fd`, `write_to_fd`,
  180. `read_from_fd`, and optionally `get_fd_error`.
  181. """
  182. def __init__(
  183. self,
  184. max_buffer_size: Optional[int] = None,
  185. read_chunk_size: Optional[int] = None,
  186. max_write_buffer_size: Optional[int] = None,
  187. ) -> None:
  188. """`BaseIOStream` constructor.
  189. :arg max_buffer_size: Maximum amount of incoming data to buffer;
  190. defaults to 100MB.
  191. :arg read_chunk_size: Amount of data to read at one time from the
  192. underlying transport; defaults to 64KB.
  193. :arg max_write_buffer_size: Amount of outgoing data to buffer;
  194. defaults to unlimited.
  195. .. versionchanged:: 4.0
  196. Add the ``max_write_buffer_size`` parameter. Changed default
  197. ``read_chunk_size`` to 64KB.
  198. .. versionchanged:: 5.0
  199. The ``io_loop`` argument (deprecated since version 4.1) has been
  200. removed.
  201. """
  202. self.io_loop = ioloop.IOLoop.current()
  203. self.max_buffer_size = max_buffer_size or 104857600
  204. # A chunk size that is too close to max_buffer_size can cause
  205. # spurious failures.
  206. self.read_chunk_size = min(read_chunk_size or 65536, self.max_buffer_size // 2)
  207. self.max_write_buffer_size = max_write_buffer_size
  208. self.error = None # type: Optional[BaseException]
  209. self._read_buffer = bytearray()
  210. self._read_buffer_size = 0
  211. self._user_read_buffer = False
  212. self._after_user_read_buffer = None # type: Optional[bytearray]
  213. self._write_buffer = _StreamBuffer()
  214. self._total_write_index = 0
  215. self._total_write_done_index = 0
  216. self._read_delimiter = None # type: Optional[bytes]
  217. self._read_regex = None # type: Optional[Pattern]
  218. self._read_max_bytes = None # type: Optional[int]
  219. self._read_bytes = None # type: Optional[int]
  220. self._read_partial = False
  221. self._read_until_close = False
  222. self._read_future = None # type: Optional[Future]
  223. self._write_futures = (
  224. collections.deque()
  225. ) # type: Deque[Tuple[int, Future[None]]]
  226. self._close_callback = None # type: Optional[Callable[[], None]]
  227. self._connect_future = None # type: Optional[Future[IOStream]]
  228. # _ssl_connect_future should be defined in SSLIOStream
  229. # but it's here so we can clean it up in _signal_closed
  230. # TODO: refactor that so subclasses can add additional futures
  231. # to be cancelled.
  232. self._ssl_connect_future = None # type: Optional[Future[SSLIOStream]]
  233. self._connecting = False
  234. self._state = None # type: Optional[int]
  235. self._closed = False
  236. def fileno(self) -> Union[int, ioloop._Selectable]:
  237. """Returns the file descriptor for this stream."""
  238. raise NotImplementedError()
  239. def close_fd(self) -> None:
  240. """Closes the file underlying this stream.
  241. ``close_fd`` is called by `BaseIOStream` and should not be called
  242. elsewhere; other users should call `close` instead.
  243. """
  244. raise NotImplementedError()
  245. def write_to_fd(self, data: memoryview) -> int:
  246. """Attempts to write ``data`` to the underlying file.
  247. Returns the number of bytes written.
  248. """
  249. raise NotImplementedError()
  250. def read_from_fd(self, buf: Union[bytearray, memoryview]) -> Optional[int]:
  251. """Attempts to read from the underlying file.
  252. Reads up to ``len(buf)`` bytes, storing them in the buffer.
  253. Returns the number of bytes read. Returns None if there was
  254. nothing to read (the socket returned `~errno.EWOULDBLOCK` or
  255. equivalent), and zero on EOF.
  256. .. versionchanged:: 5.0
  257. Interface redesigned to take a buffer and return a number
  258. of bytes instead of a freshly-allocated object.
  259. """
  260. raise NotImplementedError()
  261. def get_fd_error(self) -> Optional[Exception]:
  262. """Returns information about any error on the underlying file.
  263. This method is called after the `.IOLoop` has signaled an error on the
  264. file descriptor, and should return an Exception (such as `socket.error`
  265. with additional information, or None if no such information is
  266. available.
  267. """
  268. return None
  269. def read_until_regex(
  270. self, regex: bytes, max_bytes: Optional[int] = None
  271. ) -> Awaitable[bytes]:
  272. """Asynchronously read until we have matched the given regex.
  273. The result includes the data that matches the regex and anything
  274. that came before it.
  275. If ``max_bytes`` is not None, the connection will be closed
  276. if more than ``max_bytes`` bytes have been read and the regex is
  277. not satisfied.
  278. .. versionchanged:: 4.0
  279. Added the ``max_bytes`` argument. The ``callback`` argument is
  280. now optional and a `.Future` will be returned if it is omitted.
  281. .. versionchanged:: 6.0
  282. The ``callback`` argument was removed. Use the returned
  283. `.Future` instead.
  284. """
  285. future = self._start_read()
  286. self._read_regex = re.compile(regex)
  287. self._read_max_bytes = max_bytes
  288. try:
  289. self._try_inline_read()
  290. except UnsatisfiableReadError as e:
  291. # Handle this the same way as in _handle_events.
  292. gen_log.info("Unsatisfiable read, closing connection: %s" % e)
  293. self.close(exc_info=e)
  294. return future
  295. except:
  296. # Ensure that the future doesn't log an error because its
  297. # failure was never examined.
  298. future.add_done_callback(lambda f: f.exception())
  299. raise
  300. return future
  301. def read_until(
  302. self, delimiter: bytes, max_bytes: Optional[int] = None
  303. ) -> Awaitable[bytes]:
  304. """Asynchronously read until we have found the given delimiter.
  305. The result includes all the data read including the delimiter.
  306. If ``max_bytes`` is not None, the connection will be closed
  307. if more than ``max_bytes`` bytes have been read and the delimiter
  308. is not found.
  309. .. versionchanged:: 4.0
  310. Added the ``max_bytes`` argument. The ``callback`` argument is
  311. now optional and a `.Future` will be returned if it is omitted.
  312. .. versionchanged:: 6.0
  313. The ``callback`` argument was removed. Use the returned
  314. `.Future` instead.
  315. """
  316. future = self._start_read()
  317. self._read_delimiter = delimiter
  318. self._read_max_bytes = max_bytes
  319. try:
  320. self._try_inline_read()
  321. except UnsatisfiableReadError as e:
  322. # Handle this the same way as in _handle_events.
  323. gen_log.info("Unsatisfiable read, closing connection: %s" % e)
  324. self.close(exc_info=e)
  325. return future
  326. except:
  327. future.add_done_callback(lambda f: f.exception())
  328. raise
  329. return future
  330. def read_bytes(self, num_bytes: int, partial: bool = False) -> Awaitable[bytes]:
  331. """Asynchronously read a number of bytes.
  332. If ``partial`` is true, data is returned as soon as we have
  333. any bytes to return (but never more than ``num_bytes``)
  334. .. versionchanged:: 4.0
  335. Added the ``partial`` argument. The callback argument is now
  336. optional and a `.Future` will be returned if it is omitted.
  337. .. versionchanged:: 6.0
  338. The ``callback`` and ``streaming_callback`` arguments have
  339. been removed. Use the returned `.Future` (and
  340. ``partial=True`` for ``streaming_callback``) instead.
  341. """
  342. future = self._start_read()
  343. assert isinstance(num_bytes, numbers.Integral)
  344. self._read_bytes = num_bytes
  345. self._read_partial = partial
  346. try:
  347. self._try_inline_read()
  348. except:
  349. future.add_done_callback(lambda f: f.exception())
  350. raise
  351. return future
  352. def read_into(self, buf: bytearray, partial: bool = False) -> Awaitable[int]:
  353. """Asynchronously read a number of bytes.
  354. ``buf`` must be a writable buffer into which data will be read.
  355. If ``partial`` is true, the callback is run as soon as any bytes
  356. have been read. Otherwise, it is run when the ``buf`` has been
  357. entirely filled with read data.
  358. .. versionadded:: 5.0
  359. .. versionchanged:: 6.0
  360. The ``callback`` argument was removed. Use the returned
  361. `.Future` instead.
  362. """
  363. future = self._start_read()
  364. # First copy data already in read buffer
  365. available_bytes = self._read_buffer_size
  366. n = len(buf)
  367. if available_bytes >= n:
  368. buf[:] = memoryview(self._read_buffer)[:n]
  369. del self._read_buffer[:n]
  370. self._after_user_read_buffer = self._read_buffer
  371. elif available_bytes > 0:
  372. buf[:available_bytes] = memoryview(self._read_buffer)[:]
  373. # Set up the supplied buffer as our temporary read buffer.
  374. # The original (if it had any data remaining) has been
  375. # saved for later.
  376. self._user_read_buffer = True
  377. self._read_buffer = buf
  378. self._read_buffer_size = available_bytes
  379. self._read_bytes = n
  380. self._read_partial = partial
  381. try:
  382. self._try_inline_read()
  383. except:
  384. future.add_done_callback(lambda f: f.exception())
  385. raise
  386. return future
  387. def read_until_close(self) -> Awaitable[bytes]:
  388. """Asynchronously reads all data from the socket until it is closed.
  389. This will buffer all available data until ``max_buffer_size``
  390. is reached. If flow control or cancellation are desired, use a
  391. loop with `read_bytes(partial=True) <.read_bytes>` instead.
  392. .. versionchanged:: 4.0
  393. The callback argument is now optional and a `.Future` will
  394. be returned if it is omitted.
  395. .. versionchanged:: 6.0
  396. The ``callback`` and ``streaming_callback`` arguments have
  397. been removed. Use the returned `.Future` (and `read_bytes`
  398. with ``partial=True`` for ``streaming_callback``) instead.
  399. """
  400. future = self._start_read()
  401. if self.closed():
  402. self._finish_read(self._read_buffer_size)
  403. return future
  404. self._read_until_close = True
  405. try:
  406. self._try_inline_read()
  407. except:
  408. future.add_done_callback(lambda f: f.exception())
  409. raise
  410. return future
  411. def write(self, data: Union[bytes, memoryview]) -> "Future[None]":
  412. """Asynchronously write the given data to this stream.
  413. This method returns a `.Future` that resolves (with a result
  414. of ``None``) when the write has been completed.
  415. The ``data`` argument may be of type `bytes` or `memoryview`.
  416. .. versionchanged:: 4.0
  417. Now returns a `.Future` if no callback is given.
  418. .. versionchanged:: 4.5
  419. Added support for `memoryview` arguments.
  420. .. versionchanged:: 6.0
  421. The ``callback`` argument was removed. Use the returned
  422. `.Future` instead.
  423. """
  424. self._check_closed()
  425. if data:
  426. if isinstance(data, memoryview):
  427. # Make sure that ``len(data) == data.nbytes``
  428. data = memoryview(data).cast("B")
  429. if (
  430. self.max_write_buffer_size is not None
  431. and len(self._write_buffer) + len(data) > self.max_write_buffer_size
  432. ):
  433. raise StreamBufferFullError("Reached maximum write buffer size")
  434. self._write_buffer.append(data)
  435. self._total_write_index += len(data)
  436. future = Future() # type: Future[None]
  437. future.add_done_callback(lambda f: f.exception())
  438. self._write_futures.append((self._total_write_index, future))
  439. if not self._connecting:
  440. self._handle_write()
  441. if self._write_buffer:
  442. self._add_io_state(self.io_loop.WRITE)
  443. self._maybe_add_error_listener()
  444. return future
  445. def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None:
  446. """Call the given callback when the stream is closed.
  447. This mostly is not necessary for applications that use the
  448. `.Future` interface; all outstanding ``Futures`` will resolve
  449. with a `StreamClosedError` when the stream is closed. However,
  450. it is still useful as a way to signal that the stream has been
  451. closed while no other read or write is in progress.
  452. Unlike other callback-based interfaces, ``set_close_callback``
  453. was not removed in Tornado 6.0.
  454. """
  455. self._close_callback = callback
  456. self._maybe_add_error_listener()
  457. def close(
  458. self,
  459. exc_info: Union[
  460. None,
  461. bool,
  462. BaseException,
  463. Tuple[
  464. "Optional[Type[BaseException]]",
  465. Optional[BaseException],
  466. Optional[TracebackType],
  467. ],
  468. ] = False,
  469. ) -> None:
  470. """Close this stream.
  471. If ``exc_info`` is true, set the ``error`` attribute to the current
  472. exception from `sys.exc_info` (or if ``exc_info`` is a tuple,
  473. use that instead of `sys.exc_info`).
  474. """
  475. if not self.closed():
  476. if exc_info:
  477. if isinstance(exc_info, tuple):
  478. self.error = exc_info[1]
  479. elif isinstance(exc_info, BaseException):
  480. self.error = exc_info
  481. else:
  482. exc_info = sys.exc_info()
  483. if any(exc_info):
  484. self.error = exc_info[1]
  485. if self._read_until_close:
  486. self._read_until_close = False
  487. self._finish_read(self._read_buffer_size)
  488. elif self._read_future is not None:
  489. # resolve reads that are pending and ready to complete
  490. try:
  491. pos = self._find_read_pos()
  492. except UnsatisfiableReadError:
  493. pass
  494. else:
  495. if pos is not None:
  496. self._read_from_buffer(pos)
  497. if self._state is not None:
  498. self.io_loop.remove_handler(self.fileno())
  499. self._state = None
  500. self.close_fd()
  501. self._closed = True
  502. self._signal_closed()
  503. def _signal_closed(self) -> None:
  504. futures = [] # type: List[Future]
  505. if self._read_future is not None:
  506. futures.append(self._read_future)
  507. self._read_future = None
  508. futures += [future for _, future in self._write_futures]
  509. self._write_futures.clear()
  510. if self._connect_future is not None:
  511. futures.append(self._connect_future)
  512. self._connect_future = None
  513. for future in futures:
  514. if not future.done():
  515. future.set_exception(StreamClosedError(real_error=self.error))
  516. # Reference the exception to silence warnings. Annoyingly,
  517. # this raises if the future was cancelled, but just
  518. # returns any other error.
  519. try:
  520. future.exception()
  521. except asyncio.CancelledError:
  522. pass
  523. if self._ssl_connect_future is not None:
  524. # _ssl_connect_future expects to see the real exception (typically
  525. # an ssl.SSLError), not just StreamClosedError.
  526. if not self._ssl_connect_future.done():
  527. if self.error is not None:
  528. self._ssl_connect_future.set_exception(self.error)
  529. else:
  530. self._ssl_connect_future.set_exception(StreamClosedError())
  531. self._ssl_connect_future.exception()
  532. self._ssl_connect_future = None
  533. if self._close_callback is not None:
  534. cb = self._close_callback
  535. self._close_callback = None
  536. self.io_loop.add_callback(cb)
  537. # Clear the buffers so they can be cleared immediately even
  538. # if the IOStream object is kept alive by a reference cycle.
  539. # TODO: Clear the read buffer too; it currently breaks some tests.
  540. self._write_buffer = None # type: ignore
  541. def reading(self) -> bool:
  542. """Returns ``True`` if we are currently reading from the stream."""
  543. return self._read_future is not None
  544. def writing(self) -> bool:
  545. """Returns ``True`` if we are currently writing to the stream."""
  546. return bool(self._write_buffer)
  547. def closed(self) -> bool:
  548. """Returns ``True`` if the stream has been closed."""
  549. return self._closed
  550. def set_nodelay(self, value: bool) -> None:
  551. """Sets the no-delay flag for this stream.
  552. By default, data written to TCP streams may be held for a time
  553. to make the most efficient use of bandwidth (according to
  554. Nagle's algorithm). The no-delay flag requests that data be
  555. written as soon as possible, even if doing so would consume
  556. additional bandwidth.
  557. This flag is currently defined only for TCP-based ``IOStreams``.
  558. .. versionadded:: 3.1
  559. """
  560. pass
  561. def _handle_connect(self) -> None:
  562. raise NotImplementedError()
  563. def _handle_events(self, fd: Union[int, ioloop._Selectable], events: int) -> None:
  564. if self.closed():
  565. gen_log.warning("Got events for closed stream %s", fd)
  566. return
  567. try:
  568. if self._connecting:
  569. # Most IOLoops will report a write failed connect
  570. # with the WRITE event, but SelectIOLoop reports a
  571. # READ as well so we must check for connecting before
  572. # either.
  573. self._handle_connect()
  574. if self.closed():
  575. return
  576. if events & self.io_loop.READ:
  577. self._handle_read()
  578. if self.closed():
  579. return
  580. if events & self.io_loop.WRITE:
  581. self._handle_write()
  582. if self.closed():
  583. return
  584. if events & self.io_loop.ERROR:
  585. self.error = self.get_fd_error()
  586. # We may have queued up a user callback in _handle_read or
  587. # _handle_write, so don't close the IOStream until those
  588. # callbacks have had a chance to run.
  589. self.io_loop.add_callback(self.close)
  590. return
  591. state = self.io_loop.ERROR
  592. if self.reading():
  593. state |= self.io_loop.READ
  594. if self.writing():
  595. state |= self.io_loop.WRITE
  596. if state == self.io_loop.ERROR and self._read_buffer_size == 0:
  597. # If the connection is idle, listen for reads too so
  598. # we can tell if the connection is closed. If there is
  599. # data in the read buffer we won't run the close callback
  600. # yet anyway, so we don't need to listen in this case.
  601. state |= self.io_loop.READ
  602. if state != self._state:
  603. assert (
  604. self._state is not None
  605. ), "shouldn't happen: _handle_events without self._state"
  606. self._state = state
  607. self.io_loop.update_handler(self.fileno(), self._state)
  608. except UnsatisfiableReadError as e:
  609. gen_log.info("Unsatisfiable read, closing connection: %s" % e)
  610. self.close(exc_info=e)
  611. except Exception as e:
  612. gen_log.error("Uncaught exception, closing connection.", exc_info=True)
  613. self.close(exc_info=e)
  614. raise
  615. def _read_to_buffer_loop(self) -> Optional[int]:
  616. # This method is called from _handle_read and _try_inline_read.
  617. if self._read_bytes is not None:
  618. target_bytes = self._read_bytes # type: Optional[int]
  619. elif self._read_max_bytes is not None:
  620. target_bytes = self._read_max_bytes
  621. elif self.reading():
  622. # For read_until without max_bytes, or
  623. # read_until_close, read as much as we can before
  624. # scanning for the delimiter.
  625. target_bytes = None
  626. else:
  627. target_bytes = 0
  628. next_find_pos = 0
  629. while not self.closed():
  630. # Read from the socket until we get EWOULDBLOCK or equivalent.
  631. # SSL sockets do some internal buffering, and if the data is
  632. # sitting in the SSL object's buffer select() and friends
  633. # can't see it; the only way to find out if it's there is to
  634. # try to read it.
  635. if self._read_to_buffer() == 0:
  636. break
  637. # If we've read all the bytes we can use, break out of
  638. # this loop.
  639. # If we've reached target_bytes, we know we're done.
  640. if target_bytes is not None and self._read_buffer_size >= target_bytes:
  641. break
  642. # Otherwise, we need to call the more expensive find_read_pos.
  643. # It's inefficient to do this on every read, so instead
  644. # do it on the first read and whenever the read buffer
  645. # size has doubled.
  646. if self._read_buffer_size >= next_find_pos:
  647. pos = self._find_read_pos()
  648. if pos is not None:
  649. return pos
  650. next_find_pos = self._read_buffer_size * 2
  651. return self._find_read_pos()
  652. def _handle_read(self) -> None:
  653. try:
  654. pos = self._read_to_buffer_loop()
  655. except UnsatisfiableReadError:
  656. raise
  657. except asyncio.CancelledError:
  658. raise
  659. except Exception as e:
  660. gen_log.warning("error on read: %s" % e)
  661. self.close(exc_info=e)
  662. return
  663. if pos is not None:
  664. self._read_from_buffer(pos)
  665. def _start_read(self) -> Future:
  666. if self._read_future is not None:
  667. # It is an error to start a read while a prior read is unresolved.
  668. # However, if the prior read is unresolved because the stream was
  669. # closed without satisfying it, it's better to raise
  670. # StreamClosedError instead of AssertionError. In particular, this
  671. # situation occurs in harmless situations in http1connection.py and
  672. # an AssertionError would be logged noisily.
  673. #
  674. # On the other hand, it is legal to start a new read while the
  675. # stream is closed, in case the read can be satisfied from the
  676. # read buffer. So we only want to check the closed status of the
  677. # stream if we need to decide what kind of error to raise for
  678. # "already reading".
  679. #
  680. # These conditions have proven difficult to test; we have no
  681. # unittests that reliably verify this behavior so be careful
  682. # when making changes here. See #2651 and #2719.
  683. self._check_closed()
  684. assert self._read_future is None, "Already reading"
  685. self._read_future = Future()
  686. return self._read_future
  687. def _finish_read(self, size: int) -> None:
  688. if self._user_read_buffer:
  689. self._read_buffer = self._after_user_read_buffer or bytearray()
  690. self._after_user_read_buffer = None
  691. self._read_buffer_size = len(self._read_buffer)
  692. self._user_read_buffer = False
  693. result = size # type: Union[int, bytes]
  694. else:
  695. result = self._consume(size)
  696. if self._read_future is not None:
  697. future = self._read_future
  698. self._read_future = None
  699. future_set_result_unless_cancelled(future, result)
  700. self._maybe_add_error_listener()
  701. def _try_inline_read(self) -> None:
  702. """Attempt to complete the current read operation from buffered data.
  703. If the read can be completed without blocking, schedules the
  704. read callback on the next IOLoop iteration; otherwise starts
  705. listening for reads on the socket.
  706. """
  707. # See if we've already got the data from a previous read
  708. pos = self._find_read_pos()
  709. if pos is not None:
  710. self._read_from_buffer(pos)
  711. return
  712. self._check_closed()
  713. pos = self._read_to_buffer_loop()
  714. if pos is not None:
  715. self._read_from_buffer(pos)
  716. return
  717. # We couldn't satisfy the read inline, so make sure we're
  718. # listening for new data unless the stream is closed.
  719. if not self.closed():
  720. self._add_io_state(ioloop.IOLoop.READ)
  721. def _read_to_buffer(self) -> Optional[int]:
  722. """Reads from the socket and appends the result to the read buffer.
  723. Returns the number of bytes read. Returns 0 if there is nothing
  724. to read (i.e. the read returns EWOULDBLOCK or equivalent). On
  725. error closes the socket and raises an exception.
  726. """
  727. try:
  728. while True:
  729. try:
  730. if self._user_read_buffer:
  731. buf = memoryview(self._read_buffer)[
  732. self._read_buffer_size :
  733. ] # type: Union[memoryview, bytearray]
  734. else:
  735. buf = bytearray(self.read_chunk_size)
  736. bytes_read = self.read_from_fd(buf)
  737. except OSError as e:
  738. # ssl.SSLError is a subclass of socket.error
  739. if self._is_connreset(e):
  740. # Treat ECONNRESET as a connection close rather than
  741. # an error to minimize log spam (the exception will
  742. # be available on self.error for apps that care).
  743. self.close(exc_info=e)
  744. return None
  745. self.close(exc_info=e)
  746. raise
  747. break
  748. if bytes_read is None:
  749. return 0
  750. elif bytes_read == 0:
  751. self.close()
  752. return 0
  753. if not self._user_read_buffer:
  754. self._read_buffer += memoryview(buf)[:bytes_read]
  755. self._read_buffer_size += bytes_read
  756. finally:
  757. # Break the reference to buf so we don't waste a chunk's worth of
  758. # memory in case an exception hangs on to our stack frame.
  759. del buf
  760. if self._read_buffer_size > self.max_buffer_size:
  761. gen_log.error("Reached maximum read buffer size")
  762. self.close()
  763. raise StreamBufferFullError("Reached maximum read buffer size")
  764. return bytes_read
  765. def _read_from_buffer(self, pos: int) -> None:
  766. """Attempts to complete the currently-pending read from the buffer.
  767. The argument is either a position in the read buffer or None,
  768. as returned by _find_read_pos.
  769. """
  770. self._read_bytes = self._read_delimiter = self._read_regex = None
  771. self._read_partial = False
  772. self._finish_read(pos)
  773. def _find_read_pos(self) -> Optional[int]:
  774. """Attempts to find a position in the read buffer that satisfies
  775. the currently-pending read.
  776. Returns a position in the buffer if the current read can be satisfied,
  777. or None if it cannot.
  778. """
  779. if self._read_bytes is not None and (
  780. self._read_buffer_size >= self._read_bytes
  781. or (self._read_partial and self._read_buffer_size > 0)
  782. ):
  783. num_bytes = min(self._read_bytes, self._read_buffer_size)
  784. return num_bytes
  785. elif self._read_delimiter is not None:
  786. # Multi-byte delimiters (e.g. '\r\n') may straddle two
  787. # chunks in the read buffer, so we can't easily find them
  788. # without collapsing the buffer. However, since protocols
  789. # using delimited reads (as opposed to reads of a known
  790. # length) tend to be "line" oriented, the delimiter is likely
  791. # to be in the first few chunks. Merge the buffer gradually
  792. # since large merges are relatively expensive and get undone in
  793. # _consume().
  794. if self._read_buffer:
  795. loc = self._read_buffer.find(self._read_delimiter)
  796. if loc != -1:
  797. delimiter_len = len(self._read_delimiter)
  798. self._check_max_bytes(self._read_delimiter, loc + delimiter_len)
  799. return loc + delimiter_len
  800. self._check_max_bytes(self._read_delimiter, self._read_buffer_size)
  801. elif self._read_regex is not None:
  802. if self._read_buffer:
  803. m = self._read_regex.search(self._read_buffer)
  804. if m is not None:
  805. loc = m.end()
  806. self._check_max_bytes(self._read_regex, loc)
  807. return loc
  808. self._check_max_bytes(self._read_regex, self._read_buffer_size)
  809. return None
  810. def _check_max_bytes(self, delimiter: Union[bytes, Pattern], size: int) -> None:
  811. if self._read_max_bytes is not None and size > self._read_max_bytes:
  812. raise UnsatisfiableReadError(
  813. "delimiter %r not found within %d bytes"
  814. % (delimiter, self._read_max_bytes)
  815. )
  816. def _handle_write(self) -> None:
  817. while True:
  818. size = len(self._write_buffer)
  819. if not size:
  820. break
  821. assert size > 0
  822. try:
  823. if _WINDOWS:
  824. # On windows, socket.send blows up if given a
  825. # write buffer that's too large, instead of just
  826. # returning the number of bytes it was able to
  827. # process. Therefore we must not call socket.send
  828. # with more than 128KB at a time.
  829. size = 128 * 1024
  830. num_bytes = self.write_to_fd(self._write_buffer.peek(size))
  831. if num_bytes == 0:
  832. break
  833. self._write_buffer.advance(num_bytes)
  834. self._total_write_done_index += num_bytes
  835. except BlockingIOError:
  836. break
  837. except OSError as e:
  838. if not self._is_connreset(e):
  839. # Broken pipe errors are usually caused by connection
  840. # reset, and its better to not log EPIPE errors to
  841. # minimize log spam
  842. gen_log.warning("Write error on %s: %s", self.fileno(), e)
  843. self.close(exc_info=e)
  844. return
  845. while self._write_futures:
  846. index, future = self._write_futures[0]
  847. if index > self._total_write_done_index:
  848. break
  849. self._write_futures.popleft()
  850. future_set_result_unless_cancelled(future, None)
  851. def _consume(self, loc: int) -> bytes:
  852. # Consume loc bytes from the read buffer and return them
  853. if loc == 0:
  854. return b""
  855. assert loc <= self._read_buffer_size
  856. # Slice the bytearray buffer into bytes, without intermediate copying
  857. b = (memoryview(self._read_buffer)[:loc]).tobytes()
  858. self._read_buffer_size -= loc
  859. del self._read_buffer[:loc]
  860. return b
  861. def _check_closed(self) -> None:
  862. if self.closed():
  863. raise StreamClosedError(real_error=self.error)
  864. def _maybe_add_error_listener(self) -> None:
  865. # This method is part of an optimization: to detect a connection that
  866. # is closed when we're not actively reading or writing, we must listen
  867. # for read events. However, it is inefficient to do this when the
  868. # connection is first established because we are going to read or write
  869. # immediately anyway. Instead, we insert checks at various times to
  870. # see if the connection is idle and add the read listener then.
  871. if self._state is None or self._state == ioloop.IOLoop.ERROR:
  872. if (
  873. not self.closed()
  874. and self._read_buffer_size == 0
  875. and self._close_callback is not None
  876. ):
  877. self._add_io_state(ioloop.IOLoop.READ)
  878. def _add_io_state(self, state: int) -> None:
  879. """Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler.
  880. Implementation notes: Reads and writes have a fast path and a
  881. slow path. The fast path reads synchronously from socket
  882. buffers, while the slow path uses `_add_io_state` to schedule
  883. an IOLoop callback.
  884. To detect closed connections, we must have called
  885. `_add_io_state` at some point, but we want to delay this as
  886. much as possible so we don't have to set an `IOLoop.ERROR`
  887. listener that will be overwritten by the next slow-path
  888. operation. If a sequence of fast-path ops do not end in a
  889. slow-path op, (e.g. for an @asynchronous long-poll request),
  890. we must add the error handler.
  891. TODO: reevaluate this now that callbacks are gone.
  892. """
  893. if self.closed():
  894. # connection has been closed, so there can be no future events
  895. return
  896. if self._state is None:
  897. self._state = ioloop.IOLoop.ERROR | state
  898. self.io_loop.add_handler(self.fileno(), self._handle_events, self._state)
  899. elif not self._state & state:
  900. self._state = self._state | state
  901. self.io_loop.update_handler(self.fileno(), self._state)
  902. def _is_connreset(self, exc: BaseException) -> bool:
  903. """Return ``True`` if exc is ECONNRESET or equivalent.
  904. May be overridden in subclasses.
  905. """
  906. return (
  907. isinstance(exc, (socket.error, IOError))
  908. and errno_from_exception(exc) in _ERRNO_CONNRESET
  909. )
  910. class IOStream(BaseIOStream):
  911. r"""Socket-based `IOStream` implementation.
  912. This class supports the read and write methods from `BaseIOStream`
  913. plus a `connect` method.
  914. The ``socket`` parameter may either be connected or unconnected.
  915. For server operations the socket is the result of calling
  916. `socket.accept <socket.socket.accept>`. For client operations the
  917. socket is created with `socket.socket`, and may either be
  918. connected before passing it to the `IOStream` or connected with
  919. `IOStream.connect`.
  920. A very simple (and broken) HTTP client using this class:
  921. .. testcode::
  922. import socket
  923. import tornado
  924. async def main():
  925. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  926. stream = tornado.iostream.IOStream(s)
  927. await stream.connect(("friendfeed.com", 80))
  928. await stream.write(b"GET / HTTP/1.0\r\nHost: friendfeed.com\r\n\r\n")
  929. header_data = await stream.read_until(b"\r\n\r\n")
  930. headers = {}
  931. for line in header_data.split(b"\r\n"):
  932. parts = line.split(b":")
  933. if len(parts) == 2:
  934. headers[parts[0].strip()] = parts[1].strip()
  935. body_data = await stream.read_bytes(int(headers[b"Content-Length"]))
  936. print(body_data)
  937. stream.close()
  938. if __name__ == '__main__':
  939. asyncio.run(main())
  940. """
  941. def __init__(self, socket: socket.socket, *args: Any, **kwargs: Any) -> None:
  942. self.socket = socket
  943. self.socket.setblocking(False)
  944. super().__init__(*args, **kwargs)
  945. def fileno(self) -> Union[int, ioloop._Selectable]:
  946. return self.socket
  947. def close_fd(self) -> None:
  948. self.socket.close()
  949. self.socket = None # type: ignore
  950. def get_fd_error(self) -> Optional[Exception]:
  951. errno = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  952. return socket.error(errno, os.strerror(errno))
  953. def read_from_fd(self, buf: Union[bytearray, memoryview]) -> Optional[int]:
  954. try:
  955. return self.socket.recv_into(buf, len(buf))
  956. except BlockingIOError:
  957. return None
  958. finally:
  959. del buf
  960. def write_to_fd(self, data: memoryview) -> int:
  961. try:
  962. return self.socket.send(data) # type: ignore
  963. finally:
  964. # Avoid keeping to data, which can be a memoryview.
  965. # See https://github.com/tornadoweb/tornado/pull/2008
  966. del data
  967. def connect(
  968. self: _IOStreamType, address: Any, server_hostname: Optional[str] = None
  969. ) -> "Future[_IOStreamType]":
  970. """Connects the socket to a remote address without blocking.
  971. May only be called if the socket passed to the constructor was
  972. not previously connected. The address parameter is in the
  973. same format as for `socket.connect <socket.socket.connect>` for
  974. the type of socket passed to the IOStream constructor,
  975. e.g. an ``(ip, port)`` tuple. Hostnames are accepted here,
  976. but will be resolved synchronously and block the IOLoop.
  977. If you have a hostname instead of an IP address, the `.TCPClient`
  978. class is recommended instead of calling this method directly.
  979. `.TCPClient` will do asynchronous DNS resolution and handle
  980. both IPv4 and IPv6.
  981. If ``callback`` is specified, it will be called with no
  982. arguments when the connection is completed; if not this method
  983. returns a `.Future` (whose result after a successful
  984. connection will be the stream itself).
  985. In SSL mode, the ``server_hostname`` parameter will be used
  986. for certificate validation (unless disabled in the
  987. ``ssl_options``) and SNI.
  988. Note that it is safe to call `IOStream.write
  989. <BaseIOStream.write>` while the connection is pending, in
  990. which case the data will be written as soon as the connection
  991. is ready. Calling `IOStream` read methods before the socket is
  992. connected works on some platforms but is non-portable.
  993. .. versionchanged:: 4.0
  994. If no callback is given, returns a `.Future`.
  995. .. versionchanged:: 4.2
  996. SSL certificates are validated by default; pass
  997. ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a
  998. suitably-configured `ssl.SSLContext` to the
  999. `SSLIOStream` constructor to disable.
  1000. .. versionchanged:: 6.0
  1001. The ``callback`` argument was removed. Use the returned
  1002. `.Future` instead.
  1003. """
  1004. self._connecting = True
  1005. future = Future() # type: Future[_IOStreamType]
  1006. self._connect_future = typing.cast("Future[IOStream]", future)
  1007. try:
  1008. self.socket.connect(address)
  1009. except BlockingIOError:
  1010. # In non-blocking mode we expect connect() to raise an
  1011. # exception with EINPROGRESS or EWOULDBLOCK.
  1012. pass
  1013. except OSError as e:
  1014. # On freebsd, other errors such as ECONNREFUSED may be
  1015. # returned immediately when attempting to connect to
  1016. # localhost, so handle them the same way as an error
  1017. # reported later in _handle_connect.
  1018. if future is None:
  1019. gen_log.warning("Connect error on fd %s: %s", self.socket.fileno(), e)
  1020. self.close(exc_info=e)
  1021. return future
  1022. self._add_io_state(self.io_loop.WRITE)
  1023. return future
  1024. def start_tls(
  1025. self,
  1026. server_side: bool,
  1027. ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,
  1028. server_hostname: Optional[str] = None,
  1029. ) -> Awaitable["SSLIOStream"]:
  1030. """Convert this `IOStream` to an `SSLIOStream`.
  1031. This enables protocols that begin in clear-text mode and
  1032. switch to SSL after some initial negotiation (such as the
  1033. ``STARTTLS`` extension to SMTP and IMAP).
  1034. This method cannot be used if there are outstanding reads
  1035. or writes on the stream, or if there is any data in the
  1036. IOStream's buffer (data in the operating system's socket
  1037. buffer is allowed). This means it must generally be used
  1038. immediately after reading or writing the last clear-text
  1039. data. It can also be used immediately after connecting,
  1040. before any reads or writes.
  1041. The ``ssl_options`` argument may be either an `ssl.SSLContext`
  1042. object or a dictionary of keyword arguments for the
  1043. `ssl.SSLContext.wrap_socket` function. The ``server_hostname`` argument
  1044. will be used for certificate validation unless disabled
  1045. in the ``ssl_options``.
  1046. This method returns a `.Future` whose result is the new
  1047. `SSLIOStream`. After this method has been called,
  1048. any other operation on the original stream is undefined.
  1049. If a close callback is defined on this stream, it will be
  1050. transferred to the new stream.
  1051. .. versionadded:: 4.0
  1052. .. versionchanged:: 4.2
  1053. SSL certificates are validated by default; pass
  1054. ``ssl_options=dict(cert_reqs=ssl.CERT_NONE)`` or a
  1055. suitably-configured `ssl.SSLContext` to disable.
  1056. """
  1057. if (
  1058. self._read_future
  1059. or self._write_futures
  1060. or self._connect_future
  1061. or self._closed
  1062. or self._read_buffer
  1063. or self._write_buffer
  1064. ):
  1065. raise ValueError("IOStream is not idle; cannot convert to SSL")
  1066. if ssl_options is None:
  1067. if server_side:
  1068. ssl_options = _server_ssl_defaults
  1069. else:
  1070. ssl_options = _client_ssl_defaults
  1071. socket = self.socket
  1072. self.io_loop.remove_handler(socket)
  1073. self.socket = None # type: ignore
  1074. socket = ssl_wrap_socket(
  1075. socket,
  1076. ssl_options,
  1077. server_hostname=server_hostname,
  1078. server_side=server_side,
  1079. do_handshake_on_connect=False,
  1080. )
  1081. orig_close_callback = self._close_callback
  1082. self._close_callback = None
  1083. future = Future() # type: Future[SSLIOStream]
  1084. ssl_stream = SSLIOStream(socket, ssl_options=ssl_options)
  1085. ssl_stream.set_close_callback(orig_close_callback)
  1086. ssl_stream._ssl_connect_future = future
  1087. ssl_stream.max_buffer_size = self.max_buffer_size
  1088. ssl_stream.read_chunk_size = self.read_chunk_size
  1089. return future
  1090. def _handle_connect(self) -> None:
  1091. try:
  1092. err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  1093. except OSError as e:
  1094. # Hurd doesn't allow SO_ERROR for loopback sockets because all
  1095. # errors for such sockets are reported synchronously.
  1096. if errno_from_exception(e) == errno.ENOPROTOOPT:
  1097. err = 0
  1098. if err != 0:
  1099. self.error = socket.error(err, os.strerror(err))
  1100. # IOLoop implementations may vary: some of them return
  1101. # an error state before the socket becomes writable, so
  1102. # in that case a connection failure would be handled by the
  1103. # error path in _handle_events instead of here.
  1104. if self._connect_future is None:
  1105. gen_log.warning(
  1106. "Connect error on fd %s: %s",
  1107. self.socket.fileno(),
  1108. errno.errorcode[err],
  1109. )
  1110. self.close()
  1111. return
  1112. if self._connect_future is not None:
  1113. future = self._connect_future
  1114. self._connect_future = None
  1115. future_set_result_unless_cancelled(future, self)
  1116. self._connecting = False
  1117. def set_nodelay(self, value: bool) -> None:
  1118. if self.socket is not None and self.socket.family in (
  1119. socket.AF_INET,
  1120. socket.AF_INET6,
  1121. ):
  1122. try:
  1123. self.socket.setsockopt(
  1124. socket.IPPROTO_TCP, socket.TCP_NODELAY, 1 if value else 0
  1125. )
  1126. except OSError as e:
  1127. # Sometimes setsockopt will fail if the socket is closed
  1128. # at the wrong time. This can happen with HTTPServer
  1129. # resetting the value to ``False`` between requests.
  1130. if e.errno != errno.EINVAL and not self._is_connreset(e):
  1131. raise
  1132. class SSLIOStream(IOStream):
  1133. """A utility class to write to and read from a non-blocking SSL socket.
  1134. If the socket passed to the constructor is already connected,
  1135. it should be wrapped with::
  1136. ssl.SSLContext(...).wrap_socket(sock, do_handshake_on_connect=False, **kwargs)
  1137. before constructing the `SSLIOStream`. Unconnected sockets will be
  1138. wrapped when `IOStream.connect` is finished.
  1139. """
  1140. socket = None # type: ssl.SSLSocket
  1141. def __init__(self, *args: Any, **kwargs: Any) -> None:
  1142. """The ``ssl_options`` keyword argument may either be an
  1143. `ssl.SSLContext` object or a dictionary of keywords arguments
  1144. for `ssl.SSLContext.wrap_socket`
  1145. """
  1146. self._ssl_options = kwargs.pop("ssl_options", _client_ssl_defaults)
  1147. super().__init__(*args, **kwargs)
  1148. self._ssl_accepting = True
  1149. self._handshake_reading = False
  1150. self._handshake_writing = False
  1151. self._server_hostname = None # type: Optional[str]
  1152. # If the socket is already connected, attempt to start the handshake.
  1153. try:
  1154. self.socket.getpeername()
  1155. except OSError:
  1156. pass
  1157. else:
  1158. # Indirectly start the handshake, which will run on the next
  1159. # IOLoop iteration and then the real IO state will be set in
  1160. # _handle_events.
  1161. self._add_io_state(self.io_loop.WRITE)
  1162. def reading(self) -> bool:
  1163. return self._handshake_reading or super().reading()
  1164. def writing(self) -> bool:
  1165. return self._handshake_writing or super().writing()
  1166. def _do_ssl_handshake(self) -> None:
  1167. # Based on code from test_ssl.py in the python stdlib
  1168. try:
  1169. self._handshake_reading = False
  1170. self._handshake_writing = False
  1171. self.socket.do_handshake()
  1172. except ssl.SSLError as err:
  1173. if err.args[0] == ssl.SSL_ERROR_WANT_READ:
  1174. self._handshake_reading = True
  1175. return
  1176. elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
  1177. self._handshake_writing = True
  1178. return
  1179. elif err.args[0] in (ssl.SSL_ERROR_EOF, ssl.SSL_ERROR_ZERO_RETURN):
  1180. return self.close(exc_info=err)
  1181. elif err.args[0] in (ssl.SSL_ERROR_SSL, ssl.SSL_ERROR_SYSCALL):
  1182. try:
  1183. peer = self.socket.getpeername()
  1184. except Exception:
  1185. peer = "(not connected)"
  1186. gen_log.warning(
  1187. "SSL Error on %s %s: %s", self.socket.fileno(), peer, err
  1188. )
  1189. return self.close(exc_info=err)
  1190. raise
  1191. except OSError as err:
  1192. # Some port scans (e.g. nmap in -sT mode) have been known
  1193. # to cause do_handshake to raise EBADF and ENOTCONN, so make
  1194. # those errors quiet as well.
  1195. # https://groups.google.com/forum/?fromgroups#!topic/python-tornado/ApucKJat1_0
  1196. # Errno 0 is also possible in some cases (nc -z).
  1197. # https://github.com/tornadoweb/tornado/issues/2504
  1198. if self._is_connreset(err) or err.args[0] in (
  1199. 0,
  1200. errno.EBADF,
  1201. errno.ENOTCONN,
  1202. ):
  1203. return self.close(exc_info=err)
  1204. raise
  1205. except AttributeError as err:
  1206. # On Linux, if the connection was reset before the call to
  1207. # wrap_socket, do_handshake will fail with an
  1208. # AttributeError.
  1209. return self.close(exc_info=err)
  1210. else:
  1211. self._ssl_accepting = False
  1212. # Prior to the introduction of SNI, this is where we would check
  1213. # the server's claimed hostname.
  1214. assert ssl.HAS_SNI
  1215. self._finish_ssl_connect()
  1216. def _finish_ssl_connect(self) -> None:
  1217. if self._ssl_connect_future is not None:
  1218. future = self._ssl_connect_future
  1219. self._ssl_connect_future = None
  1220. future_set_result_unless_cancelled(future, self)
  1221. def _handle_read(self) -> None:
  1222. if self._ssl_accepting:
  1223. self._do_ssl_handshake()
  1224. return
  1225. super()._handle_read()
  1226. def _handle_write(self) -> None:
  1227. if self._ssl_accepting:
  1228. self._do_ssl_handshake()
  1229. return
  1230. super()._handle_write()
  1231. def connect(
  1232. self, address: Tuple, server_hostname: Optional[str] = None
  1233. ) -> "Future[SSLIOStream]":
  1234. self._server_hostname = server_hostname
  1235. # Ignore the result of connect(). If it fails,
  1236. # wait_for_handshake will raise an error too. This is
  1237. # necessary for the old semantics of the connect callback
  1238. # (which takes no arguments). In 6.0 this can be refactored to
  1239. # be a regular coroutine.
  1240. # TODO: This is trickier than it looks, since if write()
  1241. # is called with a connect() pending, we want the connect
  1242. # to resolve before the write. Or do we care about this?
  1243. # (There's a test for it, but I think in practice users
  1244. # either wait for the connect before performing a write or
  1245. # they don't care about the connect Future at all)
  1246. fut = super().connect(address)
  1247. fut.add_done_callback(lambda f: f.exception())
  1248. return self.wait_for_handshake()
  1249. def _handle_connect(self) -> None:
  1250. # Call the superclass method to check for errors.
  1251. super()._handle_connect()
  1252. if self.closed():
  1253. return
  1254. # When the connection is complete, wrap the socket for SSL
  1255. # traffic. Note that we do this by overriding _handle_connect
  1256. # instead of by passing a callback to super().connect because
  1257. # user callbacks are enqueued asynchronously on the IOLoop,
  1258. # but since _handle_events calls _handle_connect immediately
  1259. # followed by _handle_write we need this to be synchronous.
  1260. #
  1261. # The IOLoop will get confused if we swap out self.socket while the
  1262. # fd is registered, so remove it now and re-register after
  1263. # wrap_socket().
  1264. self.io_loop.remove_handler(self.socket)
  1265. old_state = self._state
  1266. assert old_state is not None
  1267. self._state = None
  1268. self.socket = ssl_wrap_socket(
  1269. self.socket,
  1270. self._ssl_options,
  1271. server_hostname=self._server_hostname,
  1272. do_handshake_on_connect=False,
  1273. server_side=False,
  1274. )
  1275. self._add_io_state(old_state)
  1276. def wait_for_handshake(self) -> "Future[SSLIOStream]":
  1277. """Wait for the initial SSL handshake to complete.
  1278. If a ``callback`` is given, it will be called with no
  1279. arguments once the handshake is complete; otherwise this
  1280. method returns a `.Future` which will resolve to the
  1281. stream itself after the handshake is complete.
  1282. Once the handshake is complete, information such as
  1283. the peer's certificate and NPN/ALPN selections may be
  1284. accessed on ``self.socket``.
  1285. This method is intended for use on server-side streams
  1286. or after using `IOStream.start_tls`; it should not be used
  1287. with `IOStream.connect` (which already waits for the
  1288. handshake to complete). It may only be called once per stream.
  1289. .. versionadded:: 4.2
  1290. .. versionchanged:: 6.0
  1291. The ``callback`` argument was removed. Use the returned
  1292. `.Future` instead.
  1293. """
  1294. if self._ssl_connect_future is not None:
  1295. raise RuntimeError("Already waiting")
  1296. future = self._ssl_connect_future = Future()
  1297. if not self._ssl_accepting:
  1298. self._finish_ssl_connect()
  1299. return future
  1300. def write_to_fd(self, data: memoryview) -> int:
  1301. # clip buffer size at 1GB since SSL sockets only support upto 2GB
  1302. # this change in behaviour is transparent, since the function is
  1303. # already expected to (possibly) write less than the provided buffer
  1304. if len(data) >> 30:
  1305. data = memoryview(data)[: 1 << 30]
  1306. try:
  1307. return self.socket.send(data) # type: ignore
  1308. except ssl.SSLError as e:
  1309. if e.args[0] == ssl.SSL_ERROR_WANT_WRITE:
  1310. # In Python 3.5+, SSLSocket.send raises a WANT_WRITE error if
  1311. # the socket is not writeable; we need to transform this into
  1312. # an EWOULDBLOCK socket.error or a zero return value,
  1313. # either of which will be recognized by the caller of this
  1314. # method. Prior to Python 3.5, an unwriteable socket would
  1315. # simply return 0 bytes written.
  1316. return 0
  1317. raise
  1318. finally:
  1319. # Avoid keeping to data, which can be a memoryview.
  1320. # See https://github.com/tornadoweb/tornado/pull/2008
  1321. del data
  1322. def read_from_fd(self, buf: Union[bytearray, memoryview]) -> Optional[int]:
  1323. try:
  1324. if self._ssl_accepting:
  1325. # If the handshake hasn't finished yet, there can't be anything
  1326. # to read (attempting to read may or may not raise an exception
  1327. # depending on the SSL version)
  1328. return None
  1329. # clip buffer size at 1GB since SSL sockets only support upto 2GB
  1330. # this change in behaviour is transparent, since the function is
  1331. # already expected to (possibly) read less than the provided buffer
  1332. if len(buf) >> 30:
  1333. buf = memoryview(buf)[: 1 << 30]
  1334. try:
  1335. return self.socket.recv_into(buf, len(buf))
  1336. except ssl.SSLError as e:
  1337. # SSLError is a subclass of socket.error, so this except
  1338. # block must come first.
  1339. if e.args[0] == ssl.SSL_ERROR_WANT_READ:
  1340. return None
  1341. else:
  1342. raise
  1343. except BlockingIOError:
  1344. return None
  1345. finally:
  1346. del buf
  1347. def _is_connreset(self, e: BaseException) -> bool:
  1348. if isinstance(e, ssl.SSLError) and e.args[0] == ssl.SSL_ERROR_EOF:
  1349. return True
  1350. return super()._is_connreset(e)
  1351. class PipeIOStream(BaseIOStream):
  1352. """Pipe-based `IOStream` implementation.
  1353. The constructor takes an integer file descriptor (such as one returned
  1354. by `os.pipe`) rather than an open file object. Pipes are generally
  1355. one-way, so a `PipeIOStream` can be used for reading or writing but not
  1356. both.
  1357. ``PipeIOStream`` is only available on Unix-based platforms.
  1358. """
  1359. def __init__(self, fd: int, *args: Any, **kwargs: Any) -> None:
  1360. self.fd = fd
  1361. self._fio = io.FileIO(self.fd, "r+")
  1362. if sys.platform == "win32":
  1363. # The form and placement of this assertion is important to mypy.
  1364. # A plain assert statement isn't recognized here. If the assertion
  1365. # were earlier it would worry that the attributes of self aren't
  1366. # set on windows. If it were missing it would complain about
  1367. # the absence of the set_blocking function.
  1368. raise AssertionError("PipeIOStream is not supported on Windows")
  1369. os.set_blocking(fd, False)
  1370. super().__init__(*args, **kwargs)
  1371. def fileno(self) -> int:
  1372. return self.fd
  1373. def close_fd(self) -> None:
  1374. self._fio.close()
  1375. def write_to_fd(self, data: memoryview) -> int:
  1376. try:
  1377. return os.write(self.fd, data) # type: ignore
  1378. finally:
  1379. # Avoid keeping to data, which can be a memoryview.
  1380. # See https://github.com/tornadoweb/tornado/pull/2008
  1381. del data
  1382. def read_from_fd(self, buf: Union[bytearray, memoryview]) -> Optional[int]:
  1383. try:
  1384. return self._fio.readinto(buf) # type: ignore
  1385. except OSError as e:
  1386. if errno_from_exception(e) == errno.EBADF:
  1387. # If the writing half of a pipe is closed, select will
  1388. # report it as readable but reads will fail with EBADF.
  1389. self.close(exc_info=e)
  1390. return None
  1391. else:
  1392. raise
  1393. finally:
  1394. del buf
  1395. def doctests() -> Any:
  1396. import doctest
  1397. return doctest.DocTestSuite()