endpoints.py 77 KB

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