protocol.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. # -*- test-case-name: twisted.test.test_factories,twisted.internet.test.test_protocol -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Standard implementations of Twisted protocol-related interfaces.
  6. Start here if you are looking to write a new protocol implementation for
  7. Twisted. The Protocol class contains some introductory material.
  8. """
  9. from __future__ import annotations
  10. import random
  11. from typing import Any, Callable, Optional
  12. from zope.interface import implementer
  13. from twisted.internet import defer, error, interfaces
  14. from twisted.internet.interfaces import (
  15. IAddress,
  16. IMulticastTransport,
  17. ITransport,
  18. IUDPTransport,
  19. )
  20. from twisted.logger import _loggerFor
  21. from twisted.python import components, failure, log
  22. @implementer(interfaces.IProtocolFactory, interfaces.ILoggingContext)
  23. class Factory:
  24. """
  25. This is a factory which produces protocols.
  26. By default, buildProtocol will create a protocol of the class given in
  27. self.protocol.
  28. """
  29. protocol: "Optional[Callable[[], Protocol]]" = None
  30. numPorts = 0
  31. noisy = True
  32. @classmethod
  33. def forProtocol(cls, protocol, *args, **kwargs):
  34. """
  35. Create a factory for the given protocol.
  36. It sets the C{protocol} attribute and returns the constructed factory
  37. instance.
  38. @param protocol: A L{Protocol} subclass
  39. @param args: Positional arguments for the factory.
  40. @param kwargs: Keyword arguments for the factory.
  41. @return: A L{Factory} instance wired up to C{protocol}.
  42. """
  43. factory = cls(*args, **kwargs)
  44. factory.protocol = protocol
  45. return factory
  46. def logPrefix(self):
  47. """
  48. Describe this factory for log messages.
  49. """
  50. return self.__class__.__name__
  51. def doStart(self):
  52. """
  53. Make sure startFactory is called.
  54. Users should not call this function themselves!
  55. """
  56. if not self.numPorts:
  57. if self.noisy:
  58. _loggerFor(self).info("Starting factory {factory!r}", factory=self)
  59. self.startFactory()
  60. self.numPorts = self.numPorts + 1
  61. def doStop(self):
  62. """
  63. Make sure stopFactory is called.
  64. Users should not call this function themselves!
  65. """
  66. if self.numPorts == 0:
  67. # This shouldn't happen, but does sometimes and this is better
  68. # than blowing up in assert as we did previously.
  69. return
  70. self.numPorts = self.numPorts - 1
  71. if not self.numPorts:
  72. if self.noisy:
  73. _loggerFor(self).info("Stopping factory {factory!r}", factory=self)
  74. self.stopFactory()
  75. def startFactory(self):
  76. """
  77. This will be called before I begin listening on a Port or Connector.
  78. It will only be called once, even if the factory is connected
  79. to multiple ports.
  80. This can be used to perform 'unserialization' tasks that
  81. are best put off until things are actually running, such
  82. as connecting to a database, opening files, etcetera.
  83. """
  84. def stopFactory(self):
  85. """
  86. This will be called before I stop listening on all Ports/Connectors.
  87. This can be overridden to perform 'shutdown' tasks such as disconnecting
  88. database connections, closing files, etc.
  89. It will be called, for example, before an application shuts down,
  90. if it was connected to a port. User code should not call this function
  91. directly.
  92. """
  93. def buildProtocol(self, addr: IAddress) -> "Optional[Protocol]":
  94. """
  95. Create an instance of a subclass of Protocol.
  96. The returned instance will handle input on an incoming server
  97. connection, and an attribute "factory" pointing to the creating
  98. factory.
  99. Alternatively, L{None} may be returned to immediately close the
  100. new connection.
  101. Override this method to alter how Protocol instances get created.
  102. @param addr: an object implementing L{IAddress}
  103. """
  104. assert self.protocol is not None
  105. p = self.protocol()
  106. p.factory = self
  107. return p
  108. class ClientFactory(Factory):
  109. """
  110. A Protocol factory for clients.
  111. This can be used together with the various connectXXX methods in
  112. reactors.
  113. """
  114. def startedConnecting(self, connector):
  115. """
  116. Called when a connection has been started.
  117. You can call connector.stopConnecting() to stop the connection attempt.
  118. @param connector: a Connector object.
  119. """
  120. def clientConnectionFailed(self, connector, reason):
  121. """
  122. Called when a connection has failed to connect.
  123. It may be useful to call connector.connect() - this will reconnect.
  124. @type reason: L{twisted.python.failure.Failure}
  125. """
  126. def clientConnectionLost(self, connector, reason):
  127. """
  128. Called when an established connection is lost.
  129. It may be useful to call connector.connect() - this will reconnect.
  130. @type reason: L{twisted.python.failure.Failure}
  131. """
  132. class _InstanceFactory(ClientFactory):
  133. """
  134. Factory used by ClientCreator.
  135. @ivar deferred: The L{Deferred} which represents this connection attempt and
  136. which will be fired when it succeeds or fails.
  137. @ivar pending: After a connection attempt succeeds or fails, a delayed call
  138. which will fire the L{Deferred} representing this connection attempt.
  139. """
  140. noisy = False
  141. pending = None
  142. def __init__(self, reactor, instance, deferred):
  143. self.reactor = reactor
  144. self.instance = instance
  145. self.deferred = deferred
  146. def __repr__(self) -> str:
  147. return f"<ClientCreator factory: {self.instance!r}>"
  148. def buildProtocol(self, addr):
  149. """
  150. Return the pre-constructed protocol instance and arrange to fire the
  151. waiting L{Deferred} to indicate success establishing the connection.
  152. """
  153. self.pending = self.reactor.callLater(
  154. 0, self.fire, self.deferred.callback, self.instance
  155. )
  156. self.deferred = None
  157. return self.instance
  158. def clientConnectionFailed(self, connector, reason):
  159. """
  160. Arrange to fire the waiting L{Deferred} with the given failure to
  161. indicate the connection could not be established.
  162. """
  163. self.pending = self.reactor.callLater(
  164. 0, self.fire, self.deferred.errback, reason
  165. )
  166. self.deferred = None
  167. def fire(self, func, value):
  168. """
  169. Clear C{self.pending} to avoid a reference cycle and then invoke func
  170. with the value.
  171. """
  172. self.pending = None
  173. func(value)
  174. class ClientCreator:
  175. """
  176. Client connections that do not require a factory.
  177. The various connect* methods create a protocol instance using the given
  178. protocol class and arguments, and connect it, returning a Deferred of the
  179. resulting protocol instance.
  180. Useful for cases when we don't really need a factory. Mainly this
  181. is when there is no shared state between protocol instances, and no need
  182. to reconnect.
  183. The C{connectTCP}, C{connectUNIX}, and C{connectSSL} methods each return a
  184. L{Deferred} which will fire with an instance of the protocol class passed to
  185. L{ClientCreator.__init__}. These Deferred can be cancelled to abort the
  186. connection attempt (in a very unlikely case, cancelling the Deferred may not
  187. prevent the protocol from being instantiated and connected to a transport;
  188. if this happens, it will be disconnected immediately afterwards and the
  189. Deferred will still errback with L{CancelledError}).
  190. """
  191. def __init__(self, reactor, protocolClass, *args, **kwargs):
  192. self.reactor = reactor
  193. self.protocolClass = protocolClass
  194. self.args = args
  195. self.kwargs = kwargs
  196. def _connect(self, method, *args, **kwargs):
  197. """
  198. Initiate a connection attempt.
  199. @param method: A callable which will actually start the connection
  200. attempt. For example, C{reactor.connectTCP}.
  201. @param args: Positional arguments to pass to C{method}, excluding the
  202. factory.
  203. @param kwargs: Keyword arguments to pass to C{method}.
  204. @return: A L{Deferred} which fires with an instance of the protocol
  205. class passed to this L{ClientCreator}'s initializer or fails if the
  206. connection cannot be set up for some reason.
  207. """
  208. def cancelConnect(deferred):
  209. connector.disconnect()
  210. if f.pending is not None:
  211. f.pending.cancel()
  212. d = defer.Deferred(cancelConnect)
  213. f = _InstanceFactory(
  214. self.reactor, self.protocolClass(*self.args, **self.kwargs), d
  215. )
  216. connector = method(factory=f, *args, **kwargs)
  217. return d
  218. def connectTCP(self, host, port, timeout=30, bindAddress=None):
  219. """
  220. Connect to a TCP server.
  221. The parameters are all the same as to L{IReactorTCP.connectTCP} except
  222. that the factory parameter is omitted.
  223. @return: A L{Deferred} which fires with an instance of the protocol
  224. class passed to this L{ClientCreator}'s initializer or fails if the
  225. connection cannot be set up for some reason.
  226. """
  227. return self._connect(
  228. self.reactor.connectTCP,
  229. host,
  230. port,
  231. timeout=timeout,
  232. bindAddress=bindAddress,
  233. )
  234. def connectUNIX(self, address, timeout=30, checkPID=False):
  235. """
  236. Connect to a Unix socket.
  237. The parameters are all the same as to L{IReactorUNIX.connectUNIX} except
  238. that the factory parameter is omitted.
  239. @return: A L{Deferred} which fires with an instance of the protocol
  240. class passed to this L{ClientCreator}'s initializer or fails if the
  241. connection cannot be set up for some reason.
  242. """
  243. return self._connect(
  244. self.reactor.connectUNIX, address, timeout=timeout, checkPID=checkPID
  245. )
  246. def connectSSL(self, host, port, contextFactory, timeout=30, bindAddress=None):
  247. """
  248. Connect to an SSL server.
  249. The parameters are all the same as to L{IReactorSSL.connectSSL} except
  250. that the factory parameter is omitted.
  251. @return: A L{Deferred} which fires with an instance of the protocol
  252. class passed to this L{ClientCreator}'s initializer or fails if the
  253. connection cannot be set up for some reason.
  254. """
  255. return self._connect(
  256. self.reactor.connectSSL,
  257. host,
  258. port,
  259. contextFactory=contextFactory,
  260. timeout=timeout,
  261. bindAddress=bindAddress,
  262. )
  263. class ReconnectingClientFactory(ClientFactory):
  264. """
  265. Factory which auto-reconnects clients with an exponential back-off.
  266. Note that clients should call my resetDelay method after they have
  267. connected successfully.
  268. @ivar maxDelay: Maximum number of seconds between connection attempts.
  269. @ivar initialDelay: Delay for the first reconnection attempt.
  270. @ivar factor: A multiplicitive factor by which the delay grows
  271. @ivar jitter: Percentage of randomness to introduce into the delay length
  272. to prevent stampeding.
  273. @ivar clock: The clock used to schedule reconnection. It's mainly useful to
  274. be parametrized in tests. If the factory is serialized, this attribute
  275. will not be serialized, and the default value (the reactor) will be
  276. restored when deserialized.
  277. @type clock: L{IReactorTime}
  278. @ivar maxRetries: Maximum number of consecutive unsuccessful connection
  279. attempts, after which no further connection attempts will be made. If
  280. this is not explicitly set, no maximum is applied.
  281. """
  282. maxDelay = 3600
  283. initialDelay = 1.0
  284. # Note: These highly sensitive factors have been precisely measured by
  285. # the National Institute of Science and Technology. Take extreme care
  286. # in altering them, or you may damage your Internet!
  287. # (Seriously: <http://physics.nist.gov/cuu/Constants/index.html>)
  288. factor = 2.7182818284590451 # (math.e)
  289. # Phi = 1.6180339887498948 # (Phi is acceptable for use as a
  290. # factor if e is too large for your application.)
  291. # This is the value of the molar Planck constant times c, joule
  292. # meter/mole. The value is attributable to
  293. # https://physics.nist.gov/cgi-bin/cuu/Value?nahc|search_for=molar+planck+constant+times+c
  294. jitter = 0.119626565582
  295. delay = initialDelay
  296. retries = 0
  297. maxRetries = None
  298. _callID = None
  299. connector = None
  300. clock = None
  301. continueTrying = 1
  302. def clientConnectionFailed(self, connector, reason):
  303. if self.continueTrying:
  304. self.connector = connector
  305. self.retry()
  306. def clientConnectionLost(self, connector, unused_reason):
  307. if self.continueTrying:
  308. self.connector = connector
  309. self.retry()
  310. def retry(self, connector=None):
  311. """
  312. Have this connector connect again, after a suitable delay.
  313. """
  314. if not self.continueTrying:
  315. if self.noisy:
  316. log.msg(f"Abandoning {connector} on explicit request")
  317. return
  318. if connector is None:
  319. if self.connector is None:
  320. raise ValueError("no connector to retry")
  321. else:
  322. connector = self.connector
  323. self.retries += 1
  324. if self.maxRetries is not None and (self.retries > self.maxRetries):
  325. if self.noisy:
  326. log.msg("Abandoning %s after %d retries." % (connector, self.retries))
  327. return
  328. self.delay = min(self.delay * self.factor, self.maxDelay)
  329. if self.jitter:
  330. self.delay = random.normalvariate(self.delay, self.delay * self.jitter)
  331. if self.noisy:
  332. log.msg(
  333. "%s will retry in %d seconds"
  334. % (
  335. connector,
  336. self.delay,
  337. )
  338. )
  339. def reconnector():
  340. self._callID = None
  341. connector.connect()
  342. if self.clock is None:
  343. from twisted.internet import reactor
  344. self.clock = reactor
  345. self._callID = self.clock.callLater(self.delay, reconnector)
  346. def stopTrying(self):
  347. """
  348. Put a stop to any attempt to reconnect in progress.
  349. """
  350. # ??? Is this function really stopFactory?
  351. if self._callID:
  352. self._callID.cancel()
  353. self._callID = None
  354. self.continueTrying = 0
  355. if self.connector:
  356. try:
  357. self.connector.stopConnecting()
  358. except error.NotConnectingError:
  359. pass
  360. def resetDelay(self):
  361. """
  362. Call this method after a successful connection: it resets the delay and
  363. the retry counter.
  364. """
  365. self.delay = self.initialDelay
  366. self.retries = 0
  367. self._callID = None
  368. self.continueTrying = 1
  369. def __getstate__(self):
  370. """
  371. Remove all of the state which is mutated by connection attempts and
  372. failures, returning just the state which describes how reconnections
  373. should be attempted. This will make the unserialized instance
  374. behave just as this one did when it was first instantiated.
  375. """
  376. state = self.__dict__.copy()
  377. for key in [
  378. "connector",
  379. "retries",
  380. "delay",
  381. "continueTrying",
  382. "_callID",
  383. "clock",
  384. ]:
  385. if key in state:
  386. del state[key]
  387. return state
  388. class ServerFactory(Factory):
  389. """
  390. Subclass this to indicate that your protocol.Factory is only usable for servers.
  391. """
  392. class BaseProtocol:
  393. """
  394. This is the abstract superclass of all protocols.
  395. Some methods have helpful default implementations here so that they can
  396. easily be shared, but otherwise the direct subclasses of this class are more
  397. interesting, L{Protocol} and L{ProcessProtocol}.
  398. """
  399. connected = 0
  400. transport: Optional[ITransport] = None
  401. def makeConnection(self, transport):
  402. """
  403. Make a connection to a transport and a server.
  404. This sets the 'transport' attribute of this Protocol, and calls the
  405. connectionMade() callback.
  406. """
  407. self.connected = 1
  408. self.transport = transport
  409. self.connectionMade()
  410. def connectionMade(self):
  411. """
  412. Called when a connection is made.
  413. This may be considered the initializer of the protocol, because
  414. it is called when the connection is completed. For clients,
  415. this is called once the connection to the server has been
  416. established; for servers, this is called after an accept() call
  417. stops blocking and a socket has been received. If you need to
  418. send any greeting or initial message, do it here.
  419. """
  420. connectionDone = failure.Failure(error.ConnectionDone())
  421. connectionDone.cleanFailure()
  422. @implementer(interfaces.IProtocol, interfaces.ILoggingContext)
  423. class Protocol(BaseProtocol):
  424. """
  425. This is the base class for streaming connection-oriented protocols.
  426. If you are going to write a new connection-oriented protocol for Twisted,
  427. start here. Any protocol implementation, either client or server, should
  428. be a subclass of this class.
  429. The API is quite simple. Implement L{dataReceived} to handle both
  430. event-based and synchronous input; output can be sent through the
  431. 'transport' attribute, which is to be an instance that implements
  432. L{twisted.internet.interfaces.ITransport}. Override C{connectionLost} to be
  433. notified when the connection ends.
  434. Some subclasses exist already to help you write common types of protocols:
  435. see the L{twisted.protocols.basic} module for a few of them.
  436. """
  437. factory: Optional[Factory] = None
  438. def logPrefix(self):
  439. """
  440. Return a prefix matching the class name, to identify log messages
  441. related to this protocol instance.
  442. """
  443. return self.__class__.__name__
  444. def dataReceived(self, data: bytes) -> None:
  445. """
  446. Called whenever data is received.
  447. Use this method to translate to a higher-level message. Usually, some
  448. callback will be made upon the receipt of each complete protocol
  449. message.
  450. @param data: a string of indeterminate length. Please keep in mind
  451. that you will probably need to buffer some data, as partial
  452. (or multiple) protocol messages may be received! I recommend
  453. that unit tests for protocols call through to this method with
  454. differing chunk sizes, down to one byte at a time.
  455. """
  456. def connectionLost(self, reason: failure.Failure = connectionDone) -> None:
  457. """
  458. Called when the connection is shut down.
  459. Clear any circular references here, and any external references
  460. to this Protocol. The connection has been closed.
  461. @type reason: L{twisted.python.failure.Failure}
  462. """
  463. @implementer(interfaces.IConsumer)
  464. class ProtocolToConsumerAdapter(components.Adapter):
  465. def write(self, data: bytes) -> None:
  466. self.original.dataReceived(data)
  467. def registerProducer(self, producer, streaming):
  468. pass
  469. def unregisterProducer(self):
  470. pass
  471. components.registerAdapter(
  472. ProtocolToConsumerAdapter, interfaces.IProtocol, interfaces.IConsumer
  473. )
  474. @implementer(interfaces.IProtocol)
  475. class ConsumerToProtocolAdapter(components.Adapter):
  476. def dataReceived(self, data: bytes) -> None:
  477. self.original.write(data)
  478. def connectionLost(self, reason: failure.Failure) -> None:
  479. pass
  480. def makeConnection(self, transport):
  481. pass
  482. def connectionMade(self):
  483. pass
  484. components.registerAdapter(
  485. ConsumerToProtocolAdapter, interfaces.IConsumer, interfaces.IProtocol
  486. )
  487. @implementer(interfaces.IProcessProtocol)
  488. class ProcessProtocol(BaseProtocol):
  489. """
  490. Base process protocol implementation which does simple dispatching for
  491. stdin, stdout, and stderr file descriptors.
  492. """
  493. transport: Optional[interfaces.IProcessTransport] = None
  494. def childDataReceived(self, childFD: int, data: bytes) -> None:
  495. if childFD == 1:
  496. self.outReceived(data)
  497. elif childFD == 2:
  498. self.errReceived(data)
  499. def outReceived(self, data: bytes) -> None:
  500. """
  501. Some data was received from stdout.
  502. """
  503. def errReceived(self, data: bytes) -> None:
  504. """
  505. Some data was received from stderr.
  506. """
  507. def childConnectionLost(self, childFD: int) -> None:
  508. if childFD == 0:
  509. self.inConnectionLost()
  510. elif childFD == 1:
  511. self.outConnectionLost()
  512. elif childFD == 2:
  513. self.errConnectionLost()
  514. def inConnectionLost(self):
  515. """
  516. This will be called when stdin is closed.
  517. """
  518. def outConnectionLost(self):
  519. """
  520. This will be called when stdout is closed.
  521. """
  522. def errConnectionLost(self):
  523. """
  524. This will be called when stderr is closed.
  525. """
  526. def processExited(self, reason: failure.Failure) -> None:
  527. """
  528. This will be called when the subprocess exits.
  529. @type reason: L{twisted.python.failure.Failure}
  530. """
  531. def processEnded(self, reason: failure.Failure) -> None:
  532. """
  533. Called when the child process exits and all file descriptors
  534. associated with it have been closed.
  535. @type reason: L{twisted.python.failure.Failure}
  536. """
  537. class AbstractDatagramProtocol:
  538. """
  539. Abstract protocol for datagram-oriented transports, e.g. IP, ICMP, ARP,
  540. UDP.
  541. """
  542. transport: IUDPTransport | IMulticastTransport | None = None
  543. numPorts = 0
  544. noisy = True
  545. def __getstate__(self):
  546. d = self.__dict__.copy()
  547. d["transport"] = None
  548. return d
  549. def doStart(self):
  550. """
  551. Make sure startProtocol is called.
  552. This will be called by makeConnection(), users should not call it.
  553. """
  554. if not self.numPorts:
  555. if self.noisy:
  556. log.msg("Starting protocol %s" % self)
  557. self.startProtocol()
  558. self.numPorts = self.numPorts + 1
  559. def doStop(self):
  560. """
  561. Make sure stopProtocol is called.
  562. This will be called by the port, users should not call it.
  563. """
  564. assert self.numPorts > 0
  565. self.numPorts = self.numPorts - 1
  566. self.transport = None
  567. if not self.numPorts:
  568. if self.noisy:
  569. log.msg("Stopping protocol %s" % self)
  570. self.stopProtocol()
  571. def startProtocol(self):
  572. """
  573. Called when a transport is connected to this protocol.
  574. Will only be called once, even if multiple ports are connected.
  575. """
  576. def stopProtocol(self):
  577. """
  578. Called when the transport is disconnected.
  579. Will only be called once, after all ports are disconnected.
  580. """
  581. def makeConnection(self, transport: IUDPTransport) -> None:
  582. """
  583. Make a connection to a transport and a server.
  584. This sets the 'transport' attribute of this DatagramProtocol, and calls the
  585. doStart() callback.
  586. """
  587. assert self.transport == None
  588. self.transport = transport
  589. self.doStart()
  590. def datagramReceived(self, datagram: bytes, addr: Any) -> None:
  591. """
  592. Called when a datagram is received.
  593. @param datagram: the bytes received from the transport.
  594. @param addr: tuple of source of datagram.
  595. """
  596. @implementer(interfaces.ILoggingContext)
  597. class DatagramProtocol(AbstractDatagramProtocol):
  598. """
  599. Protocol for datagram-oriented transport, e.g. UDP.
  600. @type transport: L{None} or
  601. L{IUDPTransport<twisted.internet.interfaces.IUDPTransport>} provider
  602. @ivar transport: The transport with which this protocol is associated,
  603. if it is associated with one.
  604. """
  605. def logPrefix(self):
  606. """
  607. Return a prefix matching the class name, to identify log messages
  608. related to this protocol instance.
  609. """
  610. return self.__class__.__name__
  611. def connectionRefused(self):
  612. """
  613. Called due to error from write in connected mode.
  614. Note this is a result of ICMP message generated by *previous*
  615. write.
  616. """
  617. class ConnectedDatagramProtocol(DatagramProtocol):
  618. """
  619. Protocol for connected datagram-oriented transport.
  620. No longer necessary for UDP.
  621. """
  622. def datagramReceived(self, datagram):
  623. """
  624. Called when a datagram is received.
  625. @param datagram: the string received from the transport.
  626. """
  627. def connectionFailed(self, failure: failure.Failure) -> None:
  628. """
  629. Called if connecting failed.
  630. Usually this will be due to a DNS lookup failure.
  631. """
  632. @implementer(interfaces.ITransport)
  633. class FileWrapper:
  634. """
  635. A wrapper around a file-like object to make it behave as a Transport.
  636. This doesn't actually stream the file to the attached protocol,
  637. and is thus useful mainly as a utility for debugging protocols.
  638. """
  639. closed = 0
  640. disconnecting = 0
  641. producer = None
  642. streamingProducer = 0
  643. def __init__(self, file):
  644. self.file = file
  645. def write(self, data: bytes) -> None:
  646. try:
  647. self.file.write(data)
  648. except BaseException:
  649. self.handleException()
  650. def _checkProducer(self):
  651. # Cheating; this is called at "idle" times to allow producers to be
  652. # found and dealt with
  653. if self.producer:
  654. self.producer.resumeProducing()
  655. def registerProducer(self, producer, streaming):
  656. """
  657. From abstract.FileDescriptor
  658. """
  659. self.producer = producer
  660. self.streamingProducer = streaming
  661. if not streaming:
  662. producer.resumeProducing()
  663. def unregisterProducer(self):
  664. self.producer = None
  665. def stopConsuming(self):
  666. self.unregisterProducer()
  667. self.loseConnection()
  668. def writeSequence(self, iovec):
  669. self.write(b"".join(iovec))
  670. def loseConnection(self):
  671. self.closed = 1
  672. try:
  673. self.file.close()
  674. except OSError:
  675. self.handleException()
  676. def getPeer(self):
  677. # FIXME: https://twistedmatrix.com/trac/ticket/7820
  678. # According to ITransport, this should return an IAddress!
  679. return "file", "file"
  680. def getHost(self):
  681. # FIXME: https://twistedmatrix.com/trac/ticket/7820
  682. # According to ITransport, this should return an IAddress!
  683. return "file"
  684. def handleException(self):
  685. pass
  686. def resumeProducing(self):
  687. # Never sends data anyways
  688. pass
  689. def pauseProducing(self):
  690. # Never sends data anyways
  691. pass
  692. def stopProducing(self):
  693. self.loseConnection()
  694. __all__ = [
  695. "Factory",
  696. "ClientFactory",
  697. "ReconnectingClientFactory",
  698. "connectionDone",
  699. "Protocol",
  700. "ProcessProtocol",
  701. "FileWrapper",
  702. "ServerFactory",
  703. "AbstractDatagramProtocol",
  704. "DatagramProtocol",
  705. "ConnectedDatagramProtocol",
  706. "ClientCreator",
  707. ]