abstract.py 19 KB

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