test_tcp.py 64 KB

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