iostream.py 64 KB

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