endpoints.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. # -*- test-case-name: twisted.internet.test.test_endpoints -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Implementations of L{IStreamServerEndpoint} and L{IStreamClientEndpoint} that
  6. wrap the L{IReactorTCP}, L{IReactorSSL}, and L{IReactorUNIX} interfaces.
  7. This also implements an extensible mini-language for describing endpoints,
  8. parsed by the L{clientFromString} and L{serverFromString} functions.
  9. @since: 10.1
  10. """
  11. from __future__ import division, absolute_import
  12. import os
  13. import re
  14. import socket
  15. from unicodedata import normalize
  16. import warnings
  17. from constantly import NamedConstant, Names
  18. from incremental import Version
  19. from zope.interface import implementer, directlyProvides, provider
  20. from twisted.internet import interfaces, defer, error, fdesc, threads
  21. from twisted.internet.abstract import isIPv6Address, isIPAddress
  22. from twisted.internet.address import (
  23. _ProcessAddress, HostnameAddress, IPv4Address, IPv6Address
  24. )
  25. from twisted.internet.interfaces import (
  26. IStreamServerEndpointStringParser,
  27. IStreamClientEndpointStringParserWithReactor, IResolutionReceiver,
  28. IReactorPluggableNameResolver,
  29. IHostnameResolver,
  30. )
  31. from twisted.internet.protocol import ClientFactory, Factory
  32. from twisted.internet.protocol import ProcessProtocol, Protocol
  33. from twisted.internet.stdio import StandardIO, PipeAddress
  34. from twisted.internet.task import LoopingCall
  35. from twisted.internet._resolver import HostResolution
  36. from twisted.logger import Logger
  37. from twisted.plugin import IPlugin, getPlugins
  38. from twisted.python import deprecate, log
  39. from twisted.python.compat import nativeString, unicode, _matchingString
  40. from twisted.python.components import proxyForInterface
  41. from twisted.python.failure import Failure
  42. from twisted.python.filepath import FilePath
  43. from twisted.python.compat import iterbytes
  44. from twisted.internet.defer import Deferred
  45. from twisted.python.systemd import ListenFDs
  46. from ._idna import _idnaBytes, _idnaText
  47. try:
  48. from twisted.protocols.tls import TLSMemoryBIOFactory
  49. from twisted.internet.ssl import (
  50. optionsForClientTLS, PrivateCertificate, Certificate, KeyPair,
  51. CertificateOptions, trustRootFromCertificates
  52. )
  53. from OpenSSL.SSL import Error as SSLError
  54. except ImportError:
  55. TLSMemoryBIOFactory = None
  56. __all__ = ["clientFromString", "serverFromString",
  57. "TCP4ServerEndpoint", "TCP6ServerEndpoint",
  58. "TCP4ClientEndpoint", "TCP6ClientEndpoint",
  59. "UNIXServerEndpoint", "UNIXClientEndpoint",
  60. "SSL4ServerEndpoint", "SSL4ClientEndpoint",
  61. "AdoptedStreamServerEndpoint", "StandardIOEndpoint",
  62. "ProcessEndpoint", "HostnameEndpoint",
  63. "StandardErrorBehavior", "connectProtocol",
  64. "wrapClientTLS"]
  65. class _WrappingProtocol(Protocol):
  66. """
  67. Wrap another protocol in order to notify my user when a connection has
  68. been made.
  69. """
  70. def __init__(self, connectedDeferred, wrappedProtocol):
  71. """
  72. @param connectedDeferred: The L{Deferred} that will callback
  73. with the C{wrappedProtocol} when it is connected.
  74. @param wrappedProtocol: An L{IProtocol} provider that will be
  75. connected.
  76. """
  77. self._connectedDeferred = connectedDeferred
  78. self._wrappedProtocol = wrappedProtocol
  79. for iface in [interfaces.IHalfCloseableProtocol,
  80. interfaces.IFileDescriptorReceiver,
  81. interfaces.IHandshakeListener]:
  82. if iface.providedBy(self._wrappedProtocol):
  83. directlyProvides(self, iface)
  84. def logPrefix(self):
  85. """
  86. Transparently pass through the wrapped protocol's log prefix.
  87. """
  88. if interfaces.ILoggingContext.providedBy(self._wrappedProtocol):
  89. return self._wrappedProtocol.logPrefix()
  90. return self._wrappedProtocol.__class__.__name__
  91. def connectionMade(self):
  92. """
  93. Connect the C{self._wrappedProtocol} to our C{self.transport} and
  94. callback C{self._connectedDeferred} with the C{self._wrappedProtocol}
  95. """
  96. self._wrappedProtocol.makeConnection(self.transport)
  97. self._connectedDeferred.callback(self._wrappedProtocol)
  98. def dataReceived(self, data):
  99. """
  100. Proxy C{dataReceived} calls to our C{self._wrappedProtocol}
  101. """
  102. return self._wrappedProtocol.dataReceived(data)
  103. def fileDescriptorReceived(self, descriptor):
  104. """
  105. Proxy C{fileDescriptorReceived} calls to our C{self._wrappedProtocol}
  106. """
  107. return self._wrappedProtocol.fileDescriptorReceived(descriptor)
  108. def connectionLost(self, reason):
  109. """
  110. Proxy C{connectionLost} calls to our C{self._wrappedProtocol}
  111. """
  112. return self._wrappedProtocol.connectionLost(reason)
  113. def readConnectionLost(self):
  114. """
  115. Proxy L{IHalfCloseableProtocol.readConnectionLost} to our
  116. C{self._wrappedProtocol}
  117. """
  118. self._wrappedProtocol.readConnectionLost()
  119. def writeConnectionLost(self):
  120. """
  121. Proxy L{IHalfCloseableProtocol.writeConnectionLost} to our
  122. C{self._wrappedProtocol}
  123. """
  124. self._wrappedProtocol.writeConnectionLost()
  125. def handshakeCompleted(self):
  126. """
  127. Proxy L{interfaces.IHandshakeListener} to our
  128. C{self._wrappedProtocol}.
  129. """
  130. self._wrappedProtocol.handshakeCompleted()
  131. class _WrappingFactory(ClientFactory):
  132. """
  133. Wrap a factory in order to wrap the protocols it builds.
  134. @ivar _wrappedFactory: A provider of I{IProtocolFactory} whose buildProtocol
  135. method will be called and whose resulting protocol will be wrapped.
  136. @ivar _onConnection: A L{Deferred} that fires when the protocol is
  137. connected
  138. @ivar _connector: A L{connector <twisted.internet.interfaces.IConnector>}
  139. that is managing the current or previous connection attempt.
  140. """
  141. protocol = _WrappingProtocol
  142. def __init__(self, wrappedFactory):
  143. """
  144. @param wrappedFactory: A provider of I{IProtocolFactory} whose
  145. buildProtocol method will be called and whose resulting protocol
  146. will be wrapped.
  147. """
  148. self._wrappedFactory = wrappedFactory
  149. self._onConnection = defer.Deferred(canceller=self._canceller)
  150. def startedConnecting(self, connector):
  151. """
  152. A connection attempt was started. Remember the connector which started
  153. said attempt, for use later.
  154. """
  155. self._connector = connector
  156. def _canceller(self, deferred):
  157. """
  158. The outgoing connection attempt was cancelled. Fail that L{Deferred}
  159. with an L{error.ConnectingCancelledError}.
  160. @param deferred: The L{Deferred <defer.Deferred>} that was cancelled;
  161. should be the same as C{self._onConnection}.
  162. @type deferred: L{Deferred <defer.Deferred>}
  163. @note: This relies on startedConnecting having been called, so it may
  164. seem as though there's a race condition where C{_connector} may not
  165. have been set. However, using public APIs, this condition is
  166. impossible to catch, because a connection API
  167. (C{connectTCP}/C{SSL}/C{UNIX}) is always invoked before a
  168. L{_WrappingFactory}'s L{Deferred <defer.Deferred>} is returned to
  169. C{connect()}'s caller.
  170. @return: L{None}
  171. """
  172. deferred.errback(
  173. error.ConnectingCancelledError(
  174. self._connector.getDestination()))
  175. self._connector.stopConnecting()
  176. def doStart(self):
  177. """
  178. Start notifications are passed straight through to the wrapped factory.
  179. """
  180. self._wrappedFactory.doStart()
  181. def doStop(self):
  182. """
  183. Stop notifications are passed straight through to the wrapped factory.
  184. """
  185. self._wrappedFactory.doStop()
  186. def buildProtocol(self, addr):
  187. """
  188. Proxy C{buildProtocol} to our C{self._wrappedFactory} or errback the
  189. C{self._onConnection} L{Deferred} if the wrapped factory raises an
  190. exception or returns L{None}.
  191. @return: An instance of L{_WrappingProtocol} or L{None}
  192. """
  193. try:
  194. proto = self._wrappedFactory.buildProtocol(addr)
  195. if proto is None:
  196. raise error.NoProtocol()
  197. except:
  198. self._onConnection.errback()
  199. else:
  200. return self.protocol(self._onConnection, proto)
  201. def clientConnectionFailed(self, connector, reason):
  202. """
  203. Errback the C{self._onConnection} L{Deferred} when the
  204. client connection fails.
  205. """
  206. if not self._onConnection.called:
  207. self._onConnection.errback(reason)
  208. @implementer(interfaces.IStreamServerEndpoint)
  209. class StandardIOEndpoint(object):
  210. """
  211. A Standard Input/Output endpoint
  212. @ivar _stdio: a callable, like L{stdio.StandardIO}, which takes an
  213. L{IProtocol} provider and a C{reactor} keyword argument (interface
  214. dependent upon your platform).
  215. """
  216. _stdio = StandardIO
  217. def __init__(self, reactor):
  218. """
  219. @param reactor: The reactor for the endpoint.
  220. """
  221. self._reactor = reactor
  222. def listen(self, stdioProtocolFactory):
  223. """
  224. Implement L{IStreamServerEndpoint.listen} to listen on stdin/stdout
  225. """
  226. return defer.execute(self._stdio,
  227. stdioProtocolFactory.buildProtocol(PipeAddress()),
  228. reactor=self._reactor)
  229. class _IProcessTransportWithConsumerAndProducer(interfaces.IProcessTransport,
  230. interfaces.IConsumer,
  231. interfaces.IPushProducer):
  232. """
  233. An L{_IProcessTransportWithConsumerAndProducer} combines various interfaces
  234. to work around the issue that L{interfaces.IProcessTransport} is
  235. incompletely defined and doesn't specify flow-control interfaces, and that
  236. L{proxyForInterface} doesn't allow for multiple interfaces.
  237. """
  238. class _ProcessEndpointTransport(
  239. proxyForInterface(_IProcessTransportWithConsumerAndProducer,
  240. '_process')):
  241. """
  242. An L{ITransport}, L{IProcessTransport}, L{IConsumer}, and L{IPushProducer}
  243. provider for the L{IProtocol} instance passed to the process endpoint.
  244. @ivar _process: An active process transport which will be used by write
  245. methods on this object to write data to a child process.
  246. @type _process: L{interfaces.IProcessTransport} provider
  247. """
  248. class _WrapIProtocol(ProcessProtocol):
  249. """
  250. An L{IProcessProtocol} provider that wraps an L{IProtocol}.
  251. @ivar transport: A L{_ProcessEndpointTransport} provider that is hooked to
  252. the wrapped L{IProtocol} provider.
  253. @see: L{protocol.ProcessProtocol}
  254. """
  255. def __init__(self, proto, executable, errFlag):
  256. """
  257. @param proto: An L{IProtocol} provider.
  258. @param errFlag: A constant belonging to L{StandardErrorBehavior}
  259. that determines if stderr is logged or dropped.
  260. @param executable: The file name (full path) to spawn.
  261. """
  262. self.protocol = proto
  263. self.errFlag = errFlag
  264. self.executable = executable
  265. def makeConnection(self, process):
  266. """
  267. Call L{IProtocol} provider's makeConnection method with an
  268. L{ITransport} provider.
  269. @param process: An L{IProcessTransport} provider.
  270. """
  271. self.transport = _ProcessEndpointTransport(process)
  272. return self.protocol.makeConnection(self.transport)
  273. def childDataReceived(self, childFD, data):
  274. """
  275. This is called with data from the process's stdout or stderr pipes. It
  276. checks the status of the errFlag to setermine if stderr should be
  277. logged (default) or dropped.
  278. """
  279. if childFD == 1:
  280. return self.protocol.dataReceived(data)
  281. elif childFD == 2 and self.errFlag == StandardErrorBehavior.LOG:
  282. log.msg(
  283. format="Process %(executable)r wrote stderr unhandled by "
  284. "%(protocol)s: %(data)s",
  285. executable=self.executable, protocol=self.protocol,
  286. data=data)
  287. def processEnded(self, reason):
  288. """
  289. If the process ends with L{error.ProcessDone}, this method calls the
  290. L{IProtocol} provider's L{connectionLost} with a
  291. L{error.ConnectionDone}
  292. @see: L{ProcessProtocol.processEnded}
  293. """
  294. if (reason.check(error.ProcessDone) == error.ProcessDone) and (
  295. reason.value.status == 0):
  296. return self.protocol.connectionLost(
  297. Failure(error.ConnectionDone()))
  298. else:
  299. return self.protocol.connectionLost(reason)
  300. class StandardErrorBehavior(Names):
  301. """
  302. Constants used in ProcessEndpoint to decide what to do with stderr.
  303. @cvar LOG: Indicates that stderr is to be logged.
  304. @cvar DROP: Indicates that stderr is to be dropped (and not logged).
  305. @since: 13.1
  306. """
  307. LOG = NamedConstant()
  308. DROP = NamedConstant()
  309. @implementer(interfaces.IStreamClientEndpoint)
  310. class ProcessEndpoint(object):
  311. """
  312. An endpoint for child processes
  313. @ivar _spawnProcess: A hook used for testing the spawning of child process.
  314. @since: 13.1
  315. """
  316. def __init__(self, reactor, executable, args=(), env={}, path=None,
  317. uid=None, gid=None, usePTY=0, childFDs=None,
  318. errFlag=StandardErrorBehavior.LOG):
  319. """
  320. See L{IReactorProcess.spawnProcess}.
  321. @param errFlag: Determines if stderr should be logged.
  322. @type errFlag: L{endpoints.StandardErrorBehavior}
  323. """
  324. self._reactor = reactor
  325. self._executable = executable
  326. self._args = args
  327. self._env = env
  328. self._path = path
  329. self._uid = uid
  330. self._gid = gid
  331. self._usePTY = usePTY
  332. self._childFDs = childFDs
  333. self._errFlag = errFlag
  334. self._spawnProcess = self._reactor.spawnProcess
  335. def connect(self, protocolFactory):
  336. """
  337. Implement L{IStreamClientEndpoint.connect} to launch a child process
  338. and connect it to a protocol created by C{protocolFactory}.
  339. @param protocolFactory: A factory for an L{IProtocol} provider which
  340. will be notified of all events related to the created process.
  341. """
  342. proto = protocolFactory.buildProtocol(_ProcessAddress())
  343. try:
  344. self._spawnProcess(
  345. _WrapIProtocol(proto, self._executable, self._errFlag),
  346. self._executable, self._args, self._env, self._path, self._uid,
  347. self._gid, self._usePTY, self._childFDs)
  348. except:
  349. return defer.fail()
  350. else:
  351. return defer.succeed(proto)
  352. @implementer(interfaces.IStreamServerEndpoint)
  353. class _TCPServerEndpoint(object):
  354. """
  355. A TCP server endpoint interface
  356. """
  357. def __init__(self, reactor, port, backlog, interface):
  358. """
  359. @param reactor: An L{IReactorTCP} provider.
  360. @param port: The port number used for listening
  361. @type port: int
  362. @param backlog: Size of the listen queue
  363. @type backlog: int
  364. @param interface: The hostname to bind to
  365. @type interface: str
  366. """
  367. self._reactor = reactor
  368. self._port = port
  369. self._backlog = backlog
  370. self._interface = interface
  371. def listen(self, protocolFactory):
  372. """
  373. Implement L{IStreamServerEndpoint.listen} to listen on a TCP
  374. socket
  375. """
  376. return defer.execute(self._reactor.listenTCP,
  377. self._port,
  378. protocolFactory,
  379. backlog=self._backlog,
  380. interface=self._interface)
  381. class TCP4ServerEndpoint(_TCPServerEndpoint):
  382. """
  383. Implements TCP server endpoint with an IPv4 configuration
  384. """
  385. def __init__(self, reactor, port, backlog=50, interface=''):
  386. """
  387. @param reactor: An L{IReactorTCP} provider.
  388. @param port: The port number used for listening
  389. @type port: int
  390. @param backlog: Size of the listen queue
  391. @type backlog: int
  392. @param interface: The hostname to bind to, defaults to '' (all)
  393. @type interface: str
  394. """
  395. _TCPServerEndpoint.__init__(self, reactor, port, backlog, interface)
  396. class TCP6ServerEndpoint(_TCPServerEndpoint):
  397. """
  398. Implements TCP server endpoint with an IPv6 configuration
  399. """
  400. def __init__(self, reactor, port, backlog=50, interface='::'):
  401. """
  402. @param reactor: An L{IReactorTCP} provider.
  403. @param port: The port number used for listening
  404. @type port: int
  405. @param backlog: Size of the listen queue
  406. @type backlog: int
  407. @param interface: The hostname to bind to, defaults to C{::} (all)
  408. @type interface: str
  409. """
  410. _TCPServerEndpoint.__init__(self, reactor, port, backlog, interface)
  411. @implementer(interfaces.IStreamClientEndpoint)
  412. class TCP4ClientEndpoint(object):
  413. """
  414. TCP client endpoint with an IPv4 configuration.
  415. """
  416. def __init__(self, reactor, host, port, timeout=30, bindAddress=None):
  417. """
  418. @param reactor: An L{IReactorTCP} provider
  419. @param host: A hostname, used when connecting
  420. @type host: str
  421. @param port: The port number, used when connecting
  422. @type port: int
  423. @param timeout: The number of seconds to wait before assuming the
  424. connection has failed.
  425. @type timeout: int
  426. @param bindAddress: A (host, port) tuple of local address to bind to,
  427. or None.
  428. @type bindAddress: tuple
  429. """
  430. self._reactor = reactor
  431. self._host = host
  432. self._port = port
  433. self._timeout = timeout
  434. self._bindAddress = bindAddress
  435. def connect(self, protocolFactory):
  436. """
  437. Implement L{IStreamClientEndpoint.connect} to connect via TCP.
  438. """
  439. try:
  440. wf = _WrappingFactory(protocolFactory)
  441. self._reactor.connectTCP(
  442. self._host, self._port, wf,
  443. timeout=self._timeout, bindAddress=self._bindAddress)
  444. return wf._onConnection
  445. except:
  446. return defer.fail()
  447. @implementer(interfaces.IStreamClientEndpoint)
  448. class TCP6ClientEndpoint(object):
  449. """
  450. TCP client endpoint with an IPv6 configuration.
  451. @ivar _getaddrinfo: A hook used for testing name resolution.
  452. @ivar _deferToThread: A hook used for testing deferToThread.
  453. @ivar _GAI_ADDRESS: Index of the address portion in result of
  454. getaddrinfo to be used.
  455. @ivar _GAI_ADDRESS_HOST: Index of the actual host-address in the
  456. 5-tuple L{_GAI_ADDRESS}.
  457. """
  458. _getaddrinfo = staticmethod(socket.getaddrinfo)
  459. _deferToThread = staticmethod(threads.deferToThread)
  460. _GAI_ADDRESS = 4
  461. _GAI_ADDRESS_HOST = 0
  462. def __init__(self, reactor, host, port, timeout=30, bindAddress=None):
  463. """
  464. @param host: An IPv6 address literal or a hostname with an
  465. IPv6 address
  466. @see: L{twisted.internet.interfaces.IReactorTCP.connectTCP}
  467. """
  468. self._reactor = reactor
  469. self._host = host
  470. self._port = port
  471. self._timeout = timeout
  472. self._bindAddress = bindAddress
  473. def connect(self, protocolFactory):
  474. """
  475. Implement L{IStreamClientEndpoint.connect} to connect via TCP,
  476. once the hostname resolution is done.
  477. """
  478. if isIPv6Address(self._host):
  479. d = self._resolvedHostConnect(self._host, protocolFactory)
  480. else:
  481. d = self._nameResolution(self._host)
  482. d.addCallback(lambda result: result[0][self._GAI_ADDRESS]
  483. [self._GAI_ADDRESS_HOST])
  484. d.addCallback(self._resolvedHostConnect, protocolFactory)
  485. return d
  486. def _nameResolution(self, host):
  487. """
  488. Resolve the hostname string into a tuple containing the host
  489. IPv6 address.
  490. """
  491. return self._deferToThread(
  492. self._getaddrinfo, host, 0, socket.AF_INET6)
  493. def _resolvedHostConnect(self, resolvedHost, protocolFactory):
  494. """
  495. Connect to the server using the resolved hostname.
  496. """
  497. try:
  498. wf = _WrappingFactory(protocolFactory)
  499. self._reactor.connectTCP(resolvedHost, self._port, wf,
  500. timeout=self._timeout, bindAddress=self._bindAddress)
  501. return wf._onConnection
  502. except:
  503. return defer.fail()
  504. @implementer(IHostnameResolver)
  505. class _SimpleHostnameResolver(object):
  506. """
  507. An L{IHostnameResolver} provider that invokes a provided callable
  508. to resolve hostnames.
  509. @ivar _nameResolution: the callable L{resolveHostName} invokes to
  510. resolve hostnames.
  511. @type _nameResolution: A L{callable} that accepts two arguments:
  512. the host to resolve and the port number to include in the
  513. result.
  514. """
  515. _log = Logger()
  516. def __init__(self, nameResolution):
  517. """
  518. Create a L{_SimpleHostnameResolver} instance.
  519. """
  520. self._nameResolution = nameResolution
  521. def resolveHostName(self, resolutionReceiver,
  522. hostName,
  523. portNumber=0,
  524. addressTypes=None,
  525. transportSemantics='TCP'):
  526. """
  527. Initiate a hostname resolution.
  528. @param resolutionReceiver: an object that will receive each resolved
  529. address as it arrives.
  530. @type resolutionReceiver: L{IResolutionReceiver}
  531. @param hostName: see interface
  532. @param portNumber: see interface
  533. @param addressTypes: Ignored in this implementation.
  534. @param transportSemantics: Ignored in this implementation.
  535. @return: The resolution in progress.
  536. @rtype: L{IResolutionReceiver}
  537. """
  538. resolutionReceiver.resolutionBegan(HostResolution(hostName))
  539. d = self._nameResolution(hostName, portNumber)
  540. def cbDeliver(gairesult):
  541. for family, socktype, proto, canonname, sockaddr in gairesult:
  542. if family == socket.AF_INET6:
  543. resolutionReceiver.addressResolved(
  544. IPv6Address('TCP', *sockaddr))
  545. elif family == socket.AF_INET:
  546. resolutionReceiver.addressResolved(
  547. IPv4Address('TCP', *sockaddr))
  548. def ebLog(error):
  549. self._log.failure("while looking up {name} with {callable}",
  550. error, name=hostName,
  551. callable=self._nameResolution)
  552. d.addCallback(cbDeliver)
  553. d.addErrback(ebLog)
  554. d.addBoth(lambda ignored: resolutionReceiver.resolutionComplete())
  555. return resolutionReceiver
  556. @implementer(interfaces.IStreamClientEndpoint)
  557. class HostnameEndpoint(object):
  558. """
  559. A name-based endpoint that connects to the fastest amongst the resolved
  560. host addresses.
  561. @cvar _DEFAULT_ATTEMPT_DELAY: The default time to use between attempts, in
  562. seconds, when no C{attemptDelay} is given to
  563. L{HostnameEndpoint.__init__}.
  564. @ivar _hostText: the textual representation of the hostname passed to the
  565. constructor. Used to pass to the reactor's hostname resolver.
  566. @type _hostText: L{unicode}
  567. @ivar _hostBytes: the encoded bytes-representation of the hostname passed
  568. to the constructor. Used to construct the L{HostnameAddress}
  569. associated with this endpoint.
  570. @type _hostBytes: L{bytes}
  571. @ivar _hostStr: the native-string representation of the hostname passed to
  572. the constructor, used for exception construction
  573. @type _hostStr: native L{str}
  574. @ivar _badHostname: a flag - hopefully false! - indicating that an invalid
  575. hostname was passed to the constructor. This might be a textual
  576. hostname that isn't valid IDNA, or non-ASCII bytes.
  577. @type _badHostname: L{bool}
  578. """
  579. _getaddrinfo = staticmethod(socket.getaddrinfo)
  580. _deferToThread = staticmethod(threads.deferToThread)
  581. _DEFAULT_ATTEMPT_DELAY = 0.3
  582. def __init__(self, reactor, host, port, timeout=30, bindAddress=None,
  583. attemptDelay=None):
  584. """
  585. Create a L{HostnameEndpoint}.
  586. @param reactor: The reactor to use for connections and delayed calls.
  587. @type reactor: provider of L{IReactorTCP}, L{IReactorTime} and either
  588. L{IReactorPluggableNameResolver} or L{IReactorPluggableResolver}.
  589. @param host: A hostname to connect to.
  590. @type host: L{bytes} or L{unicode}
  591. @param port: The port number to connect to.
  592. @type port: L{int}
  593. @param timeout: For each individual connection attempt, the number of
  594. seconds to wait before assuming the connection has failed.
  595. @type timeout: L{int}
  596. @param bindAddress: the local address of the network interface to make
  597. the connections from.
  598. @type bindAddress: L{bytes}
  599. @param attemptDelay: The number of seconds to delay between connection
  600. attempts.
  601. @type attemptDelay: L{float}
  602. @see: L{twisted.internet.interfaces.IReactorTCP.connectTCP}
  603. """
  604. self._reactor = reactor
  605. self._nameResolver = self._getNameResolverAndMaybeWarn(reactor)
  606. [self._badHostname, self._hostBytes, self._hostText] = (
  607. self._hostAsBytesAndText(host)
  608. )
  609. self._hostStr = self._hostBytes if bytes is str else self._hostText
  610. self._port = port
  611. self._timeout = timeout
  612. self._bindAddress = bindAddress
  613. if attemptDelay is None:
  614. attemptDelay = self._DEFAULT_ATTEMPT_DELAY
  615. self._attemptDelay = attemptDelay
  616. def _getNameResolverAndMaybeWarn(self, reactor):
  617. """
  618. Retrieve a C{nameResolver} callable and warn the caller's
  619. caller that using a reactor which doesn't provide
  620. L{IReactorPluggableNameResolver} is deprecated.
  621. @param reactor: The reactor to check.
  622. @return: A L{IHostnameResolver} provider.
  623. """
  624. if not IReactorPluggableNameResolver.providedBy(reactor):
  625. warningString = deprecate.getDeprecationWarningString(
  626. reactor.__class__,
  627. Version('Twisted', 17, 5, 0),
  628. format=("Passing HostnameEndpoint a reactor that does not"
  629. " provide IReactorPluggableNameResolver (%(fqpn)s)"
  630. " was deprecated in %(version)s"),
  631. replacement=("a reactor that provides"
  632. " IReactorPluggableNameResolver"),
  633. )
  634. warnings.warn(warningString, DeprecationWarning, stacklevel=3)
  635. return _SimpleHostnameResolver(self._fallbackNameResolution)
  636. return reactor.nameResolver
  637. @staticmethod
  638. def _hostAsBytesAndText(host):
  639. """
  640. For various reasons (documented in the C{@ivar}'s in the class
  641. docstring) we need both a textual and a binary representation of the
  642. hostname given to the constructor. For compatibility and convenience,
  643. we accept both textual and binary representations of the hostname, save
  644. the form that was passed, and convert into the other form. This is
  645. mostly just because L{HostnameAddress} chose somewhat poorly to define
  646. its attribute as bytes; hopefully we can find a compatible way to clean
  647. this up in the future and just operate in terms of text internally.
  648. @param host: A hostname to convert.
  649. @type host: L{bytes} or C{str}
  650. @return: a 3-tuple of C{(invalid, bytes, text)} where C{invalid} is a
  651. boolean indicating the validity of the hostname, C{bytes} is a
  652. binary representation of C{host}, and C{text} is a textual
  653. representation of C{host}.
  654. """
  655. if isinstance(host, bytes):
  656. if isIPAddress(host) or isIPv6Address(host):
  657. return False, host, host.decode("ascii")
  658. else:
  659. try:
  660. return False, host, _idnaText(host)
  661. except UnicodeError:
  662. # Convert the host to _some_ kind of text, to handle below.
  663. host = host.decode("charmap")
  664. else:
  665. host = normalize('NFC', host)
  666. if isIPAddress(host) or isIPv6Address(host):
  667. return False, host.encode("ascii"), host
  668. else:
  669. try:
  670. return False, _idnaBytes(host), host
  671. except UnicodeError:
  672. pass
  673. # `host` has been converted to text by this point either way; it's
  674. # invalid as a hostname, and so may contain unprintable characters and
  675. # such. escape it with backslashes so the user can get _some_ guess as
  676. # to what went wrong.
  677. asciibytes = host.encode('ascii', 'backslashreplace')
  678. return True, asciibytes, asciibytes.decode('ascii')
  679. def connect(self, protocolFactory):
  680. """
  681. Attempts a connection to each resolved address, and returns a
  682. connection which is established first.
  683. @param protocolFactory: The protocol factory whose protocol
  684. will be connected.
  685. @type protocolFactory:
  686. L{IProtocolFactory<twisted.internet.interfaces.IProtocolFactory>}
  687. @return: A L{Deferred} that fires with the connected protocol
  688. or fails a connection-related error.
  689. """
  690. if self._badHostname:
  691. return defer.fail(
  692. ValueError("invalid hostname: {}".format(self._hostStr))
  693. )
  694. d = Deferred()
  695. addresses = []
  696. @provider(IResolutionReceiver)
  697. class EndpointReceiver(object):
  698. @staticmethod
  699. def resolutionBegan(resolutionInProgress):
  700. pass
  701. @staticmethod
  702. def addressResolved(address):
  703. addresses.append(address)
  704. @staticmethod
  705. def resolutionComplete():
  706. d.callback(addresses)
  707. self._nameResolver.resolveHostName(
  708. EndpointReceiver, self._hostText, portNumber=self._port
  709. )
  710. d.addErrback(lambda ignored: defer.fail(error.DNSLookupError(
  711. "Couldn't find the hostname '{}'".format(self._hostStr))))
  712. @d.addCallback
  713. def resolvedAddressesToEndpoints(addresses):
  714. # Yield an endpoint for every address resolved from the name.
  715. for eachAddress in addresses:
  716. if isinstance(eachAddress, IPv6Address):
  717. yield TCP6ClientEndpoint(
  718. self._reactor, eachAddress.host, eachAddress.port,
  719. self._timeout, self._bindAddress
  720. )
  721. if isinstance(eachAddress, IPv4Address):
  722. yield TCP4ClientEndpoint(
  723. self._reactor, eachAddress.host, eachAddress.port,
  724. self._timeout, self._bindAddress
  725. )
  726. d.addCallback(list)
  727. def _canceller(d):
  728. # This canceller must remain defined outside of
  729. # `startConnectionAttempts`, because Deferred should not
  730. # participate in cycles with their cancellers; that would create a
  731. # potentially problematic circular reference and possibly
  732. # gc.garbage.
  733. d.errback(error.ConnectingCancelledError(
  734. HostnameAddress(self._hostBytes, self._port)))
  735. @d.addCallback
  736. def startConnectionAttempts(endpoints):
  737. """
  738. Given a sequence of endpoints obtained via name resolution, start
  739. connecting to a new one every C{self._attemptDelay} seconds until
  740. one of the connections succeeds, all of them fail, or the attempt
  741. is cancelled.
  742. @param endpoints: a list of all the endpoints we might try to
  743. connect to, as determined by name resolution.
  744. @type endpoints: L{list} of L{IStreamServerEndpoint}
  745. @return: a Deferred that fires with the result of the
  746. C{endpoint.connect} method that completes the fastest, or fails
  747. with the first connection error it encountered if none of them
  748. succeed.
  749. @rtype: L{Deferred} failing with L{error.ConnectingCancelledError}
  750. or firing with L{IProtocol}
  751. """
  752. if not endpoints:
  753. raise error.DNSLookupError(
  754. "no results for hostname lookup: {}".format(self._hostStr)
  755. )
  756. iterEndpoints = iter(endpoints)
  757. pending = []
  758. failures = []
  759. winner = defer.Deferred(canceller=_canceller)
  760. def checkDone():
  761. if pending or checkDone.completed or checkDone.endpointsLeft:
  762. return
  763. winner.errback(failures.pop())
  764. checkDone.completed = False
  765. checkDone.endpointsLeft = True
  766. @LoopingCall
  767. def iterateEndpoint():
  768. endpoint = next(iterEndpoints, None)
  769. if endpoint is None:
  770. # The list of endpoints ends.
  771. checkDone.endpointsLeft = False
  772. checkDone()
  773. return
  774. eachAttempt = endpoint.connect(protocolFactory)
  775. pending.append(eachAttempt)
  776. @eachAttempt.addBoth
  777. def noLongerPending(result):
  778. pending.remove(eachAttempt)
  779. return result
  780. @eachAttempt.addCallback
  781. def succeeded(result):
  782. winner.callback(result)
  783. @eachAttempt.addErrback
  784. def failed(reason):
  785. failures.append(reason)
  786. checkDone()
  787. iterateEndpoint.clock = self._reactor
  788. iterateEndpoint.start(self._attemptDelay)
  789. @winner.addBoth
  790. def cancelRemainingPending(result):
  791. checkDone.completed = True
  792. for remaining in pending[:]:
  793. remaining.cancel()
  794. if iterateEndpoint.running:
  795. iterateEndpoint.stop()
  796. return result
  797. return winner
  798. return d
  799. def _fallbackNameResolution(self, host, port):
  800. """
  801. Resolve the hostname string into a tuple containing the host
  802. address. This is method is only used when the reactor does
  803. not provide L{IReactorPluggableNameResolver}.
  804. @param host: A unicode hostname to resolve.
  805. @param port: The port to include in the resolution.
  806. @return: A L{Deferred} that fires with L{_getaddrinfo}'s
  807. return value.
  808. """
  809. return self._deferToThread(self._getaddrinfo, host, port, 0,
  810. socket.SOCK_STREAM)
  811. @implementer(interfaces.IStreamServerEndpoint)
  812. class SSL4ServerEndpoint(object):
  813. """
  814. SSL secured TCP server endpoint with an IPv4 configuration.
  815. """
  816. def __init__(self, reactor, port, sslContextFactory,
  817. backlog=50, interface=''):
  818. """
  819. @param reactor: An L{IReactorSSL} provider.
  820. @param port: The port number used for listening
  821. @type port: int
  822. @param sslContextFactory: An instance of
  823. L{interfaces.IOpenSSLContextFactory}.
  824. @param backlog: Size of the listen queue
  825. @type backlog: int
  826. @param interface: The hostname to bind to, defaults to '' (all)
  827. @type interface: str
  828. """
  829. self._reactor = reactor
  830. self._port = port
  831. self._sslContextFactory = sslContextFactory
  832. self._backlog = backlog
  833. self._interface = interface
  834. def listen(self, protocolFactory):
  835. """
  836. Implement L{IStreamServerEndpoint.listen} to listen for SSL on a
  837. TCP socket.
  838. """
  839. return defer.execute(self._reactor.listenSSL, self._port,
  840. protocolFactory,
  841. contextFactory=self._sslContextFactory,
  842. backlog=self._backlog,
  843. interface=self._interface)
  844. @implementer(interfaces.IStreamClientEndpoint)
  845. class SSL4ClientEndpoint(object):
  846. """
  847. SSL secured TCP client endpoint with an IPv4 configuration
  848. """
  849. def __init__(self, reactor, host, port, sslContextFactory,
  850. timeout=30, bindAddress=None):
  851. """
  852. @param reactor: An L{IReactorSSL} provider.
  853. @param host: A hostname, used when connecting
  854. @type host: str
  855. @param port: The port number, used when connecting
  856. @type port: int
  857. @param sslContextFactory: SSL Configuration information as an instance
  858. of L{interfaces.IOpenSSLContextFactory}.
  859. @param timeout: Number of seconds to wait before assuming the
  860. connection has failed.
  861. @type timeout: int
  862. @param bindAddress: A (host, port) tuple of local address to bind to,
  863. or None.
  864. @type bindAddress: tuple
  865. """
  866. self._reactor = reactor
  867. self._host = host
  868. self._port = port
  869. self._sslContextFactory = sslContextFactory
  870. self._timeout = timeout
  871. self._bindAddress = bindAddress
  872. def connect(self, protocolFactory):
  873. """
  874. Implement L{IStreamClientEndpoint.connect} to connect with SSL over
  875. TCP.
  876. """
  877. try:
  878. wf = _WrappingFactory(protocolFactory)
  879. self._reactor.connectSSL(
  880. self._host, self._port, wf, self._sslContextFactory,
  881. timeout=self._timeout, bindAddress=self._bindAddress)
  882. return wf._onConnection
  883. except:
  884. return defer.fail()
  885. @implementer(interfaces.IStreamServerEndpoint)
  886. class UNIXServerEndpoint(object):
  887. """
  888. UnixSocket server endpoint.
  889. """
  890. def __init__(self, reactor, address, backlog=50, mode=0o666, wantPID=0):
  891. """
  892. @param reactor: An L{IReactorUNIX} provider.
  893. @param address: The path to the Unix socket file, used when listening
  894. @param backlog: number of connections to allow in backlog.
  895. @param mode: mode to set on the unix socket. This parameter is
  896. deprecated. Permissions should be set on the directory which
  897. contains the UNIX socket.
  898. @param wantPID: If True, create a pidfile for the socket.
  899. """
  900. self._reactor = reactor
  901. self._address = address
  902. self._backlog = backlog
  903. self._mode = mode
  904. self._wantPID = wantPID
  905. def listen(self, protocolFactory):
  906. """
  907. Implement L{IStreamServerEndpoint.listen} to listen on a UNIX socket.
  908. """
  909. return defer.execute(self._reactor.listenUNIX, self._address,
  910. protocolFactory,
  911. backlog=self._backlog,
  912. mode=self._mode,
  913. wantPID=self._wantPID)
  914. @implementer(interfaces.IStreamClientEndpoint)
  915. class UNIXClientEndpoint(object):
  916. """
  917. UnixSocket client endpoint.
  918. """
  919. def __init__(self, reactor, path, timeout=30, checkPID=0):
  920. """
  921. @param reactor: An L{IReactorUNIX} provider.
  922. @param path: The path to the Unix socket file, used when connecting
  923. @type path: str
  924. @param timeout: Number of seconds to wait before assuming the
  925. connection has failed.
  926. @type timeout: int
  927. @param checkPID: If True, check for a pid file to verify that a server
  928. is listening.
  929. @type checkPID: bool
  930. """
  931. self._reactor = reactor
  932. self._path = path
  933. self._timeout = timeout
  934. self._checkPID = checkPID
  935. def connect(self, protocolFactory):
  936. """
  937. Implement L{IStreamClientEndpoint.connect} to connect via a
  938. UNIX Socket
  939. """
  940. try:
  941. wf = _WrappingFactory(protocolFactory)
  942. self._reactor.connectUNIX(
  943. self._path, wf,
  944. timeout=self._timeout,
  945. checkPID=self._checkPID)
  946. return wf._onConnection
  947. except:
  948. return defer.fail()
  949. @implementer(interfaces.IStreamServerEndpoint)
  950. class AdoptedStreamServerEndpoint(object):
  951. """
  952. An endpoint for listening on a file descriptor initialized outside of
  953. Twisted.
  954. @ivar _used: A C{bool} indicating whether this endpoint has been used to
  955. listen with a factory yet. C{True} if so.
  956. """
  957. _close = os.close
  958. _setNonBlocking = staticmethod(fdesc.setNonBlocking)
  959. def __init__(self, reactor, fileno, addressFamily):
  960. """
  961. @param reactor: An L{IReactorSocket} provider.
  962. @param fileno: An integer file descriptor corresponding to a listening
  963. I{SOCK_STREAM} socket.
  964. @param addressFamily: The address family of the socket given by
  965. C{fileno}.
  966. """
  967. self.reactor = reactor
  968. self.fileno = fileno
  969. self.addressFamily = addressFamily
  970. self._used = False
  971. def listen(self, factory):
  972. """
  973. Implement L{IStreamServerEndpoint.listen} to start listening on, and
  974. then close, C{self._fileno}.
  975. """
  976. if self._used:
  977. return defer.fail(error.AlreadyListened())
  978. self._used = True
  979. try:
  980. self._setNonBlocking(self.fileno)
  981. port = self.reactor.adoptStreamPort(
  982. self.fileno, self.addressFamily, factory)
  983. self._close(self.fileno)
  984. except:
  985. return defer.fail()
  986. return defer.succeed(port)
  987. def _parseTCP(factory, port, interface="", backlog=50):
  988. """
  989. Internal parser function for L{_parseServer} to convert the string
  990. arguments for a TCP(IPv4) stream endpoint into the structured arguments.
  991. @param factory: the protocol factory being parsed, or L{None}. (This was a
  992. leftover argument from when this code was in C{strports}, and is now
  993. mostly None and unused.)
  994. @type factory: L{IProtocolFactory} or L{None}
  995. @param port: the integer port number to bind
  996. @type port: C{str}
  997. @param interface: the interface IP to listen on
  998. @param backlog: the length of the listen queue
  999. @type backlog: C{str}
  1000. @return: a 2-tuple of (args, kwargs), describing the parameters to
  1001. L{IReactorTCP.listenTCP} (or, modulo argument 2, the factory, arguments
  1002. to L{TCP4ServerEndpoint}.
  1003. """
  1004. return (int(port), factory), {'interface': interface,
  1005. 'backlog': int(backlog)}
  1006. def _parseUNIX(factory, address, mode='666', backlog=50, lockfile=True):
  1007. """
  1008. Internal parser function for L{_parseServer} to convert the string
  1009. arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the
  1010. structured arguments.
  1011. @param factory: the protocol factory being parsed, or L{None}. (This was a
  1012. leftover argument from when this code was in C{strports}, and is now
  1013. mostly None and unused.)
  1014. @type factory: L{IProtocolFactory} or L{None}
  1015. @param address: the pathname of the unix socket
  1016. @type address: C{str}
  1017. @param backlog: the length of the listen queue
  1018. @type backlog: C{str}
  1019. @param lockfile: A string '0' or '1', mapping to True and False
  1020. respectively. See the C{wantPID} argument to C{listenUNIX}
  1021. @return: a 2-tuple of (args, kwargs), describing the parameters to
  1022. L{twisted.internet.interfaces.IReactorUNIX.listenUNIX} (or,
  1023. modulo argument 2, the factory, arguments to L{UNIXServerEndpoint}.
  1024. """
  1025. return (
  1026. (address, factory),
  1027. {'mode': int(mode, 8), 'backlog': int(backlog),
  1028. 'wantPID': bool(int(lockfile))})
  1029. def _parseSSL(factory, port, privateKey="server.pem", certKey=None,
  1030. sslmethod=None, interface='', backlog=50, extraCertChain=None,
  1031. dhParameters=None):
  1032. """
  1033. Internal parser function for L{_parseServer} to convert the string
  1034. arguments for an SSL (over TCP/IPv4) stream endpoint into the structured
  1035. arguments.
  1036. @param factory: the protocol factory being parsed, or L{None}. (This was a
  1037. leftover argument from when this code was in C{strports}, and is now
  1038. mostly None and unused.)
  1039. @type factory: L{IProtocolFactory} or L{None}
  1040. @param port: the integer port number to bind
  1041. @type port: C{str}
  1042. @param interface: the interface IP to listen on
  1043. @param backlog: the length of the listen queue
  1044. @type backlog: C{str}
  1045. @param privateKey: The file name of a PEM format private key file.
  1046. @type privateKey: C{str}
  1047. @param certKey: The file name of a PEM format certificate file.
  1048. @type certKey: C{str}
  1049. @param sslmethod: The string name of an SSL method, based on the name of a
  1050. constant in C{OpenSSL.SSL}. Must be one of: "SSLv23_METHOD",
  1051. "SSLv2_METHOD", "SSLv3_METHOD", "TLSv1_METHOD".
  1052. @type sslmethod: C{str}
  1053. @param extraCertChain: The path of a file containing one or more
  1054. certificates in PEM format that establish the chain from a root CA to
  1055. the CA that signed your C{certKey}.
  1056. @type extraCertChain: L{str}
  1057. @param dhParameters: The file name of a file containing parameters that are
  1058. required for Diffie-Hellman key exchange. If this is not specified,
  1059. the forward secret C{DHE} ciphers aren't available for servers.
  1060. @type dhParameters: L{str}
  1061. @return: a 2-tuple of (args, kwargs), describing the parameters to
  1062. L{IReactorSSL.listenSSL} (or, modulo argument 2, the factory, arguments
  1063. to L{SSL4ServerEndpoint}.
  1064. """
  1065. from twisted.internet import ssl
  1066. if certKey is None:
  1067. certKey = privateKey
  1068. kw = {}
  1069. if sslmethod is not None:
  1070. kw['method'] = getattr(ssl.SSL, sslmethod)
  1071. certPEM = FilePath(certKey).getContent()
  1072. keyPEM = FilePath(privateKey).getContent()
  1073. privateCertificate = ssl.PrivateCertificate.loadPEM(certPEM + keyPEM)
  1074. if extraCertChain is not None:
  1075. matches = re.findall(
  1076. r'(-----BEGIN CERTIFICATE-----\n.+?\n-----END CERTIFICATE-----)',
  1077. nativeString(FilePath(extraCertChain).getContent()),
  1078. flags=re.DOTALL
  1079. )
  1080. chainCertificates = [ssl.Certificate.loadPEM(chainCertPEM).original
  1081. for chainCertPEM in matches]
  1082. if not chainCertificates:
  1083. raise ValueError(
  1084. "Specified chain file '%s' doesn't contain any valid "
  1085. "certificates in PEM format." % (extraCertChain,)
  1086. )
  1087. else:
  1088. chainCertificates = None
  1089. if dhParameters is not None:
  1090. dhParameters = ssl.DiffieHellmanParameters.fromFile(
  1091. FilePath(dhParameters),
  1092. )
  1093. cf = ssl.CertificateOptions(
  1094. privateKey=privateCertificate.privateKey.original,
  1095. certificate=privateCertificate.original,
  1096. extraCertChain=chainCertificates,
  1097. dhParameters=dhParameters,
  1098. **kw
  1099. )
  1100. return ((int(port), factory, cf),
  1101. {'interface': interface, 'backlog': int(backlog)})
  1102. @implementer(IPlugin, IStreamServerEndpointStringParser)
  1103. class _StandardIOParser(object):
  1104. """
  1105. Stream server endpoint string parser for the Standard I/O type.
  1106. @ivar prefix: See L{IStreamServerEndpointStringParser.prefix}.
  1107. """
  1108. prefix = "stdio"
  1109. def _parseServer(self, reactor):
  1110. """
  1111. Internal parser function for L{_parseServer} to convert the string
  1112. arguments into structured arguments for the L{StandardIOEndpoint}
  1113. @param reactor: Reactor for the endpoint
  1114. """
  1115. return StandardIOEndpoint(reactor)
  1116. def parseStreamServer(self, reactor, *args, **kwargs):
  1117. # Redirects to another function (self._parseServer), tricks zope.interface
  1118. # into believing the interface is correctly implemented.
  1119. return self._parseServer(reactor)
  1120. @implementer(IPlugin, IStreamServerEndpointStringParser)
  1121. class _SystemdParser(object):
  1122. """
  1123. Stream server endpoint string parser for the I{systemd} endpoint type.
  1124. @ivar prefix: See L{IStreamServerEndpointStringParser.prefix}.
  1125. @ivar _sddaemon: A L{ListenFDs} instance used to translate an index into an
  1126. actual file descriptor.
  1127. """
  1128. _sddaemon = ListenFDs.fromEnvironment()
  1129. prefix = "systemd"
  1130. def _parseServer(self, reactor, domain, index):
  1131. """
  1132. Internal parser function for L{_parseServer} to convert the string
  1133. arguments for a systemd server endpoint into structured arguments for
  1134. L{AdoptedStreamServerEndpoint}.
  1135. @param reactor: An L{IReactorSocket} provider.
  1136. @param domain: The domain (or address family) of the socket inherited
  1137. from systemd. This is a string like C{"INET"} or C{"UNIX"}, ie the
  1138. name of an address family from the L{socket} module, without the
  1139. C{"AF_"} prefix.
  1140. @type domain: C{str}
  1141. @param index: An offset into the list of file descriptors inherited from
  1142. systemd.
  1143. @type index: C{str}
  1144. @return: A two-tuple of parsed positional arguments and parsed keyword
  1145. arguments (a tuple and a dictionary). These can be used to
  1146. construct an L{AdoptedStreamServerEndpoint}.
  1147. """
  1148. index = int(index)
  1149. fileno = self._sddaemon.inheritedDescriptors()[index]
  1150. addressFamily = getattr(socket, 'AF_' + domain)
  1151. return AdoptedStreamServerEndpoint(reactor, fileno, addressFamily)
  1152. def parseStreamServer(self, reactor, *args, **kwargs):
  1153. # Delegate to another function with a sane signature. This function has
  1154. # an insane signature to trick zope.interface into believing the
  1155. # interface is correctly implemented.
  1156. return self._parseServer(reactor, *args, **kwargs)
  1157. @implementer(IPlugin, IStreamServerEndpointStringParser)
  1158. class _TCP6ServerParser(object):
  1159. """
  1160. Stream server endpoint string parser for the TCP6ServerEndpoint type.
  1161. @ivar prefix: See L{IStreamServerEndpointStringParser.prefix}.
  1162. """
  1163. prefix = "tcp6" # Used in _parseServer to identify the plugin with the endpoint type
  1164. def _parseServer(self, reactor, port, backlog=50, interface='::'):
  1165. """
  1166. Internal parser function for L{_parseServer} to convert the string
  1167. arguments into structured arguments for the L{TCP6ServerEndpoint}
  1168. @param reactor: An L{IReactorTCP} provider.
  1169. @param port: The port number used for listening
  1170. @type port: int
  1171. @param backlog: Size of the listen queue
  1172. @type backlog: int
  1173. @param interface: The hostname to bind to
  1174. @type interface: str
  1175. """
  1176. port = int(port)
  1177. backlog = int(backlog)
  1178. return TCP6ServerEndpoint(reactor, port, backlog, interface)
  1179. def parseStreamServer(self, reactor, *args, **kwargs):
  1180. # Redirects to another function (self._parseServer), tricks zope.interface
  1181. # into believing the interface is correctly implemented.
  1182. return self._parseServer(reactor, *args, **kwargs)
  1183. _serverParsers = {"tcp": _parseTCP,
  1184. "unix": _parseUNIX,
  1185. "ssl": _parseSSL,
  1186. }
  1187. _OP, _STRING = range(2)
  1188. def _tokenize(description):
  1189. """
  1190. Tokenize a strports string and yield each token.
  1191. @param description: a string as described by L{serverFromString} or
  1192. L{clientFromString}.
  1193. @type description: L{str} or L{bytes}
  1194. @return: an iterable of 2-tuples of (C{_OP} or C{_STRING}, string). Tuples
  1195. starting with C{_OP} will contain a second element of either ':' (i.e.
  1196. 'next parameter') or '=' (i.e. 'assign parameter value'). For example,
  1197. the string 'hello:greeting=world' would result in a generator yielding
  1198. these values::
  1199. _STRING, 'hello'
  1200. _OP, ':'
  1201. _STRING, 'greet=ing'
  1202. _OP, '='
  1203. _STRING, 'world'
  1204. """
  1205. empty = _matchingString(u'', description)
  1206. colon = _matchingString(u':', description)
  1207. equals = _matchingString(u'=', description)
  1208. backslash = _matchingString(u'\x5c', description)
  1209. current = empty
  1210. ops = colon + equals
  1211. nextOps = {colon: colon + equals, equals: colon}
  1212. iterdesc = iter(iterbytes(description))
  1213. for n in iterdesc:
  1214. if n in iterbytes(ops):
  1215. yield _STRING, current
  1216. yield _OP, n
  1217. current = empty
  1218. ops = nextOps[n]
  1219. elif n == backslash:
  1220. current += next(iterdesc)
  1221. else:
  1222. current += n
  1223. yield _STRING, current
  1224. def _parse(description):
  1225. """
  1226. Convert a description string into a list of positional and keyword
  1227. parameters, using logic vaguely like what Python does.
  1228. @param description: a string as described by L{serverFromString} or
  1229. L{clientFromString}.
  1230. @return: a 2-tuple of C{(args, kwargs)}, where 'args' is a list of all
  1231. ':'-separated C{str}s not containing an '=' and 'kwargs' is a map of
  1232. all C{str}s which do contain an '='. For example, the result of
  1233. C{_parse('a:b:d=1:c')} would be C{(['a', 'b', 'c'], {'d': '1'})}.
  1234. """
  1235. args, kw = [], {}
  1236. colon = _matchingString(u':', description)
  1237. def add(sofar):
  1238. if len(sofar) == 1:
  1239. args.append(sofar[0])
  1240. else:
  1241. kw[nativeString(sofar[0])] = sofar[1]
  1242. sofar = ()
  1243. for (type, value) in _tokenize(description):
  1244. if type is _STRING:
  1245. sofar += (value,)
  1246. elif value == colon:
  1247. add(sofar)
  1248. sofar = ()
  1249. add(sofar)
  1250. return args, kw
  1251. # Mappings from description "names" to endpoint constructors.
  1252. _endpointServerFactories = {
  1253. 'TCP': TCP4ServerEndpoint,
  1254. 'SSL': SSL4ServerEndpoint,
  1255. 'UNIX': UNIXServerEndpoint,
  1256. }
  1257. _endpointClientFactories = {
  1258. 'TCP': TCP4ClientEndpoint,
  1259. 'SSL': SSL4ClientEndpoint,
  1260. 'UNIX': UNIXClientEndpoint,
  1261. }
  1262. def _parseServer(description, factory):
  1263. """
  1264. Parse a strports description into a 2-tuple of arguments and keyword
  1265. values.
  1266. @param description: A description in the format explained by
  1267. L{serverFromString}.
  1268. @type description: C{str}
  1269. @param factory: A 'factory' argument; this is left-over from
  1270. twisted.application.strports, it's not really used.
  1271. @type factory: L{IProtocolFactory} or L{None}
  1272. @return: a 3-tuple of (plugin or name, arguments, keyword arguments)
  1273. """
  1274. args, kw = _parse(description)
  1275. endpointType = args[0]
  1276. parser = _serverParsers.get(endpointType)
  1277. if parser is None:
  1278. # If the required parser is not found in _server, check if
  1279. # a plugin exists for the endpointType
  1280. plugin = _matchPluginToPrefix(
  1281. getPlugins(IStreamServerEndpointStringParser), endpointType
  1282. )
  1283. return (plugin, args[1:], kw)
  1284. return (endpointType.upper(),) + parser(factory, *args[1:], **kw)
  1285. def _matchPluginToPrefix(plugins, endpointType):
  1286. """
  1287. Match plugin to prefix.
  1288. """
  1289. endpointType = endpointType.lower()
  1290. for plugin in plugins:
  1291. if (_matchingString(plugin.prefix.lower(),
  1292. endpointType) == endpointType):
  1293. return plugin
  1294. raise ValueError("Unknown endpoint type: '%s'" % (endpointType,))
  1295. def serverFromString(reactor, description):
  1296. """
  1297. Construct a stream server endpoint from an endpoint description string.
  1298. The format for server endpoint descriptions is a simple byte string. It is
  1299. a prefix naming the type of endpoint, then a colon, then the arguments for
  1300. that endpoint.
  1301. For example, you can call it like this to create an endpoint that will
  1302. listen on TCP port 80::
  1303. serverFromString(reactor, "tcp:80")
  1304. Additional arguments may be specified as keywords, separated with colons.
  1305. For example, you can specify the interface for a TCP server endpoint to
  1306. bind to like this::
  1307. serverFromString(reactor, "tcp:80:interface=127.0.0.1")
  1308. SSL server endpoints may be specified with the 'ssl' prefix, and the
  1309. private key and certificate files may be specified by the C{privateKey} and
  1310. C{certKey} arguments::
  1311. serverFromString(
  1312. reactor, "ssl:443:privateKey=key.pem:certKey=crt.pem")
  1313. If a private key file name (C{privateKey}) isn't provided, a "server.pem"
  1314. file is assumed to exist which contains the private key. If the certificate
  1315. file name (C{certKey}) isn't provided, the private key file is assumed to
  1316. contain the certificate as well.
  1317. You may escape colons in arguments with a backslash, which you will need to
  1318. use if you want to specify a full pathname argument on Windows::
  1319. serverFromString(reactor,
  1320. "ssl:443:privateKey=C\\:/key.pem:certKey=C\\:/cert.pem")
  1321. finally, the 'unix' prefix may be used to specify a filesystem UNIX socket,
  1322. optionally with a 'mode' argument to specify the mode of the socket file
  1323. created by C{listen}::
  1324. serverFromString(reactor, "unix:/var/run/finger")
  1325. serverFromString(reactor, "unix:/var/run/finger:mode=660")
  1326. This function is also extensible; new endpoint types may be registered as
  1327. L{IStreamServerEndpointStringParser} plugins. See that interface for more
  1328. information.
  1329. @param reactor: The server endpoint will be constructed with this reactor.
  1330. @param description: The strports description to parse.
  1331. @type description: L{str}
  1332. @return: A new endpoint which can be used to listen with the parameters
  1333. given by C{description}.
  1334. @rtype: L{IStreamServerEndpoint<twisted.internet.interfaces.IStreamServerEndpoint>}
  1335. @raise ValueError: when the 'description' string cannot be parsed.
  1336. @since: 10.2
  1337. """
  1338. nameOrPlugin, args, kw = _parseServer(description, None)
  1339. if type(nameOrPlugin) is not str:
  1340. plugin = nameOrPlugin
  1341. return plugin.parseStreamServer(reactor, *args, **kw)
  1342. else:
  1343. name = nameOrPlugin
  1344. # Chop out the factory.
  1345. args = args[:1] + args[2:]
  1346. return _endpointServerFactories[name](reactor, *args, **kw)
  1347. def quoteStringArgument(argument):
  1348. """
  1349. Quote an argument to L{serverFromString} and L{clientFromString}. Since
  1350. arguments are separated with colons and colons are escaped with
  1351. backslashes, some care is necessary if, for example, you have a pathname,
  1352. you may be tempted to interpolate into a string like this::
  1353. serverFromString(reactor, "ssl:443:privateKey=%s" % (myPathName,))
  1354. This may appear to work, but will have portability issues (Windows
  1355. pathnames, for example). Usually you should just construct the appropriate
  1356. endpoint type rather than interpolating strings, which in this case would
  1357. be L{SSL4ServerEndpoint}. There are some use-cases where you may need to
  1358. generate such a string, though; for example, a tool to manipulate a
  1359. configuration file which has strports descriptions in it. To be correct in
  1360. those cases, do this instead::
  1361. serverFromString(reactor, "ssl:443:privateKey=%s" %
  1362. (quoteStringArgument(myPathName),))
  1363. @param argument: The part of the endpoint description string you want to
  1364. pass through.
  1365. @type argument: C{str}
  1366. @return: The quoted argument.
  1367. @rtype: C{str}
  1368. """
  1369. backslash, colon = '\\:'
  1370. for c in backslash, colon:
  1371. argument = argument.replace(c, backslash + c)
  1372. return argument
  1373. def _parseClientTCP(*args, **kwargs):
  1374. """
  1375. Perform any argument value coercion necessary for TCP client parameters.
  1376. Valid positional arguments to this function are host and port.
  1377. Valid keyword arguments to this function are all L{IReactorTCP.connectTCP}
  1378. arguments.
  1379. @return: The coerced values as a C{dict}.
  1380. """
  1381. if len(args) == 2:
  1382. kwargs['port'] = int(args[1])
  1383. kwargs['host'] = args[0]
  1384. elif len(args) == 1:
  1385. if 'host' in kwargs:
  1386. kwargs['port'] = int(args[0])
  1387. else:
  1388. kwargs['host'] = args[0]
  1389. try:
  1390. kwargs['port'] = int(kwargs['port'])
  1391. except KeyError:
  1392. pass
  1393. try:
  1394. kwargs['timeout'] = int(kwargs['timeout'])
  1395. except KeyError:
  1396. pass
  1397. try:
  1398. kwargs['bindAddress'] = (kwargs['bindAddress'], 0)
  1399. except KeyError:
  1400. pass
  1401. return kwargs
  1402. def _loadCAsFromDir(directoryPath):
  1403. """
  1404. Load certificate-authority certificate objects in a given directory.
  1405. @param directoryPath: a L{unicode} or L{bytes} pointing at a directory to
  1406. load .pem files from, or L{None}.
  1407. @return: an L{IOpenSSLTrustRoot} provider.
  1408. """
  1409. caCerts = {}
  1410. for child in directoryPath.children():
  1411. if not child.asTextMode().basename().split(u'.')[-1].lower() == u'pem':
  1412. continue
  1413. try:
  1414. data = child.getContent()
  1415. except IOError:
  1416. # Permission denied, corrupt disk, we don't care.
  1417. continue
  1418. try:
  1419. theCert = Certificate.loadPEM(data)
  1420. except SSLError:
  1421. # Duplicate certificate, invalid certificate, etc. We don't care.
  1422. pass
  1423. else:
  1424. caCerts[theCert.digest()] = theCert
  1425. return trustRootFromCertificates(caCerts.values())
  1426. def _parseTrustRootPath(pathName):
  1427. """
  1428. Parse a string referring to a directory full of certificate authorities
  1429. into a trust root.
  1430. @param pathName: path name
  1431. @type pathName: L{unicode} or L{bytes} or L{None}
  1432. @return: L{None} or L{IOpenSSLTrustRoot}
  1433. """
  1434. if pathName is None:
  1435. return None
  1436. return _loadCAsFromDir(FilePath(pathName))
  1437. def _privateCertFromPaths(certificatePath, keyPath):
  1438. """
  1439. Parse a certificate path and key path, either or both of which might be
  1440. L{None}, into a certificate object.
  1441. @param certificatePath: the certificate path
  1442. @type certificatePath: L{bytes} or L{unicode} or L{None}
  1443. @param keyPath: the private key path
  1444. @type keyPath: L{bytes} or L{unicode} or L{None}
  1445. @return: a L{PrivateCertificate} or L{None}
  1446. """
  1447. if certificatePath is None:
  1448. return None
  1449. certBytes = FilePath(certificatePath).getContent()
  1450. if keyPath is None:
  1451. return PrivateCertificate.loadPEM(certBytes)
  1452. else:
  1453. return PrivateCertificate.fromCertificateAndKeyPair(
  1454. Certificate.loadPEM(certBytes),
  1455. KeyPair.load(FilePath(keyPath).getContent(), 1)
  1456. )
  1457. def _parseClientSSLOptions(kwargs):
  1458. """
  1459. Parse common arguments for SSL endpoints, creating an L{CertificateOptions}
  1460. instance.
  1461. @param kwargs: A dict of keyword arguments to be parsed, potentially
  1462. containing keys C{certKey}, C{privateKey}, C{caCertsDir}, and
  1463. C{hostname}. See L{_parseClientSSL}.
  1464. @type kwargs: L{dict}
  1465. @return: The remaining arguments, including a new key C{sslContextFactory}.
  1466. """
  1467. hostname = kwargs.pop('hostname', None)
  1468. clientCertificate = _privateCertFromPaths(kwargs.pop('certKey', None),
  1469. kwargs.pop('privateKey', None))
  1470. trustRoot = _parseTrustRootPath(kwargs.pop('caCertsDir', None))
  1471. if hostname is not None:
  1472. configuration = optionsForClientTLS(
  1473. _idnaText(hostname), trustRoot=trustRoot,
  1474. clientCertificate=clientCertificate
  1475. )
  1476. else:
  1477. # _really_ though, you should specify a hostname.
  1478. if clientCertificate is not None:
  1479. privateKeyOpenSSL = clientCertificate.privateKey.original
  1480. certificateOpenSSL = clientCertificate.original
  1481. else:
  1482. privateKeyOpenSSL = None
  1483. certificateOpenSSL = None
  1484. configuration = CertificateOptions(
  1485. trustRoot=trustRoot,
  1486. privateKey=privateKeyOpenSSL,
  1487. certificate=certificateOpenSSL,
  1488. )
  1489. kwargs['sslContextFactory'] = configuration
  1490. return kwargs
  1491. def _parseClientSSL(*args, **kwargs):
  1492. """
  1493. Perform any argument value coercion necessary for SSL client parameters.
  1494. Valid keyword arguments to this function are all L{IReactorSSL.connectSSL}
  1495. arguments except for C{contextFactory}. Instead, C{certKey} (the path name
  1496. of the certificate file) C{privateKey} (the path name of the private key
  1497. associated with the certificate) are accepted and used to construct a
  1498. context factory.
  1499. Valid positional arguments to this function are host and port.
  1500. @param caCertsDir: The one parameter which is not part of
  1501. L{IReactorSSL.connectSSL}'s signature, this is a path name used to
  1502. construct a list of certificate authority certificates. The directory
  1503. will be scanned for files ending in C{.pem}, all of which will be
  1504. considered valid certificate authorities for this connection.
  1505. @type caCertsDir: L{str}
  1506. @param hostname: The hostname to use for validating the server's
  1507. certificate.
  1508. @type hostname: L{unicode}
  1509. @return: The coerced values as a L{dict}.
  1510. """
  1511. kwargs = _parseClientTCP(*args, **kwargs)
  1512. return _parseClientSSLOptions(kwargs)
  1513. def _parseClientUNIX(*args, **kwargs):
  1514. """
  1515. Perform any argument value coercion necessary for UNIX client parameters.
  1516. Valid keyword arguments to this function are all L{IReactorUNIX.connectUNIX}
  1517. keyword arguments except for C{checkPID}. Instead, C{lockfile} is accepted
  1518. and has the same meaning. Also C{path} is used instead of C{address}.
  1519. Valid positional arguments to this function are C{path}.
  1520. @return: The coerced values as a C{dict}.
  1521. """
  1522. if len(args) == 1:
  1523. kwargs['path'] = args[0]
  1524. try:
  1525. kwargs['checkPID'] = bool(int(kwargs.pop('lockfile')))
  1526. except KeyError:
  1527. pass
  1528. try:
  1529. kwargs['timeout'] = int(kwargs['timeout'])
  1530. except KeyError:
  1531. pass
  1532. return kwargs
  1533. _clientParsers = {
  1534. 'TCP': _parseClientTCP,
  1535. 'SSL': _parseClientSSL,
  1536. 'UNIX': _parseClientUNIX,
  1537. }
  1538. def clientFromString(reactor, description):
  1539. """
  1540. Construct a client endpoint from a description string.
  1541. Client description strings are much like server description strings,
  1542. although they take all of their arguments as keywords, aside from host and
  1543. port.
  1544. You can create a TCP client endpoint with the 'host' and 'port' arguments,
  1545. like so::
  1546. clientFromString(reactor, "tcp:host=www.example.com:port=80")
  1547. or, without specifying host and port keywords::
  1548. clientFromString(reactor, "tcp:www.example.com:80")
  1549. Or you can specify only one or the other, as in the following 2 examples::
  1550. clientFromString(reactor, "tcp:host=www.example.com:80")
  1551. clientFromString(reactor, "tcp:www.example.com:port=80")
  1552. or an SSL client endpoint with those arguments, plus the arguments used by
  1553. the server SSL, for a client certificate::
  1554. clientFromString(reactor, "ssl:web.example.com:443:"
  1555. "privateKey=foo.pem:certKey=foo.pem")
  1556. to specify your certificate trust roots, you can identify a directory with
  1557. PEM files in it with the C{caCertsDir} argument::
  1558. clientFromString(reactor, "ssl:host=web.example.com:port=443:"
  1559. "caCertsDir=/etc/ssl/certs")
  1560. Both TCP and SSL client endpoint description strings can include a
  1561. 'bindAddress' keyword argument, whose value should be a local IPv4
  1562. address. This fixes the client socket to that IP address::
  1563. clientFromString(reactor, "tcp:www.example.com:80:"
  1564. "bindAddress=192.0.2.100")
  1565. NB: Fixed client ports are not currently supported in TCP or SSL
  1566. client endpoints. The client socket will always use an ephemeral
  1567. port assigned by the operating system
  1568. You can create a UNIX client endpoint with the 'path' argument and optional
  1569. 'lockfile' and 'timeout' arguments::
  1570. clientFromString(
  1571. reactor, b"unix:path=/var/foo/bar:lockfile=1:timeout=9")
  1572. or, with the path as a positional argument with or without optional
  1573. arguments as in the following 2 examples::
  1574. clientFromString(reactor, "unix:/var/foo/bar")
  1575. clientFromString(reactor, "unix:/var/foo/bar:lockfile=1:timeout=9")
  1576. This function is also extensible; new endpoint types may be registered as
  1577. L{IStreamClientEndpointStringParserWithReactor} plugins. See that
  1578. interface for more information.
  1579. @param reactor: The client endpoint will be constructed with this reactor.
  1580. @param description: The strports description to parse.
  1581. @type description: L{str}
  1582. @return: A new endpoint which can be used to connect with the parameters
  1583. given by C{description}.
  1584. @rtype: L{IStreamClientEndpoint<twisted.internet.interfaces.IStreamClientEndpoint>}
  1585. @since: 10.2
  1586. """
  1587. args, kwargs = _parse(description)
  1588. aname = args.pop(0)
  1589. name = aname.upper()
  1590. if name not in _clientParsers:
  1591. plugin = _matchPluginToPrefix(
  1592. getPlugins(IStreamClientEndpointStringParserWithReactor), name
  1593. )
  1594. return plugin.parseStreamClient(reactor, *args, **kwargs)
  1595. kwargs = _clientParsers[name](*args, **kwargs)
  1596. return _endpointClientFactories[name](reactor, **kwargs)
  1597. def connectProtocol(endpoint, protocol):
  1598. """
  1599. Connect a protocol instance to an endpoint.
  1600. This allows using a client endpoint without having to create a factory.
  1601. @param endpoint: A client endpoint to connect to.
  1602. @param protocol: A protocol instance.
  1603. @return: The result of calling C{connect} on the endpoint, i.e. a
  1604. L{Deferred} that will fire with the protocol when connected, or an
  1605. appropriate error.
  1606. @since: 13.1
  1607. """
  1608. class OneShotFactory(Factory):
  1609. def buildProtocol(self, addr):
  1610. return protocol
  1611. return endpoint.connect(OneShotFactory())
  1612. @implementer(interfaces.IStreamClientEndpoint)
  1613. class _WrapperEndpoint(object):
  1614. """
  1615. An endpoint that wraps another endpoint.
  1616. """
  1617. def __init__(self, wrappedEndpoint, wrapperFactory):
  1618. """
  1619. Construct a L{_WrapperEndpoint}.
  1620. """
  1621. self._wrappedEndpoint = wrappedEndpoint
  1622. self._wrapperFactory = wrapperFactory
  1623. def connect(self, protocolFactory):
  1624. """
  1625. Connect the given protocol factory and unwrap its result.
  1626. """
  1627. return self._wrappedEndpoint.connect(
  1628. self._wrapperFactory(protocolFactory)
  1629. ).addCallback(lambda protocol: protocol.wrappedProtocol)
  1630. @implementer(interfaces.IStreamServerEndpoint)
  1631. class _WrapperServerEndpoint(object):
  1632. """
  1633. A server endpoint that wraps another server endpoint.
  1634. """
  1635. def __init__(self, wrappedEndpoint, wrapperFactory):
  1636. """
  1637. Construct a L{_WrapperServerEndpoint}.
  1638. """
  1639. self._wrappedEndpoint = wrappedEndpoint
  1640. self._wrapperFactory = wrapperFactory
  1641. def listen(self, protocolFactory):
  1642. """
  1643. Connect the given protocol factory and unwrap its result.
  1644. """
  1645. return self._wrappedEndpoint.listen(
  1646. self._wrapperFactory(protocolFactory)
  1647. )
  1648. def wrapClientTLS(connectionCreator, wrappedEndpoint):
  1649. """
  1650. Wrap an endpoint which upgrades to TLS as soon as the connection is
  1651. established.
  1652. @since: 16.0
  1653. @param connectionCreator: The TLS options to use when connecting; see
  1654. L{twisted.internet.ssl.optionsForClientTLS} for how to construct this.
  1655. @type connectionCreator:
  1656. L{twisted.internet.interfaces.IOpenSSLClientConnectionCreator}
  1657. @param wrappedEndpoint: The endpoint to wrap.
  1658. @type wrappedEndpoint: An L{IStreamClientEndpoint} provider.
  1659. @return: an endpoint that provides transport level encryption layered on
  1660. top of C{wrappedEndpoint}
  1661. @rtype: L{twisted.internet.interfaces.IStreamClientEndpoint}
  1662. """
  1663. if TLSMemoryBIOFactory is None:
  1664. raise NotImplementedError(
  1665. "OpenSSL not available. Try `pip install twisted[tls]`."
  1666. )
  1667. return _WrapperEndpoint(
  1668. wrappedEndpoint,
  1669. lambda protocolFactory:
  1670. TLSMemoryBIOFactory(connectionCreator, True, protocolFactory)
  1671. )
  1672. def _parseClientTLS(reactor, host, port, timeout=b'30', bindAddress=None,
  1673. certificate=None, privateKey=None, trustRoots=None,
  1674. endpoint=None, **kwargs):
  1675. """
  1676. Internal method to construct an endpoint from string parameters.
  1677. @param reactor: The reactor passed to L{clientFromString}.
  1678. @param host: The hostname to connect to.
  1679. @type host: L{bytes} or L{unicode}
  1680. @param port: The port to connect to.
  1681. @type port: L{bytes} or L{unicode}
  1682. @param timeout: For each individual connection attempt, the number of
  1683. seconds to wait before assuming the connection has failed.
  1684. @type timeout: L{bytes} or L{unicode}
  1685. @param bindAddress: The address to which to bind outgoing connections.
  1686. @type bindAddress: L{bytes} or L{unicode}
  1687. @param certificate: a string representing a filesystem path to a
  1688. PEM-encoded certificate.
  1689. @type certificate: L{bytes} or L{unicode}
  1690. @param privateKey: a string representing a filesystem path to a PEM-encoded
  1691. certificate.
  1692. @type privateKey: L{bytes} or L{unicode}
  1693. @param endpoint: an optional string endpoint description of an endpoint to
  1694. wrap; if this is passed then C{host} is used only for certificate
  1695. verification.
  1696. @type endpoint: L{bytes} or L{unicode}
  1697. @return: a client TLS endpoint
  1698. @rtype: L{IStreamClientEndpoint}
  1699. """
  1700. if kwargs:
  1701. raise TypeError('unrecognized keyword arguments present',
  1702. list(kwargs.keys()))
  1703. host = host if isinstance(host, unicode) else host.decode("utf-8")
  1704. bindAddress = (bindAddress
  1705. if isinstance(bindAddress, unicode) or bindAddress is None
  1706. else bindAddress.decode("utf-8"))
  1707. port = int(port)
  1708. timeout = int(timeout)
  1709. return wrapClientTLS(
  1710. optionsForClientTLS(
  1711. host, trustRoot=_parseTrustRootPath(trustRoots),
  1712. clientCertificate=_privateCertFromPaths(certificate,
  1713. privateKey)),
  1714. clientFromString(reactor, endpoint) if endpoint is not None
  1715. else HostnameEndpoint(reactor, _idnaBytes(host), port, timeout,
  1716. bindAddress)
  1717. )
  1718. @implementer(IPlugin, IStreamClientEndpointStringParserWithReactor)
  1719. class _TLSClientEndpointParser(object):
  1720. """
  1721. Stream client endpoint string parser for L{wrapClientTLS} with
  1722. L{HostnameEndpoint}.
  1723. @ivar prefix: See
  1724. L{IStreamClientEndpointStringParserWithReactor.prefix}.
  1725. """
  1726. prefix = 'tls'
  1727. @staticmethod
  1728. def parseStreamClient(reactor, *args, **kwargs):
  1729. """
  1730. Redirects to another function L{_parseClientTLS}; tricks zope.interface
  1731. into believing the interface is correctly implemented, since the
  1732. signature is (C{reactor}, C{*args}, C{**kwargs}). See
  1733. L{_parseClientTLS} for the specific signature description for this
  1734. endpoint parser.
  1735. @param reactor: The reactor passed to L{clientFromString}.
  1736. @param args: The positional arguments in the endpoint description.
  1737. @type args: L{tuple}
  1738. @param kwargs: The named arguments in the endpoint description.
  1739. @type kwargs: L{dict}
  1740. @return: a client TLS endpoint
  1741. @rtype: L{IStreamClientEndpoint}
  1742. """
  1743. return _parseClientTLS(reactor, *args, **kwargs)