abstract.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. # -*- test-case-name: twisted.test.test_abstract -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Support for generic select()able objects.
  6. """
  7. from __future__ import division, absolute_import
  8. from socket import AF_INET, AF_INET6, inet_pton, error
  9. from zope.interface import implementer
  10. # Twisted Imports
  11. from twisted.python.compat import _PY3, unicode, lazyByteSlice
  12. from twisted.python import reflect, failure
  13. from twisted.internet import interfaces, main
  14. if _PY3:
  15. def _concatenate(bObj, offset, bArray):
  16. # Python 3 lacks the buffer() builtin and the other primitives don't
  17. # help in this case. Just do the copy. Perhaps later these buffers can
  18. # be joined and FileDescriptor can use writev(). Or perhaps bytearrays
  19. # would help.
  20. return bObj[offset:] + b"".join(bArray)
  21. else:
  22. def _concatenate(bObj, offset, bArray):
  23. # Avoid one extra string copy by using a buffer to limit what we include
  24. # in the result.
  25. return buffer(bObj, offset) + b"".join(bArray)
  26. class _ConsumerMixin(object):
  27. """
  28. L{IConsumer} implementations can mix this in to get C{registerProducer} and
  29. C{unregisterProducer} methods which take care of keeping track of a
  30. producer's state.
  31. Subclasses must provide three attributes which L{_ConsumerMixin} will read
  32. but not write:
  33. - connected: A C{bool} which is C{True} as long as the consumer has
  34. someplace to send bytes (for example, a TCP connection), and then
  35. C{False} when it no longer does.
  36. - disconnecting: A C{bool} which is C{False} until something like
  37. L{ITransport.loseConnection} is called, indicating that the send buffer
  38. should be flushed and the connection lost afterwards. Afterwards,
  39. C{True}.
  40. - disconnected: A C{bool} which is C{False} until the consumer no longer
  41. has a place to send bytes, then C{True}.
  42. Subclasses must also override the C{startWriting} method.
  43. @ivar producer: L{None} if no producer is registered, otherwise the
  44. registered producer.
  45. @ivar producerPaused: A flag indicating whether the producer is currently
  46. paused.
  47. @type producerPaused: L{bool}
  48. @ivar streamingProducer: A flag indicating whether the producer was
  49. registered as a streaming (ie push) producer or not (ie a pull
  50. producer). This will determine whether the consumer may ever need to
  51. pause and resume it, or if it can merely call C{resumeProducing} on it
  52. when buffer space is available.
  53. @ivar streamingProducer: C{bool} or C{int}
  54. """
  55. producer = None
  56. producerPaused = False
  57. streamingProducer = False
  58. def startWriting(self):
  59. """
  60. Override in a subclass to cause the reactor to monitor this selectable
  61. for write events. This will be called once in C{unregisterProducer} if
  62. C{loseConnection} has previously been called, so that the connection can
  63. actually close.
  64. """
  65. raise NotImplementedError("%r did not implement startWriting")
  66. def registerProducer(self, producer, streaming):
  67. """
  68. Register to receive data from a producer.
  69. This sets this selectable to be a consumer for a producer. When this
  70. selectable runs out of data on a write() call, it will ask the producer
  71. to resumeProducing(). When the FileDescriptor's internal data buffer is
  72. filled, it will ask the producer to pauseProducing(). If the connection
  73. is lost, FileDescriptor calls producer's stopProducing() method.
  74. If streaming is true, the producer should provide the IPushProducer
  75. interface. Otherwise, it is assumed that producer provides the
  76. IPullProducer interface. In this case, the producer won't be asked to
  77. pauseProducing(), but it has to be careful to write() data only when its
  78. resumeProducing() method is called.
  79. """
  80. if self.producer is not None:
  81. raise RuntimeError(
  82. "Cannot register producer %s, because producer %s was never "
  83. "unregistered." % (producer, self.producer))
  84. if self.disconnected:
  85. producer.stopProducing()
  86. else:
  87. self.producer = producer
  88. self.streamingProducer = streaming
  89. if not streaming:
  90. producer.resumeProducing()
  91. def unregisterProducer(self):
  92. """
  93. Stop consuming data from a producer, without disconnecting.
  94. """
  95. self.producer = None
  96. if self.connected and self.disconnecting:
  97. self.startWriting()
  98. @implementer(interfaces.ILoggingContext)
  99. class _LogOwner(object):
  100. """
  101. Mixin to help implement L{interfaces.ILoggingContext} for transports which
  102. have a protocol, the log prefix of which should also appear in the
  103. transport's log prefix.
  104. """
  105. def _getLogPrefix(self, applicationObject):
  106. """
  107. Determine the log prefix to use for messages related to
  108. C{applicationObject}, which may or may not be an
  109. L{interfaces.ILoggingContext} provider.
  110. @return: A C{str} giving the log prefix to use.
  111. """
  112. if interfaces.ILoggingContext.providedBy(applicationObject):
  113. return applicationObject.logPrefix()
  114. return applicationObject.__class__.__name__
  115. def logPrefix(self):
  116. """
  117. Override this method to insert custom logging behavior. Its
  118. return value will be inserted in front of every line. It may
  119. be called more times than the number of output lines.
  120. """
  121. return "-"
  122. @implementer(
  123. interfaces.IPushProducer, interfaces.IReadWriteDescriptor,
  124. interfaces.IConsumer, interfaces.ITransport,
  125. interfaces.IHalfCloseableDescriptor)
  126. class FileDescriptor(_ConsumerMixin, _LogOwner):
  127. """
  128. An object which can be operated on by select().
  129. This is an abstract superclass of all objects which may be notified when
  130. they are readable or writable; e.g. they have a file-descriptor that is
  131. valid to be passed to select(2).
  132. """
  133. connected = 0
  134. disconnected = 0
  135. disconnecting = 0
  136. _writeDisconnecting = False
  137. _writeDisconnected = False
  138. dataBuffer = b""
  139. offset = 0
  140. SEND_LIMIT = 128*1024
  141. def __init__(self, reactor=None):
  142. """
  143. @param reactor: An L{IReactorFDSet} provider which this descriptor will
  144. use to get readable and writeable event notifications. If no value
  145. is given, the global reactor will be used.
  146. """
  147. if not reactor:
  148. from twisted.internet import reactor
  149. self.reactor = reactor
  150. self._tempDataBuffer = [] # will be added to dataBuffer in doWrite
  151. self._tempDataLen = 0
  152. def connectionLost(self, reason):
  153. """The connection was lost.
  154. This is called when the connection on a selectable object has been
  155. lost. It will be called whether the connection was closed explicitly,
  156. an exception occurred in an event handler, or the other end of the
  157. connection closed it first.
  158. Clean up state here, but make sure to call back up to FileDescriptor.
  159. """
  160. self.disconnected = 1
  161. self.connected = 0
  162. if self.producer is not None:
  163. self.producer.stopProducing()
  164. self.producer = None
  165. self.stopReading()
  166. self.stopWriting()
  167. def writeSomeData(self, data):
  168. """
  169. Write as much as possible of the given data, immediately.
  170. This is called to invoke the lower-level writing functionality, such
  171. as a socket's send() method, or a file's write(); this method
  172. returns an integer or an exception. If an integer, it is the number
  173. of bytes written (possibly zero); if an exception, it indicates the
  174. connection was lost.
  175. """
  176. raise NotImplementedError("%s does not implement writeSomeData" %
  177. reflect.qual(self.__class__))
  178. def doRead(self):
  179. """
  180. Called when data is available for reading.
  181. Subclasses must override this method. The result will be interpreted
  182. in the same way as a result of doWrite().
  183. """
  184. raise NotImplementedError("%s does not implement doRead" %
  185. reflect.qual(self.__class__))
  186. def doWrite(self):
  187. """
  188. Called when data can be written.
  189. @return: L{None} on success, an exception or a negative integer on
  190. failure.
  191. @see: L{twisted.internet.interfaces.IWriteDescriptor.doWrite}.
  192. """
  193. if len(self.dataBuffer) - self.offset < self.SEND_LIMIT:
  194. # If there is currently less than SEND_LIMIT bytes left to send
  195. # in the string, extend it with the array data.
  196. self.dataBuffer = _concatenate(
  197. self.dataBuffer, self.offset, self._tempDataBuffer)
  198. self.offset = 0
  199. self._tempDataBuffer = []
  200. self._tempDataLen = 0
  201. # Send as much data as you can.
  202. if self.offset:
  203. l = self.writeSomeData(lazyByteSlice(self.dataBuffer, self.offset))
  204. else:
  205. l = self.writeSomeData(self.dataBuffer)
  206. # There is no writeSomeData implementation in Twisted which returns
  207. # < 0, but the documentation for writeSomeData used to claim negative
  208. # integers meant connection lost. Keep supporting this here,
  209. # although it may be worth deprecating and removing at some point.
  210. if isinstance(l, Exception) or l < 0:
  211. return l
  212. self.offset += l
  213. # If there is nothing left to send,
  214. if self.offset == len(self.dataBuffer) and not self._tempDataLen:
  215. self.dataBuffer = b""
  216. self.offset = 0
  217. # stop writing.
  218. self.stopWriting()
  219. # If I've got a producer who is supposed to supply me with data,
  220. if self.producer is not None and ((not self.streamingProducer)
  221. or self.producerPaused):
  222. # tell them to supply some more.
  223. self.producerPaused = False
  224. self.producer.resumeProducing()
  225. elif self.disconnecting:
  226. # But if I was previously asked to let the connection die, do
  227. # so.
  228. return self._postLoseConnection()
  229. elif self._writeDisconnecting:
  230. # I was previously asked to half-close the connection. We
  231. # set _writeDisconnected before calling handler, in case the
  232. # handler calls loseConnection(), which will want to check for
  233. # this attribute.
  234. self._writeDisconnected = True
  235. result = self._closeWriteConnection()
  236. return result
  237. return None
  238. def _postLoseConnection(self):
  239. """Called after a loseConnection(), when all data has been written.
  240. Whatever this returns is then returned by doWrite.
  241. """
  242. # default implementation, telling reactor we're finished
  243. return main.CONNECTION_DONE
  244. def _closeWriteConnection(self):
  245. # override in subclasses
  246. pass
  247. def writeConnectionLost(self, reason):
  248. # in current code should never be called
  249. self.connectionLost(reason)
  250. def readConnectionLost(self, reason):
  251. # override in subclasses
  252. self.connectionLost(reason)
  253. def _isSendBufferFull(self):
  254. """
  255. Determine whether the user-space send buffer for this transport is full
  256. or not.
  257. When the buffer contains more than C{self.bufferSize} bytes, it is
  258. considered full. This might be improved by considering the size of the
  259. kernel send buffer and how much of it is free.
  260. @return: C{True} if it is full, C{False} otherwise.
  261. """
  262. return len(self.dataBuffer) + self._tempDataLen > self.bufferSize
  263. def _maybePauseProducer(self):
  264. """
  265. Possibly pause a producer, if there is one and the send buffer is full.
  266. """
  267. # If we are responsible for pausing our producer,
  268. if self.producer is not None and self.streamingProducer:
  269. # and our buffer is full,
  270. if self._isSendBufferFull():
  271. # pause it.
  272. self.producerPaused = True
  273. self.producer.pauseProducing()
  274. def write(self, data):
  275. """Reliably write some data.
  276. The data is buffered until the underlying file descriptor is ready
  277. for writing. If there is more than C{self.bufferSize} data in the
  278. buffer and this descriptor has a registered streaming producer, its
  279. C{pauseProducing()} method will be called.
  280. """
  281. if isinstance(data, unicode): # no, really, I mean it
  282. raise TypeError("Data must not be unicode")
  283. if not self.connected or self._writeDisconnected:
  284. return
  285. if data:
  286. self._tempDataBuffer.append(data)
  287. self._tempDataLen += len(data)
  288. self._maybePauseProducer()
  289. self.startWriting()
  290. def writeSequence(self, iovec):
  291. """
  292. Reliably write a sequence of data.
  293. Currently, this is a convenience method roughly equivalent to::
  294. for chunk in iovec:
  295. fd.write(chunk)
  296. It may have a more efficient implementation at a later time or in a
  297. different reactor.
  298. As with the C{write()} method, if a buffer size limit is reached and a
  299. streaming producer is registered, it will be paused until the buffered
  300. data is written to the underlying file descriptor.
  301. """
  302. for i in iovec:
  303. if isinstance(i, unicode): # no, really, I mean it
  304. raise TypeError("Data must not be unicode")
  305. if not self.connected or not iovec or self._writeDisconnected:
  306. return
  307. self._tempDataBuffer.extend(iovec)
  308. for i in iovec:
  309. self._tempDataLen += len(i)
  310. self._maybePauseProducer()
  311. self.startWriting()
  312. def loseConnection(self, _connDone=failure.Failure(main.CONNECTION_DONE)):
  313. """Close the connection at the next available opportunity.
  314. Call this to cause this FileDescriptor to lose its connection. It will
  315. first write any data that it has buffered.
  316. If there is data buffered yet to be written, this method will cause the
  317. transport to lose its connection as soon as it's done flushing its
  318. write buffer. If you have a producer registered, the connection won't
  319. be closed until the producer is finished. Therefore, make sure you
  320. unregister your producer when it's finished, or the connection will
  321. never close.
  322. """
  323. if self.connected and not self.disconnecting:
  324. if self._writeDisconnected:
  325. # doWrite won't trigger the connection close anymore
  326. self.stopReading()
  327. self.stopWriting()
  328. self.connectionLost(_connDone)
  329. else:
  330. self.stopReading()
  331. self.startWriting()
  332. self.disconnecting = 1
  333. def loseWriteConnection(self):
  334. self._writeDisconnecting = True
  335. self.startWriting()
  336. def stopReading(self):
  337. """Stop waiting for read availability.
  338. Call this to remove this selectable from being notified when it is
  339. ready for reading.
  340. """
  341. self.reactor.removeReader(self)
  342. def stopWriting(self):
  343. """Stop waiting for write availability.
  344. Call this to remove this selectable from being notified when it is ready
  345. for writing.
  346. """
  347. self.reactor.removeWriter(self)
  348. def startReading(self):
  349. """Start waiting for read availability.
  350. """
  351. self.reactor.addReader(self)
  352. def startWriting(self):
  353. """Start waiting for write availability.
  354. Call this to have this FileDescriptor be notified whenever it is ready for
  355. writing.
  356. """
  357. self.reactor.addWriter(self)
  358. # Producer/consumer implementation
  359. # first, the consumer stuff. This requires no additional work, as
  360. # any object you can write to can be a consumer, really.
  361. producer = None
  362. bufferSize = 2**2**2**2
  363. def stopConsuming(self):
  364. """Stop consuming data.
  365. This is called when a producer has lost its connection, to tell the
  366. consumer to go lose its connection (and break potential circular
  367. references).
  368. """
  369. self.unregisterProducer()
  370. self.loseConnection()
  371. # producer interface implementation
  372. def resumeProducing(self):
  373. if self.connected and not self.disconnecting:
  374. self.startReading()
  375. def pauseProducing(self):
  376. self.stopReading()
  377. def stopProducing(self):
  378. self.loseConnection()
  379. def fileno(self):
  380. """File Descriptor number for select().
  381. This method must be overridden or assigned in subclasses to
  382. indicate a valid file descriptor for the operating system.
  383. """
  384. return -1
  385. def isIPAddress(addr, family=AF_INET):
  386. """
  387. Determine whether the given string represents an IP address of the given
  388. family; by default, an IPv4 address.
  389. @type addr: C{str}
  390. @param addr: A string which may or may not be the decimal dotted
  391. representation of an IPv4 address.
  392. @param family: The address family to test for; one of the C{AF_*} constants
  393. from the L{socket} module. (This parameter has only been available
  394. since Twisted 17.1.0; previously L{isIPAddress} could only test for IPv4
  395. addresses.)
  396. @type family: C{int}
  397. @rtype: C{bool}
  398. @return: C{True} if C{addr} represents an IPv4 address, C{False} otherwise.
  399. """
  400. if isinstance(addr, bytes):
  401. try:
  402. addr = addr.decode("ascii")
  403. except UnicodeDecodeError:
  404. return False
  405. if family == AF_INET6:
  406. # On some platforms, inet_ntop fails unless the scope ID is valid; this
  407. # is a test for whether the given string *is* an IP address, so strip
  408. # any potential scope ID before checking.
  409. addr = addr.split(u"%", 1)[0]
  410. elif family == AF_INET:
  411. # On Windows, where 3.5+ implement inet_pton, "0" is considered a valid
  412. # IPv4 address, but we want to ensure we have all 4 segments.
  413. if addr.count(u".") != 3:
  414. return False
  415. else:
  416. raise ValueError("unknown address family {!r}".format(family))
  417. try:
  418. # This might be a native implementation or the one from
  419. # twisted.python.compat.
  420. inet_pton(family, addr)
  421. except (ValueError, error):
  422. return False
  423. return True
  424. def isIPv6Address(addr):
  425. """
  426. Determine whether the given string represents an IPv6 address.
  427. @param addr: A string which may or may not be the hex
  428. representation of an IPv6 address.
  429. @type addr: C{str}
  430. @return: C{True} if C{addr} represents an IPv6 address, C{False}
  431. otherwise.
  432. @rtype: C{bool}
  433. """
  434. return isIPAddress(addr, AF_INET6)
  435. __all__ = ["FileDescriptor", "isIPAddress", "isIPv6Address"]