iostream.py 70 KB

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