endpoints.py 76 KB

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