Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_tcp.py 64KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for implementations of L{IReactorTCP}.
  5. """
  6. import errno
  7. import random
  8. import socket
  9. from functools import wraps
  10. from typing import Callable, Optional
  11. from unittest import skipIf
  12. from zope.interface import implementer
  13. import hamcrest
  14. from twisted.internet import defer, error, interfaces, protocol, reactor
  15. from twisted.internet.address import IPv4Address
  16. from twisted.internet.interfaces import IHalfCloseableProtocol, IPullProducer
  17. from twisted.internet.protocol import Protocol
  18. from twisted.protocols import policies
  19. from twisted.python.log import err, msg
  20. from twisted.python.runtime import platform
  21. from twisted.test.proto_helpers import AccumulatingProtocol
  22. from twisted.trial.unittest import SkipTest, TestCase
  23. def loopUntil(predicate, interval=0):
  24. """
  25. Poor excuse for an event notification helper. This polls a condition and
  26. calls back a Deferred when it is seen to be true.
  27. Do not use this function.
  28. """
  29. from twisted.internet import task
  30. d = defer.Deferred()
  31. def check():
  32. res = predicate()
  33. if res:
  34. d.callback(res)
  35. call = task.LoopingCall(check)
  36. def stop(result):
  37. call.stop()
  38. return result
  39. d.addCallback(stop)
  40. d2 = call.start(interval)
  41. d2.addErrback(d.errback)
  42. return d
  43. class ClosingProtocol(protocol.Protocol):
  44. def connectionMade(self):
  45. msg("ClosingProtocol.connectionMade")
  46. self.transport.loseConnection()
  47. def connectionLost(self, reason):
  48. msg("ClosingProtocol.connectionLost")
  49. reason.trap(error.ConnectionDone)
  50. class ClosingFactory(protocol.ServerFactory):
  51. """
  52. Factory that closes port immediately.
  53. """
  54. _cleanerUpper = None
  55. def buildProtocol(self, conn):
  56. self._cleanerUpper = self.port.stopListening()
  57. return ClosingProtocol()
  58. def cleanUp(self):
  59. """
  60. Clean-up for tests to wait for the port to stop listening.
  61. """
  62. if self._cleanerUpper is None:
  63. return self.port.stopListening()
  64. return self._cleanerUpper
  65. class MyProtocolFactoryMixin:
  66. """
  67. Mixin for factories which create L{AccumulatingProtocol} instances.
  68. @type protocolFactory: no-argument callable
  69. @ivar protocolFactory: Factory for protocols - takes the place of the
  70. typical C{protocol} attribute of factories (but that name is used by
  71. this class for something else).
  72. @type protocolConnectionMade: L{None} or L{defer.Deferred}
  73. @ivar protocolConnectionMade: When an instance of L{AccumulatingProtocol}
  74. is connected, if this is not L{None}, the L{Deferred} will be called
  75. back with the protocol instance and the attribute set to L{None}.
  76. @type protocolConnectionLost: L{None} or L{defer.Deferred}
  77. @ivar protocolConnectionLost: When an instance of L{AccumulatingProtocol}
  78. is created, this will be set as its C{closedDeferred} attribute and
  79. then this attribute will be set to L{None} so the L{defer.Deferred} is
  80. not used by more than one protocol.
  81. @ivar protocol: The most recently created L{AccumulatingProtocol} instance
  82. which was returned from C{buildProtocol}.
  83. @type called: C{int}
  84. @ivar called: A counter which is incremented each time C{buildProtocol}
  85. is called.
  86. @ivar peerAddresses: A C{list} of the addresses passed to C{buildProtocol}.
  87. """
  88. protocolFactory = AccumulatingProtocol
  89. protocolConnectionMade = None
  90. protocolConnectionLost = None
  91. protocol: Optional[Callable[[], Protocol]] = None
  92. called = 0
  93. def __init__(self):
  94. self.peerAddresses = []
  95. def buildProtocol(self, addr):
  96. """
  97. Create a L{AccumulatingProtocol} and set it up to be able to perform
  98. callbacks.
  99. """
  100. self.peerAddresses.append(addr)
  101. self.called += 1
  102. p = self.protocolFactory()
  103. p.factory = self
  104. p.closedDeferred = self.protocolConnectionLost
  105. self.protocolConnectionLost = None
  106. self.protocol = p
  107. return p
  108. class MyServerFactory(MyProtocolFactoryMixin, protocol.ServerFactory):
  109. """
  110. Server factory which creates L{AccumulatingProtocol} instances.
  111. """
  112. class MyClientFactory(MyProtocolFactoryMixin, protocol.ClientFactory):
  113. """
  114. Client factory which creates L{AccumulatingProtocol} instances.
  115. """
  116. failed = 0
  117. stopped = 0
  118. def __init__(self):
  119. MyProtocolFactoryMixin.__init__(self)
  120. self.deferred = defer.Deferred()
  121. self.failDeferred = defer.Deferred()
  122. def clientConnectionFailed(self, connector, reason):
  123. self.failed = 1
  124. self.reason = reason
  125. self.failDeferred.callback(None)
  126. def clientConnectionLost(self, connector, reason):
  127. self.lostReason = reason
  128. self.deferred.callback(None)
  129. def stopFactory(self):
  130. self.stopped = 1
  131. class ListeningTests(TestCase):
  132. def test_listen(self):
  133. """
  134. L{IReactorTCP.listenTCP} returns an object which provides
  135. L{IListeningPort}.
  136. """
  137. f = MyServerFactory()
  138. p1 = reactor.listenTCP(0, f, interface="127.0.0.1")
  139. self.addCleanup(p1.stopListening)
  140. self.assertTrue(interfaces.IListeningPort.providedBy(p1))
  141. def testStopListening(self):
  142. """
  143. The L{IListeningPort} returned by L{IReactorTCP.listenTCP} can be
  144. stopped with its C{stopListening} method. After the L{Deferred} it
  145. (optionally) returns has been called back, the port number can be bound
  146. to a new server.
  147. """
  148. f = MyServerFactory()
  149. port = reactor.listenTCP(0, f, interface="127.0.0.1")
  150. n = port.getHost().port
  151. def cbStopListening(ignored):
  152. # Make sure we can rebind the port right away
  153. port = reactor.listenTCP(n, f, interface="127.0.0.1")
  154. return port.stopListening()
  155. d = defer.maybeDeferred(port.stopListening)
  156. d.addCallback(cbStopListening)
  157. return d
  158. def testNumberedInterface(self):
  159. f = MyServerFactory()
  160. # listen only on the loopback interface
  161. p1 = reactor.listenTCP(0, f, interface="127.0.0.1")
  162. return p1.stopListening()
  163. def testPortRepr(self):
  164. f = MyServerFactory()
  165. p = reactor.listenTCP(0, f)
  166. portNo = str(p.getHost().port)
  167. self.assertFalse(repr(p).find(portNo) == -1)
  168. def stoppedListening(ign):
  169. self.assertFalse(repr(p).find(portNo) != -1)
  170. d = defer.maybeDeferred(p.stopListening)
  171. return d.addCallback(stoppedListening)
  172. def test_serverRepr(self):
  173. """
  174. Check that the repr string of the server transport get the good port
  175. number if the server listens on 0.
  176. """
  177. server = MyServerFactory()
  178. serverConnMade = server.protocolConnectionMade = defer.Deferred()
  179. port = reactor.listenTCP(0, server)
  180. self.addCleanup(port.stopListening)
  181. client = MyClientFactory()
  182. clientConnMade = client.protocolConnectionMade = defer.Deferred()
  183. connector = reactor.connectTCP("127.0.0.1", port.getHost().port, client)
  184. self.addCleanup(connector.disconnect)
  185. def check(result):
  186. serverProto, clientProto = result
  187. portNumber = port.getHost().port
  188. self.assertEqual(
  189. repr(serverProto.transport),
  190. f"<AccumulatingProtocol #0 on {portNumber}>",
  191. )
  192. serverProto.transport.loseConnection()
  193. clientProto.transport.loseConnection()
  194. return defer.gatherResults([serverConnMade, clientConnMade]).addCallback(check)
  195. def test_restartListening(self):
  196. """
  197. Stop and then try to restart a L{tcp.Port}: after a restart, the
  198. server should be able to handle client connections.
  199. """
  200. serverFactory = MyServerFactory()
  201. port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
  202. self.addCleanup(port.stopListening)
  203. def cbStopListening(ignored):
  204. port.startListening()
  205. client = MyClientFactory()
  206. serverFactory.protocolConnectionMade = defer.Deferred()
  207. client.protocolConnectionMade = defer.Deferred()
  208. connector = reactor.connectTCP("127.0.0.1", port.getHost().port, client)
  209. self.addCleanup(connector.disconnect)
  210. return defer.gatherResults(
  211. [serverFactory.protocolConnectionMade, client.protocolConnectionMade]
  212. ).addCallback(close)
  213. def close(result):
  214. serverProto, clientProto = result
  215. clientProto.transport.loseConnection()
  216. serverProto.transport.loseConnection()
  217. d = defer.maybeDeferred(port.stopListening)
  218. d.addCallback(cbStopListening)
  219. return d
  220. def test_exceptInStop(self):
  221. """
  222. If the server factory raises an exception in C{stopFactory}, the
  223. deferred returned by L{tcp.Port.stopListening} should fail with the
  224. corresponding error.
  225. """
  226. serverFactory = MyServerFactory()
  227. def raiseException():
  228. raise RuntimeError("An error")
  229. serverFactory.stopFactory = raiseException
  230. port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
  231. return self.assertFailure(port.stopListening(), RuntimeError)
  232. def test_restartAfterExcept(self):
  233. """
  234. Even if the server factory raise an exception in C{stopFactory}, the
  235. corresponding C{tcp.Port} instance should be in a sane state and can
  236. be restarted.
  237. """
  238. serverFactory = MyServerFactory()
  239. def raiseException():
  240. raise RuntimeError("An error")
  241. serverFactory.stopFactory = raiseException
  242. port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
  243. self.addCleanup(port.stopListening)
  244. def cbStopListening(ignored):
  245. del serverFactory.stopFactory
  246. port.startListening()
  247. client = MyClientFactory()
  248. serverFactory.protocolConnectionMade = defer.Deferred()
  249. client.protocolConnectionMade = defer.Deferred()
  250. connector = reactor.connectTCP("127.0.0.1", port.getHost().port, client)
  251. self.addCleanup(connector.disconnect)
  252. return defer.gatherResults(
  253. [serverFactory.protocolConnectionMade, client.protocolConnectionMade]
  254. ).addCallback(close)
  255. def close(result):
  256. serverProto, clientProto = result
  257. clientProto.transport.loseConnection()
  258. serverProto.transport.loseConnection()
  259. return self.assertFailure(port.stopListening(), RuntimeError).addCallback(
  260. cbStopListening
  261. )
  262. def test_directConnectionLostCall(self):
  263. """
  264. If C{connectionLost} is called directly on a port object, it succeeds
  265. (and doesn't expect the presence of a C{deferred} attribute).
  266. C{connectionLost} is called by L{reactor.disconnectAll} at shutdown.
  267. """
  268. serverFactory = MyServerFactory()
  269. port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
  270. portNumber = port.getHost().port
  271. port.connectionLost(None)
  272. client = MyClientFactory()
  273. serverFactory.protocolConnectionMade = defer.Deferred()
  274. client.protocolConnectionMade = defer.Deferred()
  275. reactor.connectTCP("127.0.0.1", portNumber, client)
  276. def check(ign):
  277. client.reason.trap(error.ConnectionRefusedError)
  278. return client.failDeferred.addCallback(check)
  279. def test_exceptInConnectionLostCall(self):
  280. """
  281. If C{connectionLost} is called directory on a port object and that the
  282. server factory raises an exception in C{stopFactory}, the exception is
  283. passed through to the caller.
  284. C{connectionLost} is called by L{reactor.disconnectAll} at shutdown.
  285. """
  286. serverFactory = MyServerFactory()
  287. def raiseException():
  288. raise RuntimeError("An error")
  289. serverFactory.stopFactory = raiseException
  290. port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
  291. self.assertRaises(RuntimeError, port.connectionLost, None)
  292. class LoopbackTests(TestCase):
  293. """
  294. Test loopback connections.
  295. """
  296. def test_closePortInProtocolFactory(self):
  297. """
  298. A port created with L{IReactorTCP.listenTCP} can be connected to with
  299. L{IReactorTCP.connectTCP}.
  300. """
  301. f = ClosingFactory()
  302. port = reactor.listenTCP(0, f, interface="127.0.0.1")
  303. f.port = port
  304. self.addCleanup(f.cleanUp)
  305. portNumber = port.getHost().port
  306. clientF = MyClientFactory()
  307. reactor.connectTCP("127.0.0.1", portNumber, clientF)
  308. def check(x):
  309. self.assertTrue(clientF.protocol.made)
  310. self.assertTrue(port.disconnected)
  311. clientF.lostReason.trap(error.ConnectionDone)
  312. return clientF.deferred.addCallback(check)
  313. def _trapCnxDone(self, obj):
  314. getattr(obj, "trap", lambda x: None)(error.ConnectionDone)
  315. def _connectedClientAndServerTest(self, callback):
  316. """
  317. Invoke the given callback with a client protocol and a server protocol
  318. which have been connected to each other.
  319. """
  320. serverFactory = MyServerFactory()
  321. serverConnMade = defer.Deferred()
  322. serverFactory.protocolConnectionMade = serverConnMade
  323. port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
  324. self.addCleanup(port.stopListening)
  325. portNumber = port.getHost().port
  326. clientF = MyClientFactory()
  327. clientConnMade = defer.Deferred()
  328. clientF.protocolConnectionMade = clientConnMade
  329. reactor.connectTCP("127.0.0.1", portNumber, clientF)
  330. connsMade = defer.gatherResults([serverConnMade, clientConnMade])
  331. def connected(result):
  332. serverProtocol, clientProtocol = result
  333. callback(serverProtocol, clientProtocol)
  334. serverProtocol.transport.loseConnection()
  335. clientProtocol.transport.loseConnection()
  336. connsMade.addCallback(connected)
  337. return connsMade
  338. def test_tcpNoDelay(self):
  339. """
  340. The transport of a protocol connected with L{IReactorTCP.connectTCP} or
  341. L{IReactor.TCP.listenTCP} can have its I{TCP_NODELAY} state inspected
  342. and manipulated with L{ITCPTransport.getTcpNoDelay} and
  343. L{ITCPTransport.setTcpNoDelay}.
  344. """
  345. def check(serverProtocol, clientProtocol):
  346. for p in [serverProtocol, clientProtocol]:
  347. transport = p.transport
  348. self.assertEqual(transport.getTcpNoDelay(), 0)
  349. transport.setTcpNoDelay(1)
  350. self.assertEqual(transport.getTcpNoDelay(), 1)
  351. transport.setTcpNoDelay(0)
  352. self.assertEqual(transport.getTcpNoDelay(), 0)
  353. return self._connectedClientAndServerTest(check)
  354. def test_tcpKeepAlive(self):
  355. """
  356. The transport of a protocol connected with L{IReactorTCP.connectTCP} or
  357. L{IReactor.TCP.listenTCP} can have its I{SO_KEEPALIVE} state inspected
  358. and manipulated with L{ITCPTransport.getTcpKeepAlive} and
  359. L{ITCPTransport.setTcpKeepAlive}.
  360. """
  361. def check(serverProtocol, clientProtocol):
  362. for p in [serverProtocol, clientProtocol]:
  363. transport = p.transport
  364. self.assertEqual(transport.getTcpKeepAlive(), 0)
  365. transport.setTcpKeepAlive(1)
  366. self.assertEqual(transport.getTcpKeepAlive(), 1)
  367. transport.setTcpKeepAlive(0)
  368. self.assertEqual(transport.getTcpKeepAlive(), 0)
  369. return self._connectedClientAndServerTest(check)
  370. def testFailing(self):
  371. clientF = MyClientFactory()
  372. # XXX we assume no one is listening on TCP port 69
  373. reactor.connectTCP("127.0.0.1", 69, clientF, timeout=5)
  374. def check(ignored):
  375. clientF.reason.trap(error.ConnectionRefusedError)
  376. return clientF.failDeferred.addCallback(check)
  377. def test_connectionRefusedErrorNumber(self):
  378. """
  379. Assert that the error number of the ConnectionRefusedError is
  380. ECONNREFUSED, and not some other socket related error.
  381. """
  382. # Bind a number of ports in the operating system. We will attempt
  383. # to connect to these in turn immediately after closing them, in the
  384. # hopes that no one else has bound them in the mean time. Any
  385. # connection which succeeds is ignored and causes us to move on to
  386. # the next port. As soon as a connection attempt fails, we move on
  387. # to making an assertion about how it failed. If they all succeed,
  388. # the test will fail.
  389. # It would be nice to have a simpler, reliable way to cause a
  390. # connection failure from the platform.
  391. #
  392. # On Linux (2.6.15), connecting to port 0 always fails. FreeBSD
  393. # (5.4) rejects the connection attempt with EADDRNOTAVAIL.
  394. #
  395. # On FreeBSD (5.4), listening on a port and then repeatedly
  396. # connecting to it without ever accepting any connections eventually
  397. # leads to an ECONNREFUSED. On Linux (2.6.15), a seemingly
  398. # unbounded number of connections succeed.
  399. serverSockets = []
  400. for i in range(10):
  401. serverSocket = socket.socket()
  402. serverSocket.bind(("127.0.0.1", 0))
  403. serverSocket.listen(1)
  404. serverSockets.append(serverSocket)
  405. random.shuffle(serverSockets)
  406. clientCreator = protocol.ClientCreator(reactor, protocol.Protocol)
  407. def tryConnectFailure():
  408. def connected(proto):
  409. """
  410. Darn. Kill it and try again, if there are any tries left.
  411. """
  412. proto.transport.loseConnection()
  413. if serverSockets:
  414. return tryConnectFailure()
  415. self.fail(
  416. "Could not fail to connect - could not test errno for that case."
  417. )
  418. serverSocket = serverSockets.pop()
  419. serverHost, serverPort = serverSocket.getsockname()
  420. serverSocket.close()
  421. connectDeferred = clientCreator.connectTCP(serverHost, serverPort)
  422. connectDeferred.addCallback(connected)
  423. return connectDeferred
  424. refusedDeferred = tryConnectFailure()
  425. self.assertFailure(refusedDeferred, error.ConnectionRefusedError)
  426. def connRefused(exc):
  427. self.assertEqual(exc.osError, errno.ECONNREFUSED)
  428. refusedDeferred.addCallback(connRefused)
  429. def cleanup(passthrough):
  430. while serverSockets:
  431. serverSockets.pop().close()
  432. return passthrough
  433. refusedDeferred.addBoth(cleanup)
  434. return refusedDeferred
  435. def test_connectByServiceFail(self):
  436. """
  437. Connecting to a named service which does not exist raises
  438. L{error.ServiceNameUnknownError}.
  439. """
  440. self.assertRaises(
  441. error.ServiceNameUnknownError,
  442. reactor.connectTCP,
  443. "127.0.0.1",
  444. "thisbetternotexist",
  445. MyClientFactory(),
  446. )
  447. def test_connectByService(self):
  448. """
  449. L{IReactorTCP.connectTCP} accepts the name of a service instead of a
  450. port number and connects to the port number associated with that
  451. service, as defined by L{socket.getservbyname}.
  452. """
  453. serverFactory = MyServerFactory()
  454. serverConnMade = defer.Deferred()
  455. serverFactory.protocolConnectionMade = serverConnMade
  456. port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
  457. self.addCleanup(port.stopListening)
  458. portNumber = port.getHost().port
  459. clientFactory = MyClientFactory()
  460. clientConnMade = defer.Deferred()
  461. clientFactory.protocolConnectionMade = clientConnMade
  462. def fakeGetServicePortByName(serviceName, protocolName):
  463. if serviceName == "http" and protocolName == "tcp":
  464. return portNumber
  465. return 10
  466. self.patch(socket, "getservbyname", fakeGetServicePortByName)
  467. reactor.connectTCP("127.0.0.1", "http", clientFactory)
  468. connMade = defer.gatherResults([serverConnMade, clientConnMade])
  469. def connected(result):
  470. serverProtocol, clientProtocol = result
  471. self.assertTrue(
  472. serverFactory.called,
  473. "Server factory was not called upon to build a protocol.",
  474. )
  475. serverProtocol.transport.loseConnection()
  476. clientProtocol.transport.loseConnection()
  477. connMade.addCallback(connected)
  478. return connMade
  479. class StartStopFactory(protocol.Factory):
  480. started = 0
  481. stopped = 0
  482. def startFactory(self):
  483. if self.started or self.stopped:
  484. raise RuntimeError
  485. self.started = 1
  486. def stopFactory(self):
  487. if not self.started or self.stopped:
  488. raise RuntimeError
  489. self.stopped = 1
  490. class ClientStartStopFactory(MyClientFactory):
  491. started = 0
  492. stopped = 0
  493. def __init__(self, *a, **kw):
  494. MyClientFactory.__init__(self, *a, **kw)
  495. self.whenStopped = defer.Deferred()
  496. def startFactory(self):
  497. if self.started or self.stopped:
  498. raise RuntimeError
  499. self.started = 1
  500. def stopFactory(self):
  501. if not self.started or self.stopped:
  502. raise RuntimeError
  503. self.stopped = 1
  504. self.whenStopped.callback(True)
  505. class FactoryTests(TestCase):
  506. """Tests for factories."""
  507. def test_serverStartStop(self):
  508. """
  509. The factory passed to L{IReactorTCP.listenTCP} should be started only
  510. when it transitions from being used on no ports to being used on one
  511. port and should be stopped only when it transitions from being used on
  512. one port to being used on no ports.
  513. """
  514. # Note - this test doesn't need to use listenTCP. It is exercising
  515. # logic implemented in Factory.doStart and Factory.doStop, so it could
  516. # just call that directly. Some other test can make sure that
  517. # listenTCP and stopListening correctly call doStart and
  518. # doStop. -exarkun
  519. f = StartStopFactory()
  520. # listen on port
  521. p1 = reactor.listenTCP(0, f, interface="127.0.0.1")
  522. self.addCleanup(p1.stopListening)
  523. self.assertEqual((f.started, f.stopped), (1, 0))
  524. # listen on two more ports
  525. p2 = reactor.listenTCP(0, f, interface="127.0.0.1")
  526. p3 = reactor.listenTCP(0, f, interface="127.0.0.1")
  527. self.assertEqual((f.started, f.stopped), (1, 0))
  528. # close two ports
  529. d1 = defer.maybeDeferred(p1.stopListening)
  530. d2 = defer.maybeDeferred(p2.stopListening)
  531. closedDeferred = defer.gatherResults([d1, d2])
  532. def cbClosed(ignored):
  533. self.assertEqual((f.started, f.stopped), (1, 0))
  534. # Close the last port
  535. return p3.stopListening()
  536. closedDeferred.addCallback(cbClosed)
  537. def cbClosedAll(ignored):
  538. self.assertEqual((f.started, f.stopped), (1, 1))
  539. closedDeferred.addCallback(cbClosedAll)
  540. return closedDeferred
  541. def test_clientStartStop(self):
  542. """
  543. The factory passed to L{IReactorTCP.connectTCP} should be started when
  544. the connection attempt starts and stopped when it is over.
  545. """
  546. f = ClosingFactory()
  547. p = reactor.listenTCP(0, f, interface="127.0.0.1")
  548. f.port = p
  549. self.addCleanup(f.cleanUp)
  550. portNumber = p.getHost().port
  551. factory = ClientStartStopFactory()
  552. reactor.connectTCP("127.0.0.1", portNumber, factory)
  553. self.assertTrue(factory.started)
  554. return loopUntil(lambda: factory.stopped)
  555. class CannotBindTests(TestCase):
  556. """
  557. Tests for correct behavior when a reactor cannot bind to the required TCP
  558. port.
  559. """
  560. def test_cannotBind(self):
  561. """
  562. L{IReactorTCP.listenTCP} raises L{error.CannotListenError} if the
  563. address to listen on is already in use.
  564. """
  565. f = MyServerFactory()
  566. p1 = reactor.listenTCP(0, f, interface="127.0.0.1")
  567. self.addCleanup(p1.stopListening)
  568. n = p1.getHost().port
  569. dest = p1.getHost()
  570. self.assertEqual(dest.type, "TCP")
  571. self.assertEqual(dest.host, "127.0.0.1")
  572. self.assertEqual(dest.port, n)
  573. # make sure new listen raises error
  574. self.assertRaises(
  575. error.CannotListenError, reactor.listenTCP, n, f, interface="127.0.0.1"
  576. )
  577. def _fireWhenDoneFunc(self, d, f):
  578. """Returns closure that when called calls f and then callbacks d."""
  579. @wraps(f)
  580. def newf(*args, **kw):
  581. rtn = f(*args, **kw)
  582. d.callback("")
  583. return rtn
  584. return newf
  585. def test_clientBind(self):
  586. """
  587. L{IReactorTCP.connectTCP} calls C{Factory.clientConnectionFailed} with
  588. L{error.ConnectBindError} if the bind address specified is already in
  589. use.
  590. """
  591. theDeferred = defer.Deferred()
  592. sf = MyServerFactory()
  593. sf.startFactory = self._fireWhenDoneFunc(theDeferred, sf.startFactory)
  594. p = reactor.listenTCP(0, sf, interface="127.0.0.1")
  595. self.addCleanup(p.stopListening)
  596. def _connect1(results):
  597. d = defer.Deferred()
  598. cf1 = MyClientFactory()
  599. cf1.buildProtocol = self._fireWhenDoneFunc(d, cf1.buildProtocol)
  600. reactor.connectTCP(
  601. "127.0.0.1", p.getHost().port, cf1, bindAddress=("127.0.0.1", 0)
  602. )
  603. d.addCallback(_conmade, cf1)
  604. return d
  605. def _conmade(results, cf1):
  606. d = defer.Deferred()
  607. cf1.protocol.connectionMade = self._fireWhenDoneFunc(
  608. d, cf1.protocol.connectionMade
  609. )
  610. d.addCallback(_check1connect2, cf1)
  611. return d
  612. def _check1connect2(results, cf1):
  613. self.assertEqual(cf1.protocol.made, 1)
  614. d1 = defer.Deferred()
  615. d2 = defer.Deferred()
  616. port = cf1.protocol.transport.getHost().port
  617. cf2 = MyClientFactory()
  618. cf2.clientConnectionFailed = self._fireWhenDoneFunc(
  619. d1, cf2.clientConnectionFailed
  620. )
  621. cf2.stopFactory = self._fireWhenDoneFunc(d2, cf2.stopFactory)
  622. reactor.connectTCP(
  623. "127.0.0.1", p.getHost().port, cf2, bindAddress=("127.0.0.1", port)
  624. )
  625. d1.addCallback(_check2failed, cf1, cf2)
  626. d2.addCallback(_check2stopped, cf1, cf2)
  627. dl = defer.DeferredList([d1, d2])
  628. dl.addCallback(_stop, cf1, cf2)
  629. return dl
  630. def _check2failed(results, cf1, cf2):
  631. self.assertEqual(cf2.failed, 1)
  632. cf2.reason.trap(error.ConnectBindError)
  633. self.assertTrue(cf2.reason.check(error.ConnectBindError))
  634. return results
  635. def _check2stopped(results, cf1, cf2):
  636. self.assertEqual(cf2.stopped, 1)
  637. return results
  638. def _stop(results, cf1, cf2):
  639. d = defer.Deferred()
  640. d.addCallback(_check1cleanup, cf1)
  641. cf1.stopFactory = self._fireWhenDoneFunc(d, cf1.stopFactory)
  642. cf1.protocol.transport.loseConnection()
  643. return d
  644. def _check1cleanup(results, cf1):
  645. self.assertEqual(cf1.stopped, 1)
  646. theDeferred.addCallback(_connect1)
  647. return theDeferred
  648. class MyOtherClientFactory(protocol.ClientFactory):
  649. def buildProtocol(self, address):
  650. self.address = address
  651. self.protocol = AccumulatingProtocol()
  652. return self.protocol
  653. class LocalRemoteAddressTests(TestCase):
  654. """
  655. Tests for correct getHost/getPeer values and that the correct address is
  656. passed to buildProtocol.
  657. """
  658. def test_hostAddress(self):
  659. """
  660. L{IListeningPort.getHost} returns the same address as a client
  661. connection's L{ITCPTransport.getPeer}.
  662. """
  663. serverFactory = MyServerFactory()
  664. serverFactory.protocolConnectionLost = defer.Deferred()
  665. serverConnectionLost = serverFactory.protocolConnectionLost
  666. port = reactor.listenTCP(0, serverFactory, interface="127.0.0.1")
  667. self.addCleanup(port.stopListening)
  668. n = port.getHost().port
  669. clientFactory = MyClientFactory()
  670. onConnection = clientFactory.protocolConnectionMade = defer.Deferred()
  671. connector = reactor.connectTCP("127.0.0.1", n, clientFactory)
  672. def check(ignored):
  673. self.assertEqual([port.getHost()], clientFactory.peerAddresses)
  674. self.assertEqual(port.getHost(), clientFactory.protocol.transport.getPeer())
  675. onConnection.addCallback(check)
  676. def cleanup(ignored):
  677. # Clean up the client explicitly here so that tear down of
  678. # the server side of the connection begins, then wait for
  679. # the server side to actually disconnect.
  680. connector.disconnect()
  681. return serverConnectionLost
  682. onConnection.addCallback(cleanup)
  683. return onConnection
  684. class WriterProtocol(protocol.Protocol):
  685. def connectionMade(self):
  686. # use everything ITransport claims to provide. If something here
  687. # fails, the exception will be written to the log, but it will not
  688. # directly flunk the test. The test will fail when maximum number of
  689. # iterations have passed and the writer's factory.done has not yet
  690. # been set.
  691. self.transport.write(b"Hello Cleveland!\n")
  692. seq = [b"Goodbye", b" cruel", b" world", b"\n"]
  693. self.transport.writeSequence(seq)
  694. peer = self.transport.getPeer()
  695. if peer.type != "TCP":
  696. msg(f"getPeer returned non-TCP socket: {peer}")
  697. self.factory.problem = 1
  698. us = self.transport.getHost()
  699. if us.type != "TCP":
  700. msg(f"getHost returned non-TCP socket: {us}")
  701. self.factory.problem = 1
  702. self.factory.done = 1
  703. self.transport.loseConnection()
  704. class ReaderProtocol(protocol.Protocol):
  705. def dataReceived(self, data):
  706. self.factory.data += data
  707. def connectionLost(self, reason):
  708. self.factory.done = 1
  709. class WriterClientFactory(protocol.ClientFactory):
  710. def __init__(self):
  711. self.done = 0
  712. self.data = b""
  713. def buildProtocol(self, addr):
  714. p = ReaderProtocol()
  715. p.factory = self
  716. self.protocol = p
  717. return p
  718. class WriteDataTests(TestCase):
  719. """
  720. Test that connected TCP sockets can actually write data. Try to exercise
  721. the entire ITransport interface.
  722. """
  723. def test_writer(self):
  724. """
  725. L{ITCPTransport.write} and L{ITCPTransport.writeSequence} send bytes to
  726. the other end of the connection.
  727. """
  728. f = protocol.Factory()
  729. f.protocol = WriterProtocol
  730. f.done = 0
  731. f.problem = 0
  732. wrappedF = WiredFactory(f)
  733. p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1")
  734. self.addCleanup(p.stopListening)
  735. n = p.getHost().port
  736. clientF = WriterClientFactory()
  737. wrappedClientF = WiredFactory(clientF)
  738. reactor.connectTCP("127.0.0.1", n, wrappedClientF)
  739. def check(ignored):
  740. self.assertTrue(f.done, "writer didn't finish, it probably died")
  741. self.assertTrue(f.problem == 0, "writer indicated an error")
  742. self.assertTrue(clientF.done, "client didn't see connection dropped")
  743. expected = b"".join(
  744. [b"Hello Cleveland!\n", b"Goodbye", b" cruel", b" world", b"\n"]
  745. )
  746. self.assertTrue(
  747. clientF.data == expected,
  748. "client didn't receive all the data it expected",
  749. )
  750. d = defer.gatherResults([wrappedF.onDisconnect, wrappedClientF.onDisconnect])
  751. return d.addCallback(check)
  752. def test_writeAfterShutdownWithoutReading(self):
  753. """
  754. A TCP transport which is written to after the connection has been shut
  755. down should notify its protocol that the connection has been lost, even
  756. if the TCP transport is not actively being monitored for read events
  757. (ie, pauseProducing was called on it).
  758. """
  759. # This is an unpleasant thing. Generally tests shouldn't skip or
  760. # run based on the name of the reactor being used (most tests
  761. # shouldn't care _at all_ what reactor is being used, in fact). The
  762. # IOCP reactor cannot pass this test, though -- please see the skip
  763. # reason below for details.
  764. if reactor.__class__.__name__ == "IOCPReactor":
  765. raise SkipTest(
  766. "iocpreactor does not, in fact, stop reading immediately "
  767. "after pauseProducing is called. This results in a "
  768. "bonus disconnection notification. Under some "
  769. "circumstances, it might be possible to not receive "
  770. "this notifications (specifically, pauseProducing, "
  771. "deliver some data, proceed with this test). "
  772. )
  773. # Called back after the protocol for the client side of the connection
  774. # has paused its transport, preventing it from reading, therefore
  775. # preventing it from noticing the disconnection before the rest of the
  776. # actions which are necessary to trigger the case this test is for have
  777. # been taken.
  778. clientPaused = defer.Deferred()
  779. # Called back when the protocol for the server side of the connection
  780. # has received connection lost notification.
  781. serverLost = defer.Deferred()
  782. class Disconnecter(protocol.Protocol):
  783. """
  784. Protocol for the server side of the connection which disconnects
  785. itself in a callback on clientPaused and publishes notification
  786. when its connection is actually lost.
  787. """
  788. def connectionMade(self):
  789. """
  790. Set up a callback on clientPaused to lose the connection.
  791. """
  792. msg("Disconnector.connectionMade")
  793. def disconnect(ignored):
  794. msg("Disconnector.connectionMade disconnect")
  795. self.transport.loseConnection()
  796. msg("loseConnection called")
  797. clientPaused.addCallback(disconnect)
  798. def connectionLost(self, reason):
  799. """
  800. Notify observers that the server side of the connection has
  801. ended.
  802. """
  803. msg("Disconnecter.connectionLost")
  804. serverLost.callback(None)
  805. msg("serverLost called back")
  806. # Create the server port to which a connection will be made.
  807. server = protocol.ServerFactory()
  808. server.protocol = Disconnecter
  809. port = reactor.listenTCP(0, server, interface="127.0.0.1")
  810. self.addCleanup(port.stopListening)
  811. addr = port.getHost()
  812. @implementer(IPullProducer)
  813. class Infinite:
  814. """
  815. A producer which will write to its consumer as long as
  816. resumeProducing is called.
  817. @ivar consumer: The L{IConsumer} which will be written to.
  818. """
  819. def __init__(self, consumer):
  820. self.consumer = consumer
  821. def resumeProducing(self):
  822. msg("Infinite.resumeProducing")
  823. self.consumer.write(b"x")
  824. msg("Infinite.resumeProducing wrote to consumer")
  825. def stopProducing(self):
  826. msg("Infinite.stopProducing")
  827. class UnreadingWriter(protocol.Protocol):
  828. """
  829. Trivial protocol which pauses its transport immediately and then
  830. writes some bytes to it.
  831. """
  832. def connectionMade(self):
  833. msg("UnreadingWriter.connectionMade")
  834. self.transport.pauseProducing()
  835. clientPaused.callback(None)
  836. msg("clientPaused called back")
  837. def write(ignored):
  838. msg("UnreadingWriter.connectionMade write")
  839. # This needs to be enough bytes to spill over into the
  840. # userspace Twisted send buffer - if it all fits into
  841. # the kernel, Twisted won't even poll for OUT events,
  842. # which means it won't poll for any events at all, so
  843. # the disconnection is never noticed. This is due to
  844. # #1662. When #1662 is fixed, this test will likely
  845. # need to be adjusted, otherwise connection lost
  846. # notification will happen too soon and the test will
  847. # probably begin to fail with ConnectionDone instead of
  848. # ConnectionLost (in any case, it will no longer be
  849. # entirely correct).
  850. producer = Infinite(self.transport)
  851. msg("UnreadingWriter.connectionMade write created producer")
  852. self.transport.registerProducer(producer, False)
  853. msg("UnreadingWriter.connectionMade write registered producer")
  854. serverLost.addCallback(write)
  855. # Create the client and initiate the connection
  856. client = MyClientFactory()
  857. client.protocolFactory = UnreadingWriter
  858. clientConnectionLost = client.deferred
  859. def cbClientLost(ignored):
  860. msg("cbClientLost")
  861. return client.lostReason
  862. clientConnectionLost.addCallback(cbClientLost)
  863. msg(f"Connecting to {addr.host}:{addr.port}")
  864. reactor.connectTCP(addr.host, addr.port, client)
  865. # By the end of the test, the client should have received notification
  866. # of unclean disconnection.
  867. msg("Returning Deferred")
  868. return self.assertFailure(clientConnectionLost, error.ConnectionLost)
  869. class ConnectionLosingProtocol(protocol.Protocol):
  870. def connectionMade(self):
  871. self.transport.write(b"1")
  872. self.transport.loseConnection()
  873. self.master._connectionMade()
  874. self.master.ports.append(self.transport)
  875. class NoopProtocol(protocol.Protocol):
  876. def connectionMade(self):
  877. self.d = defer.Deferred()
  878. self.master.serverConns.append(self.d)
  879. def connectionLost(self, reason):
  880. self.d.callback(True)
  881. class ConnectionLostNotifyingProtocol(protocol.Protocol):
  882. """
  883. Protocol which fires a Deferred which was previously passed to
  884. its initializer when the connection is lost.
  885. @ivar onConnectionLost: The L{Deferred} which will be fired in
  886. C{connectionLost}.
  887. @ivar lostConnectionReason: L{None} until the connection is lost, then a
  888. reference to the reason passed to C{connectionLost}.
  889. """
  890. def __init__(self, onConnectionLost):
  891. self.lostConnectionReason = None
  892. self.onConnectionLost = onConnectionLost
  893. def connectionLost(self, reason):
  894. self.lostConnectionReason = reason
  895. self.onConnectionLost.callback(self)
  896. class HandleSavingProtocol(ConnectionLostNotifyingProtocol):
  897. """
  898. Protocol which grabs the platform-specific socket handle and
  899. saves it as an attribute on itself when the connection is
  900. established.
  901. """
  902. def makeConnection(self, transport):
  903. """
  904. Save the platform-specific socket handle for future
  905. introspection.
  906. """
  907. self.handle = transport.getHandle()
  908. return protocol.Protocol.makeConnection(self, transport)
  909. class ProperlyCloseFilesMixin:
  910. """
  911. Tests for platform resources properly being cleaned up.
  912. """
  913. def createServer(self, address, portNumber, factory):
  914. """
  915. Bind a server port to which connections will be made. The server
  916. should use the given protocol factory.
  917. @return: The L{IListeningPort} for the server created.
  918. """
  919. raise NotImplementedError()
  920. def connectClient(self, address, portNumber, clientCreator):
  921. """
  922. Establish a connection to the given address using the given
  923. L{ClientCreator} instance.
  924. @return: A Deferred which will fire with the connected protocol instance.
  925. """
  926. raise NotImplementedError()
  927. def getHandleExceptionType(self):
  928. """
  929. Return the exception class which will be raised when an operation is
  930. attempted on a closed platform handle.
  931. """
  932. raise NotImplementedError()
  933. def getHandleErrorCodeMatcher(self):
  934. """
  935. Return a L{hamcrest.core.matcher.Matcher} that matches the
  936. errno expected to result from writing to a closed platform
  937. socket handle.
  938. """
  939. # Windows: returns WSAENOTSOCK
  940. # Linux, FreeBSD, macOS: returns EBADF
  941. if platform.isWindows():
  942. return hamcrest.equal_to(errno.WSAENOTSOCK)
  943. return hamcrest.equal_to(errno.EBADF)
  944. def test_properlyCloseFiles(self):
  945. """
  946. Test that lost connections properly have their underlying socket
  947. resources cleaned up.
  948. """
  949. onServerConnectionLost = defer.Deferred()
  950. serverFactory = protocol.ServerFactory()
  951. serverFactory.protocol = lambda: ConnectionLostNotifyingProtocol(
  952. onServerConnectionLost
  953. )
  954. serverPort = self.createServer("127.0.0.1", 0, serverFactory)
  955. onClientConnectionLost = defer.Deferred()
  956. serverAddr = serverPort.getHost()
  957. clientCreator = protocol.ClientCreator(
  958. reactor, lambda: HandleSavingProtocol(onClientConnectionLost)
  959. )
  960. clientDeferred = self.connectClient(
  961. serverAddr.host, serverAddr.port, clientCreator
  962. )
  963. def clientConnected(client):
  964. """
  965. Disconnect the client. Return a Deferred which fires when both
  966. the client and the server have received disconnect notification.
  967. """
  968. client.transport.write(b"some bytes to make sure the connection is set up")
  969. client.transport.loseConnection()
  970. return defer.gatherResults([onClientConnectionLost, onServerConnectionLost])
  971. clientDeferred.addCallback(clientConnected)
  972. def clientDisconnected(result):
  973. """
  974. Verify that the underlying platform socket handle has been
  975. cleaned up.
  976. """
  977. client, server = result
  978. if not client.lostConnectionReason.check(error.ConnectionClosed):
  979. err(
  980. client.lostConnectionReason,
  981. "Client lost connection for unexpected reason",
  982. )
  983. if not server.lostConnectionReason.check(error.ConnectionClosed):
  984. err(
  985. server.lostConnectionReason,
  986. "Server lost connection for unexpected reason",
  987. )
  988. errorCodeMatcher = self.getHandleErrorCodeMatcher()
  989. exception = self.assertRaises(
  990. self.getHandleExceptionType(), client.handle.send, b"bytes"
  991. )
  992. hamcrest.assert_that(
  993. exception.args[0],
  994. errorCodeMatcher,
  995. )
  996. clientDeferred.addCallback(clientDisconnected)
  997. def cleanup(passthrough):
  998. """
  999. Shut down the server port. Return a Deferred which fires when
  1000. this has completed.
  1001. """
  1002. result = defer.maybeDeferred(serverPort.stopListening)
  1003. result.addCallback(lambda ign: passthrough)
  1004. return result
  1005. clientDeferred.addBoth(cleanup)
  1006. return clientDeferred
  1007. class ProperlyCloseFilesTests(TestCase, ProperlyCloseFilesMixin):
  1008. """
  1009. Test that the sockets created by L{IReactorTCP.connectTCP} are cleaned up
  1010. when the connection they are associated with is closed.
  1011. """
  1012. def createServer(self, address, portNumber, factory):
  1013. """
  1014. Create a TCP server using L{IReactorTCP.listenTCP}.
  1015. """
  1016. return reactor.listenTCP(portNumber, factory, interface=address)
  1017. def connectClient(self, address, portNumber, clientCreator):
  1018. """
  1019. Create a TCP client using L{IReactorTCP.connectTCP}.
  1020. """
  1021. return clientCreator.connectTCP(address, portNumber)
  1022. def getHandleExceptionType(self):
  1023. """
  1024. Return L{socket.error} as the expected error type which will be
  1025. raised by a write to the low-level socket object after it has been
  1026. closed.
  1027. """
  1028. return socket.error
  1029. class WiredForDeferreds(policies.ProtocolWrapper):
  1030. def __init__(self, factory, wrappedProtocol):
  1031. policies.ProtocolWrapper.__init__(self, factory, wrappedProtocol)
  1032. def connectionMade(self):
  1033. policies.ProtocolWrapper.connectionMade(self)
  1034. self.factory.onConnect.callback(None)
  1035. def connectionLost(self, reason):
  1036. policies.ProtocolWrapper.connectionLost(self, reason)
  1037. self.factory.onDisconnect.callback(None)
  1038. class WiredFactory(policies.WrappingFactory):
  1039. protocol = WiredForDeferreds
  1040. def __init__(self, wrappedFactory):
  1041. policies.WrappingFactory.__init__(self, wrappedFactory)
  1042. self.onConnect = defer.Deferred()
  1043. self.onDisconnect = defer.Deferred()
  1044. class AddressTests(TestCase):
  1045. """
  1046. Tests for address-related interactions with client and server protocols.
  1047. """
  1048. def setUp(self):
  1049. """
  1050. Create a port and connected client/server pair which can be used
  1051. to test factory behavior related to addresses.
  1052. @return: A L{defer.Deferred} which will be called back when both the
  1053. client and server protocols have received their connection made
  1054. callback.
  1055. """
  1056. class RememberingWrapper(protocol.ClientFactory):
  1057. """
  1058. Simple wrapper factory which records the addresses which are
  1059. passed to its L{buildProtocol} method and delegates actual
  1060. protocol creation to another factory.
  1061. @ivar addresses: A list of the objects passed to buildProtocol.
  1062. @ivar factory: The wrapped factory to which protocol creation is
  1063. delegated.
  1064. """
  1065. def __init__(self, factory):
  1066. self.addresses = []
  1067. self.factory = factory
  1068. # Only bother to pass on buildProtocol calls to the wrapped
  1069. # factory - doStart, doStop, etc aren't necessary for this test
  1070. # to pass.
  1071. def buildProtocol(self, addr):
  1072. """
  1073. Append the given address to C{self.addresses} and forward
  1074. the call to C{self.factory}.
  1075. """
  1076. self.addresses.append(addr)
  1077. return self.factory.buildProtocol(addr)
  1078. # Make a server which we can receive connection and disconnection
  1079. # notification for, and which will record the address passed to its
  1080. # buildProtocol.
  1081. self.server = MyServerFactory()
  1082. self.serverConnMade = self.server.protocolConnectionMade = defer.Deferred()
  1083. self.serverConnLost = self.server.protocolConnectionLost = defer.Deferred()
  1084. # RememberingWrapper is a ClientFactory, but ClientFactory is-a
  1085. # ServerFactory, so this is okay.
  1086. self.serverWrapper = RememberingWrapper(self.server)
  1087. # Do something similar for a client.
  1088. self.client = MyClientFactory()
  1089. self.clientConnMade = self.client.protocolConnectionMade = defer.Deferred()
  1090. self.clientConnLost = self.client.protocolConnectionLost = defer.Deferred()
  1091. self.clientWrapper = RememberingWrapper(self.client)
  1092. self.port = reactor.listenTCP(0, self.serverWrapper, interface="127.0.0.1")
  1093. self.connector = reactor.connectTCP(
  1094. self.port.getHost().host, self.port.getHost().port, self.clientWrapper
  1095. )
  1096. return defer.gatherResults([self.serverConnMade, self.clientConnMade])
  1097. def tearDown(self):
  1098. """
  1099. Disconnect the client/server pair and shutdown the port created in
  1100. L{setUp}.
  1101. """
  1102. self.connector.disconnect()
  1103. return defer.gatherResults(
  1104. [
  1105. self.serverConnLost,
  1106. self.clientConnLost,
  1107. defer.maybeDeferred(self.port.stopListening),
  1108. ]
  1109. )
  1110. def test_buildProtocolClient(self):
  1111. """
  1112. L{ClientFactory.buildProtocol} should be invoked with the address of
  1113. the server to which a connection has been established, which should
  1114. be the same as the address reported by the C{getHost} method of the
  1115. transport of the server protocol and as the C{getPeer} method of the
  1116. transport of the client protocol.
  1117. """
  1118. serverHost = self.server.protocol.transport.getHost()
  1119. clientPeer = self.client.protocol.transport.getPeer()
  1120. self.assertEqual(
  1121. self.clientWrapper.addresses,
  1122. [IPv4Address("TCP", serverHost.host, serverHost.port)],
  1123. )
  1124. self.assertEqual(
  1125. self.clientWrapper.addresses,
  1126. [IPv4Address("TCP", clientPeer.host, clientPeer.port)],
  1127. )
  1128. class LargeBufferWriterProtocol(protocol.Protocol):
  1129. # Win32 sockets cannot handle single huge chunks of bytes. Write one
  1130. # massive string to make sure Twisted deals with this fact. Immediately
  1131. # follow that with another write to test behaviour under load (see issue
  1132. # #9446)
  1133. def connectionMade(self):
  1134. self.transport.write(b"X" * (self.factory.len - 1))
  1135. def finish():
  1136. self.transport.write(b"X")
  1137. self.factory.done = 1
  1138. self.transport.loseConnection()
  1139. reactor.callLater(0.001, finish)
  1140. class LargeBufferReaderProtocol(protocol.Protocol):
  1141. def dataReceived(self, data):
  1142. self.factory.len += len(data)
  1143. def connectionLost(self, reason):
  1144. self.factory.done = 1
  1145. class LargeBufferReaderClientFactory(protocol.ClientFactory):
  1146. def __init__(self):
  1147. self.done = 0
  1148. self.len = 0
  1149. def buildProtocol(self, addr):
  1150. p = LargeBufferReaderProtocol()
  1151. p.factory = self
  1152. self.protocol = p
  1153. return p
  1154. class FireOnClose(policies.ProtocolWrapper):
  1155. """A wrapper around a protocol that makes it fire a deferred when
  1156. connectionLost is called.
  1157. """
  1158. def connectionLost(self, reason):
  1159. policies.ProtocolWrapper.connectionLost(self, reason)
  1160. self.factory.deferred.callback(None)
  1161. class FireOnCloseFactory(policies.WrappingFactory):
  1162. protocol = FireOnClose
  1163. def __init__(self, wrappedFactory):
  1164. policies.WrappingFactory.__init__(self, wrappedFactory)
  1165. self.deferred = defer.Deferred()
  1166. class LargeBufferTests(TestCase):
  1167. """Test that buffering large amounts of data works."""
  1168. datalen = 60 * 1024 * 1024
  1169. def testWriter(self):
  1170. f = protocol.Factory()
  1171. f.protocol = LargeBufferWriterProtocol
  1172. f.done = 0
  1173. f.problem = 0
  1174. f.len = self.datalen
  1175. wrappedF = FireOnCloseFactory(f)
  1176. p = reactor.listenTCP(0, wrappedF, interface="127.0.0.1")
  1177. self.addCleanup(p.stopListening)
  1178. n = p.getHost().port
  1179. clientF = LargeBufferReaderClientFactory()
  1180. wrappedClientF = FireOnCloseFactory(clientF)
  1181. reactor.connectTCP("127.0.0.1", n, wrappedClientF)
  1182. d = defer.gatherResults([wrappedF.deferred, wrappedClientF.deferred])
  1183. def check(ignored):
  1184. self.assertTrue(f.done, "writer didn't finish, it probably died")
  1185. self.assertTrue(
  1186. clientF.len >= self.datalen,
  1187. "client didn't receive all the data it expected "
  1188. "(%d != %d)" % (clientF.len, self.datalen),
  1189. )
  1190. self.assertTrue(
  1191. clientF.len <= self.datalen,
  1192. "client did receive more data than it expected "
  1193. "(%d != %d)" % (clientF.len, self.datalen),
  1194. )
  1195. self.assertTrue(clientF.done, "client didn't see connection dropped")
  1196. return d.addCallback(check)
  1197. @implementer(IHalfCloseableProtocol)
  1198. class MyHCProtocol(AccumulatingProtocol):
  1199. readHalfClosed = False
  1200. writeHalfClosed = False
  1201. def readConnectionLost(self):
  1202. self.readHalfClosed = True
  1203. # Invoke notification logic from the base class to simplify testing.
  1204. if self.writeHalfClosed:
  1205. self.connectionLost(None)
  1206. def writeConnectionLost(self):
  1207. self.writeHalfClosed = True
  1208. # Invoke notification logic from the base class to simplify testing.
  1209. if self.readHalfClosed:
  1210. self.connectionLost(None)
  1211. class MyHCFactory(protocol.ServerFactory):
  1212. called = 0
  1213. protocolConnectionMade = None
  1214. def buildProtocol(self, addr):
  1215. self.called += 1
  1216. p = MyHCProtocol()
  1217. p.factory = self
  1218. self.protocol = p
  1219. return p
  1220. class HalfCloseTests(TestCase):
  1221. """Test half-closing connections."""
  1222. def setUp(self):
  1223. self.f = f = MyHCFactory()
  1224. self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")
  1225. self.addCleanup(p.stopListening)
  1226. d = loopUntil(lambda: p.connected)
  1227. self.cf = protocol.ClientCreator(reactor, MyHCProtocol)
  1228. d.addCallback(lambda _: self.cf.connectTCP(p.getHost().host, p.getHost().port))
  1229. d.addCallback(self._setUp)
  1230. return d
  1231. def _setUp(self, client):
  1232. self.client = client
  1233. self.clientProtoConnectionLost = self.client.closedDeferred = defer.Deferred()
  1234. self.assertEqual(self.client.transport.connected, 1)
  1235. # Wait for the server to notice there is a connection, too.
  1236. return loopUntil(lambda: getattr(self.f, "protocol", None) is not None)
  1237. def tearDown(self):
  1238. self.assertEqual(self.client.closed, 0)
  1239. self.client.transport.loseConnection()
  1240. d = defer.maybeDeferred(self.p.stopListening)
  1241. d.addCallback(lambda ign: self.clientProtoConnectionLost)
  1242. d.addCallback(self._tearDown)
  1243. return d
  1244. def _tearDown(self, ignored):
  1245. self.assertEqual(self.client.closed, 1)
  1246. # because we did half-close, the server also needs to
  1247. # closed explicitly.
  1248. self.assertEqual(self.f.protocol.closed, 0)
  1249. d = defer.Deferred()
  1250. def _connectionLost(reason):
  1251. self.f.protocol.closed = 1
  1252. d.callback(None)
  1253. self.f.protocol.connectionLost = _connectionLost
  1254. self.f.protocol.transport.loseConnection()
  1255. d.addCallback(lambda x: self.assertEqual(self.f.protocol.closed, 1))
  1256. return d
  1257. def testCloseWriteCloser(self):
  1258. client = self.client
  1259. f = self.f
  1260. t = client.transport
  1261. t.write(b"hello")
  1262. d = loopUntil(lambda: len(t._tempDataBuffer) == 0)
  1263. def loseWrite(ignored):
  1264. t.loseWriteConnection()
  1265. return loopUntil(lambda: t._writeDisconnected)
  1266. def check(ignored):
  1267. self.assertFalse(client.closed)
  1268. self.assertTrue(client.writeHalfClosed)
  1269. self.assertFalse(client.readHalfClosed)
  1270. return loopUntil(lambda: f.protocol.readHalfClosed)
  1271. def write(ignored):
  1272. w = client.transport.write
  1273. w(b" world")
  1274. w(b"lalala fooled you")
  1275. self.assertEqual(0, len(client.transport._tempDataBuffer))
  1276. self.assertEqual(f.protocol.data, b"hello")
  1277. self.assertFalse(f.protocol.closed)
  1278. self.assertTrue(f.protocol.readHalfClosed)
  1279. return d.addCallback(loseWrite).addCallback(check).addCallback(write)
  1280. def testWriteCloseNotification(self):
  1281. f = self.f
  1282. f.protocol.transport.loseWriteConnection()
  1283. d = defer.gatherResults(
  1284. [
  1285. loopUntil(lambda: f.protocol.writeHalfClosed),
  1286. loopUntil(lambda: self.client.readHalfClosed),
  1287. ]
  1288. )
  1289. d.addCallback(lambda _: self.assertEqual(f.protocol.readHalfClosed, False))
  1290. return d
  1291. class HalfCloseNoNotificationAndShutdownExceptionTests(TestCase):
  1292. def setUp(self):
  1293. self.f = f = MyServerFactory()
  1294. self.f.protocolConnectionMade = defer.Deferred()
  1295. self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1")
  1296. # XXX we don't test server side yet since we don't do it yet
  1297. d = protocol.ClientCreator(reactor, AccumulatingProtocol).connectTCP(
  1298. p.getHost().host, p.getHost().port
  1299. )
  1300. d.addCallback(self._gotClient)
  1301. return d
  1302. def _gotClient(self, client):
  1303. self.client = client
  1304. # Now wait for the server to catch up - it doesn't matter if this
  1305. # Deferred has already fired and gone away, in that case we'll
  1306. # return None and not wait at all, which is precisely correct.
  1307. return self.f.protocolConnectionMade
  1308. def tearDown(self):
  1309. self.client.transport.loseConnection()
  1310. return self.p.stopListening()
  1311. def testNoNotification(self):
  1312. """
  1313. TCP protocols support half-close connections, but not all of them
  1314. support being notified of write closes. In this case, test that
  1315. half-closing the connection causes the peer's connection to be
  1316. closed.
  1317. """
  1318. self.client.transport.write(b"hello")
  1319. self.client.transport.loseWriteConnection()
  1320. self.f.protocol.closedDeferred = d = defer.Deferred()
  1321. self.client.closedDeferred = d2 = defer.Deferred()
  1322. d.addCallback(lambda x: self.assertEqual(self.f.protocol.data, b"hello"))
  1323. d.addCallback(lambda x: self.assertTrue(self.f.protocol.closed))
  1324. return defer.gatherResults([d, d2])
  1325. def testShutdownException(self):
  1326. """
  1327. If the other side has already closed its connection,
  1328. loseWriteConnection should pass silently.
  1329. """
  1330. self.f.protocol.transport.loseConnection()
  1331. self.client.transport.write(b"X")
  1332. self.client.transport.loseWriteConnection()
  1333. self.f.protocol.closedDeferred = d = defer.Deferred()
  1334. self.client.closedDeferred = d2 = defer.Deferred()
  1335. d.addCallback(lambda x: self.assertTrue(self.f.protocol.closed))
  1336. return defer.gatherResults([d, d2])
  1337. class HalfCloseBuggyApplicationTests(TestCase):
  1338. """
  1339. Test half-closing connections where notification code has bugs.
  1340. """
  1341. def setUp(self):
  1342. """
  1343. Set up a server and connect a client to it. Return a Deferred which
  1344. only fires once this is done.
  1345. """
  1346. self.serverFactory = MyHCFactory()
  1347. self.serverFactory.protocolConnectionMade = defer.Deferred()
  1348. self.port = reactor.listenTCP(0, self.serverFactory, interface="127.0.0.1")
  1349. self.addCleanup(self.port.stopListening)
  1350. addr = self.port.getHost()
  1351. creator = protocol.ClientCreator(reactor, MyHCProtocol)
  1352. clientDeferred = creator.connectTCP(addr.host, addr.port)
  1353. def setClient(clientProtocol):
  1354. self.clientProtocol = clientProtocol
  1355. clientDeferred.addCallback(setClient)
  1356. return defer.gatherResults(
  1357. [self.serverFactory.protocolConnectionMade, clientDeferred]
  1358. )
  1359. def aBug(self, *args):
  1360. """
  1361. Fake implementation of a callback which illegally raises an
  1362. exception.
  1363. """
  1364. raise RuntimeError("ONO I AM BUGGY CODE")
  1365. def _notificationRaisesTest(self):
  1366. """
  1367. Helper for testing that an exception is logged by the time the
  1368. client protocol loses its connection.
  1369. """
  1370. closed = self.clientProtocol.closedDeferred = defer.Deferred()
  1371. self.clientProtocol.transport.loseWriteConnection()
  1372. def check(ignored):
  1373. errors = self.flushLoggedErrors(RuntimeError)
  1374. self.assertEqual(len(errors), 1)
  1375. closed.addCallback(check)
  1376. return closed
  1377. def test_readNotificationRaises(self):
  1378. """
  1379. If C{readConnectionLost} raises an exception when the transport
  1380. calls it to notify the protocol of that event, the exception should
  1381. be logged and the protocol should be disconnected completely.
  1382. """
  1383. self.serverFactory.protocol.readConnectionLost = self.aBug
  1384. return self._notificationRaisesTest()
  1385. def test_writeNotificationRaises(self):
  1386. """
  1387. If C{writeConnectionLost} raises an exception when the transport
  1388. calls it to notify the protocol of that event, the exception should
  1389. be logged and the protocol should be disconnected completely.
  1390. """
  1391. self.clientProtocol.writeConnectionLost = self.aBug
  1392. return self._notificationRaisesTest()
  1393. class LogTests(TestCase):
  1394. """
  1395. Test logging facility of TCP base classes.
  1396. """
  1397. def test_logstrClientSetup(self):
  1398. """
  1399. Check that the log customization of the client transport happens
  1400. once the client is connected.
  1401. """
  1402. server = MyServerFactory()
  1403. client = MyClientFactory()
  1404. client.protocolConnectionMade = defer.Deferred()
  1405. port = reactor.listenTCP(0, server, interface="127.0.0.1")
  1406. self.addCleanup(port.stopListening)
  1407. connector = reactor.connectTCP(port.getHost().host, port.getHost().port, client)
  1408. self.addCleanup(connector.disconnect)
  1409. # It should still have the default value
  1410. self.assertEqual(connector.transport.logstr, "Uninitialized")
  1411. def cb(ign):
  1412. self.assertEqual(connector.transport.logstr, "AccumulatingProtocol,client")
  1413. client.protocolConnectionMade.addCallback(cb)
  1414. return client.protocolConnectionMade
  1415. class PauseProducingTests(TestCase):
  1416. """
  1417. Test some behaviors of pausing the production of a transport.
  1418. """
  1419. @skipIf(
  1420. not interfaces.IReactorFDSet.providedBy(reactor),
  1421. "Reactor not providing IReactorFDSet",
  1422. )
  1423. def test_pauseProducingInConnectionMade(self):
  1424. """
  1425. In C{connectionMade} of a client protocol, C{pauseProducing} used to be
  1426. ignored: this test is here to ensure it's not ignored.
  1427. """
  1428. server = MyServerFactory()
  1429. client = MyClientFactory()
  1430. client.protocolConnectionMade = defer.Deferred()
  1431. port = reactor.listenTCP(0, server, interface="127.0.0.1")
  1432. self.addCleanup(port.stopListening)
  1433. connector = reactor.connectTCP(port.getHost().host, port.getHost().port, client)
  1434. self.addCleanup(connector.disconnect)
  1435. def checkInConnectionMade(proto):
  1436. tr = proto.transport
  1437. # The transport should already be monitored
  1438. self.assertIn(tr, reactor.getReaders() + reactor.getWriters())
  1439. proto.transport.pauseProducing()
  1440. self.assertNotIn(tr, reactor.getReaders() + reactor.getWriters())
  1441. d = defer.Deferred()
  1442. d.addCallback(checkAfterConnectionMade)
  1443. reactor.callLater(0, d.callback, proto)
  1444. return d
  1445. def checkAfterConnectionMade(proto):
  1446. tr = proto.transport
  1447. # The transport should still not be monitored
  1448. self.assertNotIn(tr, reactor.getReaders() + reactor.getWriters())
  1449. client.protocolConnectionMade.addCallback(checkInConnectionMade)
  1450. return client.protocolConnectionMade
  1451. class CallBackOrderTests(TestCase):
  1452. """
  1453. Test the order of reactor callbacks
  1454. """
  1455. def test_loseOrder(self):
  1456. """
  1457. Check that Protocol.connectionLost is called before factory's
  1458. clientConnectionLost
  1459. """
  1460. server = MyServerFactory()
  1461. server.protocolConnectionMade = defer.Deferred().addCallback(
  1462. lambda proto: self.addCleanup(proto.transport.loseConnection)
  1463. )
  1464. client = MyClientFactory()
  1465. client.protocolConnectionLost = defer.Deferred()
  1466. client.protocolConnectionMade = defer.Deferred()
  1467. def _cbCM(res):
  1468. """
  1469. protocol.connectionMade callback
  1470. """
  1471. reactor.callLater(0, client.protocol.transport.loseConnection)
  1472. client.protocolConnectionMade.addCallback(_cbCM)
  1473. port = reactor.listenTCP(0, server, interface="127.0.0.1")
  1474. self.addCleanup(port.stopListening)
  1475. connector = reactor.connectTCP(port.getHost().host, port.getHost().port, client)
  1476. self.addCleanup(connector.disconnect)
  1477. def _cbCCL(res):
  1478. """
  1479. factory.clientConnectionLost callback
  1480. """
  1481. return "CCL"
  1482. def _cbCL(res):
  1483. """
  1484. protocol.connectionLost callback
  1485. """
  1486. return "CL"
  1487. def _cbGather(res):
  1488. self.assertEqual(res, ["CL", "CCL"])
  1489. d = defer.gatherResults(
  1490. [
  1491. client.protocolConnectionLost.addCallback(_cbCL),
  1492. client.deferred.addCallback(_cbCCL),
  1493. ]
  1494. )
  1495. return d.addCallback(_cbGather)
  1496. try:
  1497. import resource
  1498. except ImportError:
  1499. pass
  1500. else:
  1501. numRounds = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + 10
  1502. setattr(ProperlyCloseFilesTests, "numberRounds", numRounds)