interfaces.py 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Interface documentation.
  5. Maintainer: Itamar Shtull-Trauring
  6. """
  7. from __future__ import annotations
  8. from typing import (
  9. TYPE_CHECKING,
  10. Any,
  11. AnyStr,
  12. Callable,
  13. Iterable,
  14. List,
  15. Mapping,
  16. Optional,
  17. Sequence,
  18. Tuple,
  19. Type,
  20. Union,
  21. )
  22. from zope.interface import Attribute, Interface
  23. from twisted.python.failure import Failure
  24. if TYPE_CHECKING:
  25. from socket import AddressFamily
  26. try:
  27. from OpenSSL.SSL import (
  28. Connection as OpenSSLConnection,
  29. Context as OpenSSLContext,
  30. )
  31. except ImportError:
  32. OpenSSLConnection = OpenSSLContext = object # type: ignore[misc,assignment]
  33. from twisted.internet.abstract import FileDescriptor
  34. from twisted.internet.address import IPv4Address, IPv6Address, UNIXAddress
  35. from twisted.internet.defer import Deferred
  36. from twisted.internet.protocol import (
  37. ClientFactory,
  38. ConnectedDatagramProtocol,
  39. DatagramProtocol,
  40. Factory,
  41. ServerFactory,
  42. )
  43. from twisted.internet.ssl import ClientContextFactory
  44. from twisted.names.dns import Query, RRHeader
  45. from twisted.protocols.tls import TLSMemoryBIOProtocol
  46. from twisted.python.runtime import platform
  47. if platform.supportsThreads():
  48. from twisted.python.threadpool import ThreadPool
  49. else:
  50. ThreadPool = object # type: ignore[misc, assignment]
  51. class IAddress(Interface):
  52. """
  53. An address, e.g. a TCP C{(host, port)}.
  54. Default implementations are in L{twisted.internet.address}.
  55. """
  56. ### Reactor Interfaces
  57. class IConnector(Interface):
  58. """
  59. Object used to interface between connections and protocols.
  60. Each L{IConnector} manages one connection.
  61. """
  62. def stopConnecting() -> None:
  63. """
  64. Stop attempting to connect.
  65. """
  66. def disconnect() -> None:
  67. """
  68. Disconnect regardless of the connection state.
  69. If we are connected, disconnect, if we are trying to connect,
  70. stop trying.
  71. """
  72. def connect() -> None:
  73. """
  74. Try to connect to remote address.
  75. """
  76. def getDestination() -> IAddress:
  77. """
  78. Return destination this will try to connect to.
  79. @return: An object which provides L{IAddress}.
  80. """
  81. class IResolverSimple(Interface):
  82. def getHostByName(name: str, timeout: Sequence[int] = ()) -> "Deferred[str]":
  83. """
  84. Resolve the domain name C{name} into an IP address.
  85. @param name: DNS name to resolve.
  86. @param timeout: Number of seconds after which to reissue the query.
  87. When the last timeout expires, the query is considered failed.
  88. @return: The callback of the Deferred that is returned will be
  89. passed a string that represents the IP address of the
  90. specified name, or the errback will be called if the
  91. lookup times out. If multiple types of address records
  92. are associated with the name, A6 records will be returned
  93. in preference to AAAA records, which will be returned in
  94. preference to A records. If there are multiple records of
  95. the type to be returned, one will be selected at random.
  96. @raise twisted.internet.defer.TimeoutError: Raised
  97. (asynchronously) if the name cannot be resolved within the
  98. specified timeout period.
  99. """
  100. class IHostResolution(Interface):
  101. """
  102. An L{IHostResolution} represents represents an in-progress recursive query
  103. for a DNS name.
  104. @since: Twisted 17.1.0
  105. """
  106. name = Attribute(
  107. """
  108. L{unicode}; the name of the host being resolved.
  109. """
  110. )
  111. def cancel() -> None:
  112. """
  113. Stop the hostname resolution in progress.
  114. """
  115. class IResolutionReceiver(Interface):
  116. """
  117. An L{IResolutionReceiver} receives the results of a hostname resolution in
  118. progress, initiated by an L{IHostnameResolver}.
  119. @since: Twisted 17.1.0
  120. """
  121. def resolutionBegan(resolutionInProgress: IHostResolution) -> None:
  122. """
  123. A hostname resolution began.
  124. @param resolutionInProgress: an L{IHostResolution}.
  125. """
  126. def addressResolved(address: IAddress) -> None:
  127. """
  128. An internet address. This is called when an address for the given name
  129. is discovered. In the current implementation this practically means
  130. L{IPv4Address} or L{IPv6Address}, but implementations of this interface
  131. should be lenient to other types being passed to this interface as
  132. well, for future-proofing.
  133. @param address: An address object.
  134. """
  135. def resolutionComplete() -> None:
  136. """
  137. Resolution has completed; no further addresses will be relayed to
  138. L{IResolutionReceiver.addressResolved}.
  139. """
  140. class IHostnameResolver(Interface):
  141. """
  142. An L{IHostnameResolver} can resolve a host name and port number into a
  143. series of L{IAddress} objects.
  144. @since: Twisted 17.1.0
  145. """
  146. def resolveHostName(
  147. resolutionReceiver: IResolutionReceiver,
  148. hostName: str,
  149. portNumber: int = 0,
  150. addressTypes: Optional[Sequence[Type[IAddress]]] = None,
  151. transportSemantics: str = "TCP",
  152. ) -> IHostResolution:
  153. """
  154. Initiate a hostname resolution.
  155. @param resolutionReceiver: an object that will receive each resolved
  156. address as it arrives.
  157. @param hostName: The name of the host to resolve. If this contains
  158. non-ASCII code points, they will be converted to IDNA first.
  159. @param portNumber: The port number that the returned addresses should
  160. include.
  161. @param addressTypes: An iterable of implementors of L{IAddress} that
  162. are acceptable values for C{resolutionReceiver} to receive to its
  163. L{addressResolved <IResolutionReceiver.addressResolved>}. In
  164. practice, this means an iterable containing
  165. L{twisted.internet.address.IPv4Address},
  166. L{twisted.internet.address.IPv6Address}, both, or neither.
  167. @param transportSemantics: A string describing the semantics of the
  168. transport; either C{'TCP'} for stream-oriented transports or
  169. C{'UDP'} for datagram-oriented; see
  170. L{twisted.internet.address.IPv6Address.type} and
  171. L{twisted.internet.address.IPv4Address.type}.
  172. @return: The resolution in progress.
  173. """
  174. class IResolver(IResolverSimple):
  175. def query(
  176. query: "Query", timeout: Sequence[int]
  177. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  178. """
  179. Dispatch C{query} to the method which can handle its type.
  180. @param query: The DNS query being issued, to which a response is to be
  181. generated.
  182. @param timeout: Number of seconds after which to reissue the query.
  183. When the last timeout expires, the query is considered failed.
  184. @return: A L{Deferred} which fires with a three-tuple of lists of
  185. L{twisted.names.dns.RRHeader} instances. The first element of the
  186. tuple gives answers. The second element of the tuple gives
  187. authorities. The third element of the tuple gives additional
  188. information. The L{Deferred} may instead fail with one of the
  189. exceptions defined in L{twisted.names.error} or with
  190. C{NotImplementedError}.
  191. """
  192. def lookupAddress(
  193. name: str, timeout: Sequence[int]
  194. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  195. """
  196. Perform an A record lookup.
  197. @param name: DNS name to resolve.
  198. @param timeout: Number of seconds after which to reissue the query.
  199. When the last timeout expires, the query is considered failed.
  200. @return: A L{Deferred} which fires with a three-tuple of lists of
  201. L{twisted.names.dns.RRHeader} instances. The first element of the
  202. tuple gives answers. The second element of the tuple gives
  203. authorities. The third element of the tuple gives additional
  204. information. The L{Deferred} may instead fail with one of the
  205. exceptions defined in L{twisted.names.error} or with
  206. C{NotImplementedError}.
  207. """
  208. def lookupAddress6(
  209. name: str, timeout: Sequence[int]
  210. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  211. """
  212. Perform an A6 record lookup.
  213. @param name: DNS name to resolve.
  214. @param timeout: Number of seconds after which to reissue the query.
  215. When the last timeout expires, the query is considered failed.
  216. @return: A L{Deferred} which fires with a three-tuple of lists of
  217. L{twisted.names.dns.RRHeader} instances. The first element of the
  218. tuple gives answers. The second element of the tuple gives
  219. authorities. The third element of the tuple gives additional
  220. information. The L{Deferred} may instead fail with one of the
  221. exceptions defined in L{twisted.names.error} or with
  222. C{NotImplementedError}.
  223. """
  224. def lookupIPV6Address(
  225. name: str, timeout: Sequence[int]
  226. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  227. """
  228. Perform an AAAA record lookup.
  229. @param name: DNS name to resolve.
  230. @param timeout: Number of seconds after which to reissue the query.
  231. When the last timeout expires, the query is considered failed.
  232. @return: A L{Deferred} which fires with a three-tuple of lists of
  233. L{twisted.names.dns.RRHeader} instances. The first element of the
  234. tuple gives answers. The second element of the tuple gives
  235. authorities. The third element of the tuple gives additional
  236. information. The L{Deferred} may instead fail with one of the
  237. exceptions defined in L{twisted.names.error} or with
  238. C{NotImplementedError}.
  239. """
  240. def lookupMailExchange(
  241. name: str, timeout: Sequence[int]
  242. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  243. """
  244. Perform an MX record lookup.
  245. @param name: DNS name to resolve.
  246. @param timeout: Number of seconds after which to reissue the query.
  247. When the last timeout expires, the query is considered failed.
  248. @return: A L{Deferred} which fires with a three-tuple of lists of
  249. L{twisted.names.dns.RRHeader} instances. The first element of the
  250. tuple gives answers. The second element of the tuple gives
  251. authorities. The third element of the tuple gives additional
  252. information. The L{Deferred} may instead fail with one of the
  253. exceptions defined in L{twisted.names.error} or with
  254. C{NotImplementedError}.
  255. """
  256. def lookupNameservers(
  257. name: str, timeout: Sequence[int]
  258. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  259. """
  260. Perform an NS record lookup.
  261. @param name: DNS name to resolve.
  262. @param timeout: Number of seconds after which to reissue the query.
  263. When the last timeout expires, the query is considered failed.
  264. @return: A L{Deferred} which fires with a three-tuple of lists of
  265. L{twisted.names.dns.RRHeader} instances. The first element of the
  266. tuple gives answers. The second element of the tuple gives
  267. authorities. The third element of the tuple gives additional
  268. information. The L{Deferred} may instead fail with one of the
  269. exceptions defined in L{twisted.names.error} or with
  270. C{NotImplementedError}.
  271. """
  272. def lookupCanonicalName(
  273. name: str, timeout: Sequence[int]
  274. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  275. """
  276. Perform a CNAME record lookup.
  277. @param name: DNS name to resolve.
  278. @param timeout: Number of seconds after which to reissue the query.
  279. When the last timeout expires, the query is considered failed.
  280. @return: A L{Deferred} which fires with a three-tuple of lists of
  281. L{twisted.names.dns.RRHeader} instances. The first element of the
  282. tuple gives answers. The second element of the tuple gives
  283. authorities. The third element of the tuple gives additional
  284. information. The L{Deferred} may instead fail with one of the
  285. exceptions defined in L{twisted.names.error} or with
  286. C{NotImplementedError}.
  287. """
  288. def lookupMailBox(
  289. name: str, timeout: Sequence[int]
  290. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  291. """
  292. Perform an MB record lookup.
  293. @param name: DNS name to resolve.
  294. @param timeout: Number of seconds after which to reissue the query.
  295. When the last timeout expires, the query is considered failed.
  296. @return: A L{Deferred} which fires with a three-tuple of lists of
  297. L{twisted.names.dns.RRHeader} instances. The first element of the
  298. tuple gives answers. The second element of the tuple gives
  299. authorities. The third element of the tuple gives additional
  300. information. The L{Deferred} may instead fail with one of the
  301. exceptions defined in L{twisted.names.error} or with
  302. C{NotImplementedError}.
  303. """
  304. def lookupMailGroup(
  305. name: str, timeout: Sequence[int]
  306. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  307. """
  308. Perform an MG record lookup.
  309. @param name: DNS name to resolve.
  310. @param timeout: Number of seconds after which to reissue the query.
  311. When the last timeout expires, the query is considered failed.
  312. @return: A L{Deferred} which fires with a three-tuple of lists of
  313. L{twisted.names.dns.RRHeader} instances. The first element of the
  314. tuple gives answers. The second element of the tuple gives
  315. authorities. The third element of the tuple gives additional
  316. information. The L{Deferred} may instead fail with one of the
  317. exceptions defined in L{twisted.names.error} or with
  318. C{NotImplementedError}.
  319. """
  320. def lookupMailRename(
  321. name: str, timeout: Sequence[int]
  322. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  323. """
  324. Perform an MR record lookup.
  325. @param name: DNS name to resolve.
  326. @param timeout: Number of seconds after which to reissue the query.
  327. When the last timeout expires, the query is considered failed.
  328. @return: A L{Deferred} which fires with a three-tuple of lists of
  329. L{twisted.names.dns.RRHeader} instances. The first element of the
  330. tuple gives answers. The second element of the tuple gives
  331. authorities. The third element of the tuple gives additional
  332. information. The L{Deferred} may instead fail with one of the
  333. exceptions defined in L{twisted.names.error} or with
  334. C{NotImplementedError}.
  335. """
  336. def lookupPointer(
  337. name: str, timeout: Sequence[int]
  338. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  339. """
  340. Perform a PTR record lookup.
  341. @param name: DNS name to resolve.
  342. @param timeout: Number of seconds after which to reissue the query.
  343. When the last timeout expires, the query is considered failed.
  344. @return: A L{Deferred} which fires with a three-tuple of lists of
  345. L{twisted.names.dns.RRHeader} instances. The first element of the
  346. tuple gives answers. The second element of the tuple gives
  347. authorities. The third element of the tuple gives additional
  348. information. The L{Deferred} may instead fail with one of the
  349. exceptions defined in L{twisted.names.error} or with
  350. C{NotImplementedError}.
  351. """
  352. def lookupAuthority(
  353. name: str, timeout: Sequence[int]
  354. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  355. """
  356. Perform an SOA record lookup.
  357. @param name: DNS name to resolve.
  358. @param timeout: Number of seconds after which to reissue the query.
  359. When the last timeout expires, the query is considered failed.
  360. @return: A L{Deferred} which fires with a three-tuple of lists of
  361. L{twisted.names.dns.RRHeader} instances. The first element of the
  362. tuple gives answers. The second element of the tuple gives
  363. authorities. The third element of the tuple gives additional
  364. information. The L{Deferred} may instead fail with one of the
  365. exceptions defined in L{twisted.names.error} or with
  366. C{NotImplementedError}.
  367. """
  368. def lookupNull(
  369. name: str, timeout: Sequence[int]
  370. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  371. """
  372. Perform a NULL record lookup.
  373. @param name: DNS name to resolve.
  374. @param timeout: Number of seconds after which to reissue the query.
  375. When the last timeout expires, the query is considered failed.
  376. @return: A L{Deferred} which fires with a three-tuple of lists of
  377. L{twisted.names.dns.RRHeader} instances. The first element of the
  378. tuple gives answers. The second element of the tuple gives
  379. authorities. The third element of the tuple gives additional
  380. information. The L{Deferred} may instead fail with one of the
  381. exceptions defined in L{twisted.names.error} or with
  382. C{NotImplementedError}.
  383. """
  384. def lookupWellKnownServices(
  385. name: str, timeout: Sequence[int]
  386. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  387. """
  388. Perform a WKS record lookup.
  389. @param name: DNS name to resolve.
  390. @param timeout: Number of seconds after which to reissue the query.
  391. When the last timeout expires, the query is considered failed.
  392. @return: A L{Deferred} which fires with a three-tuple of lists of
  393. L{twisted.names.dns.RRHeader} instances. The first element of the
  394. tuple gives answers. The second element of the tuple gives
  395. authorities. The third element of the tuple gives additional
  396. information. The L{Deferred} may instead fail with one of the
  397. exceptions defined in L{twisted.names.error} or with
  398. C{NotImplementedError}.
  399. """
  400. def lookupHostInfo(
  401. name: str, timeout: Sequence[int]
  402. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  403. """
  404. Perform a HINFO record lookup.
  405. @param name: DNS name to resolve.
  406. @param timeout: Number of seconds after which to reissue the query.
  407. When the last timeout expires, the query is considered failed.
  408. @return: A L{Deferred} which fires with a three-tuple of lists of
  409. L{twisted.names.dns.RRHeader} instances. The first element of the
  410. tuple gives answers. The second element of the tuple gives
  411. authorities. The third element of the tuple gives additional
  412. information. The L{Deferred} may instead fail with one of the
  413. exceptions defined in L{twisted.names.error} or with
  414. C{NotImplementedError}.
  415. """
  416. def lookupMailboxInfo(
  417. name: str, timeout: Sequence[int]
  418. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  419. """
  420. Perform an MINFO record lookup.
  421. @param name: DNS name to resolve.
  422. @param timeout: Number of seconds after which to reissue the query.
  423. When the last timeout expires, the query is considered failed.
  424. @return: A L{Deferred} which fires with a three-tuple of lists of
  425. L{twisted.names.dns.RRHeader} instances. The first element of the
  426. tuple gives answers. The second element of the tuple gives
  427. authorities. The third element of the tuple gives additional
  428. information. The L{Deferred} may instead fail with one of the
  429. exceptions defined in L{twisted.names.error} or with
  430. C{NotImplementedError}.
  431. """
  432. def lookupText(
  433. name: str, timeout: Sequence[int]
  434. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  435. """
  436. Perform a TXT record lookup.
  437. @param name: DNS name to resolve.
  438. @param timeout: Number of seconds after which to reissue the query.
  439. When the last timeout expires, the query is considered failed.
  440. @return: A L{Deferred} which fires with a three-tuple of lists of
  441. L{twisted.names.dns.RRHeader} instances. The first element of the
  442. tuple gives answers. The second element of the tuple gives
  443. authorities. The third element of the tuple gives additional
  444. information. The L{Deferred} may instead fail with one of the
  445. exceptions defined in L{twisted.names.error} or with
  446. C{NotImplementedError}.
  447. """
  448. def lookupResponsibility(
  449. name: str, timeout: Sequence[int]
  450. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  451. """
  452. Perform an RP record lookup.
  453. @param name: DNS name to resolve.
  454. @param timeout: Number of seconds after which to reissue the query.
  455. When the last timeout expires, the query is considered failed.
  456. @return: A L{Deferred} which fires with a three-tuple of lists of
  457. L{twisted.names.dns.RRHeader} instances. The first element of the
  458. tuple gives answers. The second element of the tuple gives
  459. authorities. The third element of the tuple gives additional
  460. information. The L{Deferred} may instead fail with one of the
  461. exceptions defined in L{twisted.names.error} or with
  462. C{NotImplementedError}.
  463. """
  464. def lookupAFSDatabase(
  465. name: str, timeout: Sequence[int]
  466. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  467. """
  468. Perform an AFSDB record lookup.
  469. @param name: DNS name to resolve.
  470. @param timeout: Number of seconds after which to reissue the query.
  471. When the last timeout expires, the query is considered failed.
  472. @return: A L{Deferred} which fires with a three-tuple of lists of
  473. L{twisted.names.dns.RRHeader} instances. The first element of the
  474. tuple gives answers. The second element of the tuple gives
  475. authorities. The third element of the tuple gives additional
  476. information. The L{Deferred} may instead fail with one of the
  477. exceptions defined in L{twisted.names.error} or with
  478. C{NotImplementedError}.
  479. """
  480. def lookupService(
  481. name: str, timeout: Sequence[int]
  482. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  483. """
  484. Perform an SRV record lookup.
  485. @param name: DNS name to resolve.
  486. @param timeout: Number of seconds after which to reissue the query.
  487. When the last timeout expires, the query is considered failed.
  488. @return: A L{Deferred} which fires with a three-tuple of lists of
  489. L{twisted.names.dns.RRHeader} instances. The first element of the
  490. tuple gives answers. The second element of the tuple gives
  491. authorities. The third element of the tuple gives additional
  492. information. The L{Deferred} may instead fail with one of the
  493. exceptions defined in L{twisted.names.error} or with
  494. C{NotImplementedError}.
  495. """
  496. def lookupAllRecords(
  497. name: str, timeout: Sequence[int]
  498. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  499. """
  500. Perform an ALL_RECORD lookup.
  501. @param name: DNS name to resolve.
  502. @param timeout: Number of seconds after which to reissue the query.
  503. When the last timeout expires, the query is considered failed.
  504. @return: A L{Deferred} which fires with a three-tuple of lists of
  505. L{twisted.names.dns.RRHeader} instances. The first element of the
  506. tuple gives answers. The second element of the tuple gives
  507. authorities. The third element of the tuple gives additional
  508. information. The L{Deferred} may instead fail with one of the
  509. exceptions defined in L{twisted.names.error} or with
  510. C{NotImplementedError}.
  511. """
  512. def lookupSenderPolicy(
  513. name: str, timeout: Sequence[int]
  514. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  515. """
  516. Perform a SPF record lookup.
  517. @param name: DNS name to resolve.
  518. @param timeout: Number of seconds after which to reissue the query.
  519. When the last timeout expires, the query is considered failed.
  520. @return: A L{Deferred} which fires with a three-tuple of lists of
  521. L{twisted.names.dns.RRHeader} instances. The first element of the
  522. tuple gives answers. The second element of the tuple gives
  523. authorities. The third element of the tuple gives additional
  524. information. The L{Deferred} may instead fail with one of the
  525. exceptions defined in L{twisted.names.error} or with
  526. C{NotImplementedError}.
  527. """
  528. def lookupNamingAuthorityPointer(
  529. name: str, timeout: Sequence[int]
  530. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  531. """
  532. Perform a NAPTR record lookup.
  533. @param name: DNS name to resolve.
  534. @param timeout: Number of seconds after which to reissue the query.
  535. When the last timeout expires, the query is considered failed.
  536. @return: A L{Deferred} which fires with a three-tuple of lists of
  537. L{twisted.names.dns.RRHeader} instances. The first element of the
  538. tuple gives answers. The second element of the tuple gives
  539. authorities. The third element of the tuple gives additional
  540. information. The L{Deferred} may instead fail with one of the
  541. exceptions defined in L{twisted.names.error} or with
  542. C{NotImplementedError}.
  543. """
  544. def lookupZone(
  545. name: str, timeout: Sequence[int]
  546. ) -> "Deferred[Tuple[RRHeader, RRHeader, RRHeader]]":
  547. """
  548. Perform an AXFR record lookup.
  549. NB This is quite different from other DNS requests. See
  550. U{http://cr.yp.to/djbdns/axfr-notes.html} for more
  551. information.
  552. NB Unlike other C{lookup*} methods, the timeout here is not a
  553. list of ints, it is a single int.
  554. @param name: DNS name to resolve.
  555. @param timeout: When this timeout expires, the query is
  556. considered failed.
  557. @return: A L{Deferred} which fires with a three-tuple of lists of
  558. L{twisted.names.dns.RRHeader} instances.
  559. The first element of the tuple gives answers.
  560. The second and third elements are always empty.
  561. The L{Deferred} may instead fail with one of the
  562. exceptions defined in L{twisted.names.error} or with
  563. C{NotImplementedError}.
  564. """
  565. class IReactorTCP(Interface):
  566. def listenTCP(
  567. port: int, factory: "ServerFactory", backlog: int, interface: str
  568. ) -> "IListeningPort":
  569. """
  570. Connects a given protocol factory to the given numeric TCP/IP port.
  571. @param port: a port number on which to listen
  572. @param factory: a L{twisted.internet.protocol.ServerFactory} instance
  573. @param backlog: size of the listen queue
  574. @param interface: The local IPv4 or IPv6 address to which to bind;
  575. defaults to '', ie all IPv4 addresses. To bind to all IPv4 and IPv6
  576. addresses, you must call this method twice.
  577. @return: an object that provides L{IListeningPort}.
  578. @raise CannotListenError: as defined here
  579. L{twisted.internet.error.CannotListenError},
  580. if it cannot listen on this port (e.g., it
  581. cannot bind to the required port number)
  582. """
  583. def connectTCP(
  584. host: str,
  585. port: int,
  586. factory: "ClientFactory",
  587. timeout: float,
  588. bindAddress: Optional[Tuple[str, int]],
  589. ) -> IConnector:
  590. """
  591. Connect a TCP client.
  592. @param host: A hostname or an IPv4 or IPv6 address literal.
  593. @param port: a port number
  594. @param factory: a L{twisted.internet.protocol.ClientFactory} instance
  595. @param timeout: number of seconds to wait before assuming the
  596. connection has failed.
  597. @param bindAddress: a (host, port) tuple of local address to bind
  598. to, or None.
  599. @return: An object which provides L{IConnector}. This connector will
  600. call various callbacks on the factory when a connection is
  601. made, failed, or lost - see
  602. L{ClientFactory<twisted.internet.protocol.ClientFactory>}
  603. docs for details.
  604. """
  605. class IReactorSSL(Interface):
  606. def connectSSL(
  607. host: str,
  608. port: int,
  609. factory: "ClientFactory",
  610. contextFactory: "ClientContextFactory",
  611. timeout: float,
  612. bindAddress: Optional[Tuple[str, int]],
  613. ) -> IConnector:
  614. """
  615. Connect a client Protocol to a remote SSL socket.
  616. @param host: a host name
  617. @param port: a port number
  618. @param factory: a L{twisted.internet.protocol.ClientFactory} instance
  619. @param contextFactory: a L{twisted.internet.ssl.ClientContextFactory} object.
  620. @param timeout: number of seconds to wait before assuming the
  621. connection has failed.
  622. @param bindAddress: a (host, port) tuple of local address to bind to,
  623. or L{None}.
  624. @return: An object which provides L{IConnector}.
  625. """
  626. def listenSSL(
  627. port: int,
  628. factory: "ServerFactory",
  629. contextFactory: "IOpenSSLContextFactory",
  630. backlog: int,
  631. interface: str,
  632. ) -> "IListeningPort":
  633. """
  634. Connects a given protocol factory to the given numeric TCP/IP port.
  635. The connection is a SSL one, using contexts created by the context
  636. factory.
  637. @param port: a port number on which to listen
  638. @param factory: a L{twisted.internet.protocol.ServerFactory} instance
  639. @param contextFactory: an implementor of L{IOpenSSLContextFactory}
  640. @param backlog: size of the listen queue
  641. @param interface: the hostname to bind to, defaults to '' (all)
  642. """
  643. class IReactorUNIX(Interface):
  644. """
  645. UNIX socket methods.
  646. """
  647. def connectUNIX(
  648. address: str, factory: "ClientFactory", timeout: float, checkPID: bool
  649. ) -> IConnector:
  650. """
  651. Connect a client protocol to a UNIX socket.
  652. @param address: a path to a unix socket on the filesystem.
  653. @param factory: a L{twisted.internet.protocol.ClientFactory} instance
  654. @param timeout: number of seconds to wait before assuming the connection
  655. has failed.
  656. @param checkPID: if True, check for a pid file to verify that a server
  657. is listening. If C{address} is a Linux abstract namespace path,
  658. this must be C{False}.
  659. @return: An object which provides L{IConnector}.
  660. """
  661. def listenUNIX(
  662. address: str, factory: "Factory", backlog: int, mode: int, wantPID: bool
  663. ) -> "IListeningPort":
  664. """
  665. Listen on a UNIX socket.
  666. @param address: a path to a unix socket on the filesystem.
  667. @param factory: a L{twisted.internet.protocol.Factory} instance.
  668. @param backlog: number of connections to allow in backlog.
  669. @param mode: The mode (B{not} umask) to set on the unix socket. See
  670. platform specific documentation for information about how this
  671. might affect connection attempts.
  672. @param wantPID: if True, create a pidfile for the socket. If C{address}
  673. is a Linux abstract namespace path, this must be C{False}.
  674. @return: An object which provides L{IListeningPort}.
  675. """
  676. class IReactorUNIXDatagram(Interface):
  677. """
  678. Datagram UNIX socket methods.
  679. """
  680. def connectUNIXDatagram(
  681. address: str,
  682. protocol: "ConnectedDatagramProtocol",
  683. maxPacketSize: int,
  684. mode: int,
  685. bindAddress: Optional[Tuple[str, int]],
  686. ) -> IConnector:
  687. """
  688. Connect a client protocol to a datagram UNIX socket.
  689. @param address: a path to a unix socket on the filesystem.
  690. @param protocol: a L{twisted.internet.protocol.ConnectedDatagramProtocol} instance
  691. @param maxPacketSize: maximum packet size to accept
  692. @param mode: The mode (B{not} umask) to set on the unix socket. See
  693. platform specific documentation for information about how this
  694. might affect connection attempts.
  695. @param bindAddress: address to bind to
  696. @return: An object which provides L{IConnector}.
  697. """
  698. def listenUNIXDatagram(
  699. address: str, protocol: "DatagramProtocol", maxPacketSize: int, mode: int
  700. ) -> "IListeningPort":
  701. """
  702. Listen on a datagram UNIX socket.
  703. @param address: a path to a unix socket on the filesystem.
  704. @param protocol: a L{twisted.internet.protocol.DatagramProtocol} instance.
  705. @param maxPacketSize: maximum packet size to accept
  706. @param mode: The mode (B{not} umask) to set on the unix socket. See
  707. platform specific documentation for information about how this
  708. might affect connection attempts.
  709. @return: An object which provides L{IListeningPort}.
  710. """
  711. class IReactorWin32Events(Interface):
  712. """
  713. Win32 Event API methods
  714. @since: 10.2
  715. """
  716. def addEvent(event: object, fd: "FileDescriptor", action: str) -> None:
  717. """
  718. Add a new win32 event to the event loop.
  719. @param event: a Win32 event object created using win32event.CreateEvent()
  720. @param fd: an instance of L{twisted.internet.abstract.FileDescriptor}
  721. @param action: a string that is a method name of the fd instance.
  722. This method is called in response to the event.
  723. """
  724. def removeEvent(event: object) -> None:
  725. """
  726. Remove an event.
  727. @param event: a Win32 event object added using L{IReactorWin32Events.addEvent}
  728. @return: None
  729. """
  730. class IReactorUDP(Interface):
  731. """
  732. UDP socket methods.
  733. """
  734. def listenUDP(
  735. port: int, protocol: "DatagramProtocol", interface: str, maxPacketSize: int
  736. ) -> "IListeningPort":
  737. """
  738. Connects a given L{DatagramProtocol} to the given numeric UDP port.
  739. @param port: A port number on which to listen.
  740. @param protocol: A L{DatagramProtocol} instance which will be
  741. connected to the given C{port}.
  742. @param interface: The local IPv4 or IPv6 address to which to bind;
  743. defaults to '', ie all IPv4 addresses.
  744. @param maxPacketSize: The maximum packet size to accept.
  745. @return: object which provides L{IListeningPort}.
  746. """
  747. class IReactorMulticast(Interface):
  748. """
  749. UDP socket methods that support multicast.
  750. IMPORTANT: This is an experimental new interface. It may change
  751. without backwards compatibility. Suggestions are welcome.
  752. """
  753. def listenMulticast(
  754. port: int,
  755. protocol: "DatagramProtocol",
  756. interface: str,
  757. maxPacketSize: int,
  758. listenMultiple: bool,
  759. ) -> "IListeningPort":
  760. """
  761. Connects a given
  762. L{DatagramProtocol<twisted.internet.protocol.DatagramProtocol>} to the
  763. given numeric UDP port.
  764. @param listenMultiple: If set to True, allows multiple sockets to
  765. bind to the same address and port number at the same time.
  766. @returns: An object which provides L{IListeningPort}.
  767. @see: L{twisted.internet.interfaces.IMulticastTransport}
  768. @see: U{http://twistedmatrix.com/documents/current/core/howto/udp.html}
  769. """
  770. class IReactorSocket(Interface):
  771. """
  772. Methods which allow a reactor to use externally created sockets.
  773. For example, to use C{adoptStreamPort} to implement behavior equivalent
  774. to that of L{IReactorTCP.listenTCP}, you might write code like this::
  775. from socket import SOMAXCONN, AF_INET, SOCK_STREAM, socket
  776. portSocket = socket(AF_INET, SOCK_STREAM)
  777. # Set FD_CLOEXEC on port, left as an exercise. Then make it into a
  778. # non-blocking listening port:
  779. portSocket.setblocking(False)
  780. portSocket.bind(('192.168.1.2', 12345))
  781. portSocket.listen(SOMAXCONN)
  782. # Now have the reactor use it as a TCP port
  783. port = reactor.adoptStreamPort(
  784. portSocket.fileno(), AF_INET, YourFactory())
  785. # portSocket itself is no longer necessary, and needs to be cleaned
  786. # up by us.
  787. portSocket.close()
  788. # Whenever the server is no longer needed, stop it as usual.
  789. stoppedDeferred = port.stopListening()
  790. Another potential use is to inherit a listening descriptor from a parent
  791. process (for example, systemd or launchd), or to receive one over a UNIX
  792. domain socket.
  793. Some plans for extending this interface exist. See:
  794. - U{http://twistedmatrix.com/trac/ticket/6594}: AF_UNIX SOCK_DGRAM ports
  795. """
  796. def adoptStreamPort(
  797. fileDescriptor: int, addressFamily: "AddressFamily", factory: "ServerFactory"
  798. ) -> "IListeningPort":
  799. """
  800. Add an existing listening I{SOCK_STREAM} socket to the reactor to
  801. monitor for new connections to accept and handle.
  802. @param fileDescriptor: A file descriptor associated with a socket which
  803. is already bound to an address and marked as listening. The socket
  804. must be set non-blocking. Any additional flags (for example,
  805. close-on-exec) must also be set by application code. Application
  806. code is responsible for closing the file descriptor, which may be
  807. done as soon as C{adoptStreamPort} returns.
  808. @param addressFamily: The address family (or I{domain}) of the socket.
  809. For example, L{socket.AF_INET6}.
  810. @param factory: A L{ServerFactory} instance to use to create new
  811. protocols to handle connections accepted via this socket.
  812. @return: An object providing L{IListeningPort}.
  813. @raise twisted.internet.error.UnsupportedAddressFamily: If the
  814. given address family is not supported by this reactor, or
  815. not supported with the given socket type.
  816. @raise twisted.internet.error.UnsupportedSocketType: If the
  817. given socket type is not supported by this reactor, or not
  818. supported with the given socket type.
  819. """
  820. def adoptStreamConnection(
  821. fileDescriptor: int, addressFamily: "AddressFamily", factory: "ServerFactory"
  822. ) -> None:
  823. """
  824. Add an existing connected I{SOCK_STREAM} socket to the reactor to
  825. monitor for data.
  826. Note that the given factory won't have its C{startFactory} and
  827. C{stopFactory} methods called, as there is no sensible time to call
  828. them in this situation.
  829. @param fileDescriptor: A file descriptor associated with a socket which
  830. is already connected. The socket must be set non-blocking. Any
  831. additional flags (for example, close-on-exec) must also be set by
  832. application code. Application code is responsible for closing the
  833. file descriptor, which may be done as soon as
  834. C{adoptStreamConnection} returns.
  835. @param addressFamily: The address family (or I{domain}) of the socket.
  836. For example, L{socket.AF_INET6}.
  837. @param factory: A L{ServerFactory} instance to use to create a new
  838. protocol to handle the connection via this socket.
  839. @raise UnsupportedAddressFamily: If the given address family is not
  840. supported by this reactor, or not supported with the given socket
  841. type.
  842. @raise UnsupportedSocketType: If the given socket type is not supported
  843. by this reactor, or not supported with the given socket type.
  844. """
  845. def adoptDatagramPort(
  846. fileDescriptor: int,
  847. addressFamily: "AddressFamily",
  848. protocol: "DatagramProtocol",
  849. maxPacketSize: int,
  850. ) -> "IListeningPort":
  851. """
  852. Add an existing listening I{SOCK_DGRAM} socket to the reactor to
  853. monitor for read and write readiness.
  854. @param fileDescriptor: A file descriptor associated with a socket which
  855. is already bound to an address and marked as listening. The socket
  856. must be set non-blocking. Any additional flags (for example,
  857. close-on-exec) must also be set by application code. Application
  858. code is responsible for closing the file descriptor, which may be
  859. done as soon as C{adoptDatagramPort} returns.
  860. @param addressFamily: The address family or I{domain} of the socket.
  861. For example, L{socket.AF_INET6}.
  862. @param protocol: A L{DatagramProtocol} instance to connect to
  863. a UDP transport.
  864. @param maxPacketSize: The maximum packet size to accept.
  865. @return: An object providing L{IListeningPort}.
  866. @raise UnsupportedAddressFamily: If the given address family is not
  867. supported by this reactor, or not supported with the given socket
  868. type.
  869. @raise UnsupportedSocketType: If the given socket type is not supported
  870. by this reactor, or not supported with the given socket type.
  871. """
  872. class IReactorProcess(Interface):
  873. def spawnProcess(
  874. processProtocol: "IProcessProtocol",
  875. executable: Union[bytes, str],
  876. args: Sequence[Union[bytes, str]],
  877. env: Optional[Mapping[AnyStr, AnyStr]] = None,
  878. path: Union[None, bytes, str] = None,
  879. uid: Optional[int] = None,
  880. gid: Optional[int] = None,
  881. usePTY: bool = False,
  882. childFDs: Optional[Mapping[int, Union[int, str]]] = None,
  883. ) -> "IProcessTransport":
  884. """
  885. Spawn a process, with a process protocol.
  886. Arguments given to this function that are listed as L{bytes} or
  887. L{unicode} may be encoded or decoded depending on the platform and the
  888. argument type given. On UNIX systems (Linux, FreeBSD, macOS) and
  889. Python 2 on Windows, L{unicode} arguments will be encoded down to
  890. L{bytes} using the encoding given by L{sys.getfilesystemencoding}, to be
  891. used with the "narrow" OS APIs. On Python 3 on Windows, L{bytes}
  892. arguments will be decoded up to L{unicode} using the encoding given by
  893. L{sys.getfilesystemencoding} (C{utf8}) and given to Windows's native "wide" APIs.
  894. @param processProtocol: An object which will be notified of all events
  895. related to the created process.
  896. @param executable: the file name to spawn - the full path should be
  897. used.
  898. @param args: the command line arguments to pass to the process; a
  899. sequence of strings. The first string should be the executable's
  900. name.
  901. @param env: the environment variables to pass to the child process.
  902. The resulting behavior varies between platforms. If:
  903. - C{env} is not set:
  904. - On POSIX: pass an empty environment.
  905. - On Windows: pass L{os.environ}.
  906. - C{env} is L{None}:
  907. - On POSIX: pass L{os.environ}.
  908. - On Windows: pass L{os.environ}.
  909. - C{env} is a L{dict}:
  910. - On POSIX: pass the key/value pairs in C{env} as the
  911. complete environment.
  912. - On Windows: update L{os.environ} with the key/value
  913. pairs in the L{dict} before passing it. As a
  914. consequence of U{bug #1640
  915. <http://twistedmatrix.com/trac/ticket/1640>}, passing
  916. keys with empty values in an effort to unset
  917. environment variables I{won't} unset them.
  918. @param path: the path to run the subprocess in - defaults to the
  919. current directory.
  920. @param uid: user ID to run the subprocess as. (Only available on POSIX
  921. systems.)
  922. @param gid: group ID to run the subprocess as. (Only available on
  923. POSIX systems.)
  924. @param usePTY: if true, run this process in a pseudo-terminal.
  925. optionally a tuple of C{(masterfd, slavefd, ttyname)}, in which
  926. case use those file descriptors. (Not available on all systems.)
  927. @param childFDs: A dictionary mapping file descriptors in the new child
  928. process to an integer or to the string 'r' or 'w'.
  929. If the value is an integer, it specifies a file descriptor in the
  930. parent process which will be mapped to a file descriptor (specified
  931. by the key) in the child process. This is useful for things like
  932. inetd and shell-like file redirection.
  933. If it is the string 'r', a pipe will be created and attached to the
  934. child at that file descriptor: the child will be able to write to
  935. that file descriptor and the parent will receive read notification
  936. via the L{IProcessProtocol.childDataReceived} callback. This is
  937. useful for the child's stdout and stderr.
  938. If it is the string 'w', similar setup to the previous case will
  939. occur, with the pipe being readable by the child instead of
  940. writeable. The parent process can write to that file descriptor
  941. using L{IProcessTransport.writeToChild}. This is useful for the
  942. child's stdin.
  943. If childFDs is not passed, the default behaviour is to use a
  944. mapping that opens the usual stdin/stdout/stderr pipes.
  945. @see: L{twisted.internet.protocol.ProcessProtocol}
  946. @return: An object which provides L{IProcessTransport}.
  947. @raise OSError: Raised with errno C{EAGAIN} or C{ENOMEM} if there are
  948. insufficient system resources to create a new process.
  949. """
  950. class IReactorTime(Interface):
  951. """
  952. Time methods that a Reactor should implement.
  953. """
  954. def seconds() -> float:
  955. """
  956. Get the current time in seconds.
  957. @return: A number-like object of some sort.
  958. """
  959. def callLater(
  960. delay: float, callable: Callable[..., Any], *args: object, **kwargs: object
  961. ) -> "IDelayedCall":
  962. """
  963. Call a function later.
  964. @param delay: the number of seconds to wait.
  965. @param callable: the callable object to call later.
  966. @param args: the arguments to call it with.
  967. @param kwargs: the keyword arguments to call it with.
  968. @return: An object which provides L{IDelayedCall} and can be used to
  969. cancel the scheduled call, by calling its C{cancel()} method.
  970. It also may be rescheduled by calling its C{delay()} or
  971. C{reset()} methods.
  972. """
  973. def getDelayedCalls() -> Sequence["IDelayedCall"]:
  974. """
  975. See L{twisted.internet.interfaces.IReactorTime.getDelayedCalls}
  976. """
  977. class IDelayedCall(Interface):
  978. """
  979. A scheduled call.
  980. There are probably other useful methods we can add to this interface;
  981. suggestions are welcome.
  982. """
  983. def getTime() -> float:
  984. """
  985. Get time when delayed call will happen.
  986. @return: time in seconds since epoch (a float).
  987. """
  988. def cancel() -> None:
  989. """
  990. Cancel the scheduled call.
  991. @raises twisted.internet.error.AlreadyCalled: if the call has already
  992. happened.
  993. @raises twisted.internet.error.AlreadyCancelled: if the call has already
  994. been cancelled.
  995. """
  996. def delay(secondsLater: float) -> None:
  997. """
  998. Delay the scheduled call.
  999. @param secondsLater: how many seconds from its current firing time to delay
  1000. @raises twisted.internet.error.AlreadyCalled: if the call has already
  1001. happened.
  1002. @raises twisted.internet.error.AlreadyCancelled: if the call has already
  1003. been cancelled.
  1004. """
  1005. def reset(secondsFromNow: float) -> None:
  1006. """
  1007. Reset the scheduled call's timer.
  1008. @param secondsFromNow: how many seconds from now it should fire,
  1009. equivalent to C{.cancel()} and then doing another
  1010. C{reactor.callLater(secondsLater, ...)}
  1011. @raises twisted.internet.error.AlreadyCalled: if the call has already
  1012. happened.
  1013. @raises twisted.internet.error.AlreadyCancelled: if the call has already
  1014. been cancelled.
  1015. """
  1016. def active() -> bool:
  1017. """
  1018. @return: True if this call is still active, False if it has been
  1019. called or cancelled.
  1020. """
  1021. class IReactorFromThreads(Interface):
  1022. """
  1023. This interface is the set of thread-safe methods which may be invoked on
  1024. the reactor from other threads.
  1025. @since: 15.4
  1026. """
  1027. def callFromThread(
  1028. callable: Callable[..., Any], *args: object, **kwargs: object
  1029. ) -> None:
  1030. """
  1031. Cause a function to be executed by the reactor thread.
  1032. Use this method when you want to run a function in the reactor's thread
  1033. from another thread. Calling L{callFromThread} should wake up the main
  1034. thread (where L{reactor.run() <IReactorCore.run>} is executing) and run
  1035. the given callable in that thread.
  1036. If you're writing a multi-threaded application the C{callable}
  1037. may need to be thread safe, but this method doesn't require it as such.
  1038. If you want to call a function in the next mainloop iteration, but
  1039. you're in the same thread, use L{callLater} with a delay of 0.
  1040. """
  1041. class IReactorInThreads(Interface):
  1042. """
  1043. This interface contains the methods exposed by a reactor which will let you
  1044. run functions in another thread.
  1045. @since: 15.4
  1046. """
  1047. def callInThread(
  1048. callable: Callable[..., Any], *args: object, **kwargs: object
  1049. ) -> None:
  1050. """
  1051. Run the given callable object in a separate thread, with the given
  1052. arguments and keyword arguments.
  1053. """
  1054. class IReactorThreads(IReactorFromThreads, IReactorInThreads):
  1055. """
  1056. Dispatch methods to be run in threads.
  1057. Internally, this should use a thread pool and dispatch methods to them.
  1058. """
  1059. def getThreadPool() -> "ThreadPool":
  1060. """
  1061. Return the threadpool used by L{IReactorInThreads.callInThread}.
  1062. Create it first if necessary.
  1063. """
  1064. def suggestThreadPoolSize(size: int) -> None:
  1065. """
  1066. Suggest the size of the internal threadpool used to dispatch functions
  1067. passed to L{IReactorInThreads.callInThread}.
  1068. """
  1069. class IReactorCore(Interface):
  1070. """
  1071. Core methods that a Reactor must implement.
  1072. """
  1073. running = Attribute(
  1074. "A C{bool} which is C{True} from I{during startup} to "
  1075. "I{during shutdown} and C{False} the rest of the time."
  1076. )
  1077. def resolve(name: str, timeout: Sequence[int]) -> "Deferred[str]":
  1078. """
  1079. Return a L{twisted.internet.defer.Deferred} that will resolve
  1080. a hostname.
  1081. """
  1082. def run() -> None:
  1083. """
  1084. Fire 'startup' System Events, move the reactor to the 'running'
  1085. state, then run the main loop until it is stopped with C{stop()} or
  1086. C{crash()}.
  1087. """
  1088. def stop() -> None:
  1089. """
  1090. Fire 'shutdown' System Events, which will move the reactor to the
  1091. 'stopped' state and cause C{reactor.run()} to exit.
  1092. """
  1093. def crash() -> None:
  1094. """
  1095. Stop the main loop *immediately*, without firing any system events.
  1096. This is named as it is because this is an extremely "rude" thing to do;
  1097. it is possible to lose data and put your system in an inconsistent
  1098. state by calling this. However, it is necessary, as sometimes a system
  1099. can become wedged in a pre-shutdown call.
  1100. """
  1101. def iterate(delay: float) -> None:
  1102. """
  1103. Run the main loop's I/O polling function for a period of time.
  1104. This is most useful in applications where the UI is being drawn "as
  1105. fast as possible", such as games. All pending L{IDelayedCall}s will
  1106. be called.
  1107. The reactor must have been started (via the C{run()} method) prior to
  1108. any invocations of this method. It must also be stopped manually
  1109. after the last call to this method (via the C{stop()} method). This
  1110. method is not re-entrant: you must not call it recursively; in
  1111. particular, you must not call it while the reactor is running.
  1112. """
  1113. def fireSystemEvent(eventType: str) -> None:
  1114. """
  1115. Fire a system-wide event.
  1116. System-wide events are things like 'startup', 'shutdown', and
  1117. 'persist'.
  1118. """
  1119. def addSystemEventTrigger(
  1120. phase: str,
  1121. eventType: str,
  1122. callable: Callable[..., Any],
  1123. *args: object,
  1124. **kwargs: object,
  1125. ) -> Any:
  1126. """
  1127. Add a function to be called when a system event occurs.
  1128. Each "system event" in Twisted, such as 'startup', 'shutdown', and
  1129. 'persist', has 3 phases: 'before', 'during', and 'after' (in that
  1130. order, of course). These events will be fired internally by the
  1131. Reactor.
  1132. An implementor of this interface must only implement those events
  1133. described here.
  1134. Callbacks registered for the "before" phase may return either None or a
  1135. Deferred. The "during" phase will not execute until all of the
  1136. Deferreds from the "before" phase have fired.
  1137. Once the "during" phase is running, all of the remaining triggers must
  1138. execute; their return values must be ignored.
  1139. @param phase: a time to call the event -- either the string 'before',
  1140. 'after', or 'during', describing when to call it
  1141. relative to the event's execution.
  1142. @param eventType: this is a string describing the type of event.
  1143. @param callable: the object to call before shutdown.
  1144. @param args: the arguments to call it with.
  1145. @param kwargs: the keyword arguments to call it with.
  1146. @return: an ID that can be used to remove this call with
  1147. removeSystemEventTrigger.
  1148. """
  1149. def removeSystemEventTrigger(triggerID: Any) -> None:
  1150. """
  1151. Removes a trigger added with addSystemEventTrigger.
  1152. @param triggerID: a value returned from addSystemEventTrigger.
  1153. @raise KeyError: If there is no system event trigger for the given
  1154. C{triggerID}.
  1155. @raise ValueError: If there is no system event trigger for the given
  1156. C{triggerID}.
  1157. @raise TypeError: If there is no system event trigger for the given
  1158. C{triggerID}.
  1159. """
  1160. def callWhenRunning(
  1161. callable: Callable[..., Any], *args: object, **kwargs: object
  1162. ) -> Optional[Any]:
  1163. """
  1164. Call a function when the reactor is running.
  1165. If the reactor has not started, the callable will be scheduled
  1166. to run when it does start. Otherwise, the callable will be invoked
  1167. immediately.
  1168. @param callable: the callable object to call later.
  1169. @param args: the arguments to call it with.
  1170. @param kwargs: the keyword arguments to call it with.
  1171. @return: None if the callable was invoked, otherwise a system
  1172. event id for the scheduled call.
  1173. """
  1174. class IReactorPluggableResolver(Interface):
  1175. """
  1176. An L{IReactorPluggableResolver} is a reactor which can be customized with
  1177. an L{IResolverSimple}. This is a fairly limited interface, that supports
  1178. only IPv4; you should use L{IReactorPluggableNameResolver} instead.
  1179. @see: L{IReactorPluggableNameResolver}
  1180. """
  1181. def installResolver(resolver: IResolverSimple) -> IResolverSimple:
  1182. """
  1183. Set the internal resolver to use to for name lookups.
  1184. @param resolver: The new resolver to use.
  1185. @return: The previously installed resolver.
  1186. """
  1187. class IReactorPluggableNameResolver(Interface):
  1188. """
  1189. An L{IReactorPluggableNameResolver} is a reactor whose name resolver can be
  1190. set to a user-supplied object.
  1191. """
  1192. nameResolver = Attribute(
  1193. """
  1194. Read-only attribute; the resolver installed with L{installResolver}.
  1195. An L{IHostnameResolver}.
  1196. """
  1197. )
  1198. def installNameResolver(resolver: IHostnameResolver) -> IHostnameResolver:
  1199. """
  1200. Set the internal resolver to use for name lookups.
  1201. @param resolver: The new resolver to use.
  1202. @return: The previously installed resolver.
  1203. """
  1204. class IReactorDaemonize(Interface):
  1205. """
  1206. A reactor which provides hooks that need to be called before and after
  1207. daemonization.
  1208. Notes:
  1209. - This interface SHOULD NOT be called by applications.
  1210. - This interface should only be implemented by reactors as a workaround
  1211. (in particular, it's implemented currently only by kqueue()).
  1212. For details please see the comments on ticket #1918.
  1213. """
  1214. def beforeDaemonize() -> None:
  1215. """
  1216. Hook to be called immediately before daemonization. No reactor methods
  1217. may be called until L{afterDaemonize} is called.
  1218. """
  1219. def afterDaemonize() -> None:
  1220. """
  1221. Hook to be called immediately after daemonization. This may only be
  1222. called after L{beforeDaemonize} had been called previously.
  1223. """
  1224. class IReactorFDSet(Interface):
  1225. """
  1226. Implement me to be able to use L{IFileDescriptor} type resources.
  1227. This assumes that your main-loop uses UNIX-style numeric file descriptors
  1228. (or at least similarly opaque IDs returned from a .fileno() method)
  1229. """
  1230. def addReader(reader: "IReadDescriptor") -> None:
  1231. """
  1232. I add reader to the set of file descriptors to get read events for.
  1233. @param reader: An L{IReadDescriptor} provider that will be checked for
  1234. read events until it is removed from the reactor with
  1235. L{removeReader}.
  1236. """
  1237. def addWriter(writer: "IWriteDescriptor") -> None:
  1238. """
  1239. I add writer to the set of file descriptors to get write events for.
  1240. @param writer: An L{IWriteDescriptor} provider that will be checked for
  1241. write events until it is removed from the reactor with
  1242. L{removeWriter}.
  1243. """
  1244. def removeReader(reader: "IReadDescriptor") -> None:
  1245. """
  1246. Removes an object previously added with L{addReader}.
  1247. """
  1248. def removeWriter(writer: "IWriteDescriptor") -> None:
  1249. """
  1250. Removes an object previously added with L{addWriter}.
  1251. """
  1252. def removeAll() -> List[Union["IReadDescriptor", "IWriteDescriptor"]]:
  1253. """
  1254. Remove all readers and writers.
  1255. Should not remove reactor internal reactor connections (like a waker).
  1256. @return: A list of L{IReadDescriptor} and L{IWriteDescriptor} providers
  1257. which were removed.
  1258. """
  1259. def getReaders() -> List["IReadDescriptor"]:
  1260. """
  1261. Return the list of file descriptors currently monitored for input
  1262. events by the reactor.
  1263. @return: the list of file descriptors monitored for input events.
  1264. """
  1265. def getWriters() -> List["IWriteDescriptor"]:
  1266. """
  1267. Return the list file descriptors currently monitored for output events
  1268. by the reactor.
  1269. @return: the list of file descriptors monitored for output events.
  1270. """
  1271. class IListeningPort(Interface):
  1272. """
  1273. A listening port.
  1274. """
  1275. def startListening() -> None:
  1276. """
  1277. Start listening on this port.
  1278. @raise CannotListenError: If it cannot listen on this port (e.g., it is
  1279. a TCP port and it cannot bind to the required
  1280. port number).
  1281. """
  1282. def stopListening() -> Optional["Deferred[None]"]:
  1283. """
  1284. Stop listening on this port.
  1285. If it does not complete immediately, will return Deferred that fires
  1286. upon completion.
  1287. """
  1288. def getHost() -> IAddress:
  1289. """
  1290. Get the host that this port is listening for.
  1291. @return: An L{IAddress} provider.
  1292. """
  1293. class ILoggingContext(Interface):
  1294. """
  1295. Give context information that will be used to log events generated by
  1296. this item.
  1297. """
  1298. def logPrefix() -> str:
  1299. """
  1300. @return: Prefix used during log formatting to indicate context.
  1301. """
  1302. class IFileDescriptor(ILoggingContext):
  1303. """
  1304. An interface representing a UNIX-style numeric file descriptor.
  1305. """
  1306. def fileno() -> object:
  1307. """
  1308. @return: The platform-specified representation of a file descriptor
  1309. number. Or C{-1} if the descriptor no longer has a valid file
  1310. descriptor number associated with it. As long as the descriptor
  1311. is valid, calls to this method on a particular instance must
  1312. return the same value.
  1313. """
  1314. def connectionLost(reason: Failure) -> None:
  1315. """
  1316. Called when the connection was lost.
  1317. This is called when the connection on a selectable object has been
  1318. lost. It will be called whether the connection was closed explicitly,
  1319. an exception occurred in an event handler, or the other end of the
  1320. connection closed it first.
  1321. See also L{IHalfCloseableDescriptor} if your descriptor wants to be
  1322. notified separately of the two halves of the connection being closed.
  1323. @param reason: A failure instance indicating the reason why the
  1324. connection was lost. L{error.ConnectionLost} and
  1325. L{error.ConnectionDone} are of special note, but the
  1326. failure may be of other classes as well.
  1327. """
  1328. class IReadDescriptor(IFileDescriptor):
  1329. """
  1330. An L{IFileDescriptor} that can read.
  1331. This interface is generally used in conjunction with L{IReactorFDSet}.
  1332. """
  1333. def doRead() -> Optional[Failure]:
  1334. """
  1335. Some data is available for reading on your descriptor.
  1336. @return: If an error is encountered which causes the descriptor to
  1337. no longer be valid, a L{Failure} should be returned. Otherwise,
  1338. L{None}.
  1339. """
  1340. class IWriteDescriptor(IFileDescriptor):
  1341. """
  1342. An L{IFileDescriptor} that can write.
  1343. This interface is generally used in conjunction with L{IReactorFDSet}.
  1344. """
  1345. def doWrite() -> Optional[Failure]:
  1346. """
  1347. Some data can be written to your descriptor.
  1348. @return: If an error is encountered which causes the descriptor to
  1349. no longer be valid, a L{Failure} should be returned. Otherwise,
  1350. L{None}.
  1351. """
  1352. class IReadWriteDescriptor(IReadDescriptor, IWriteDescriptor):
  1353. """
  1354. An L{IFileDescriptor} that can both read and write.
  1355. """
  1356. class IHalfCloseableDescriptor(Interface):
  1357. """
  1358. A descriptor that can be half-closed.
  1359. """
  1360. def writeConnectionLost(reason: Failure) -> None:
  1361. """
  1362. Indicates write connection was lost.
  1363. """
  1364. def readConnectionLost(reason: Failure) -> None:
  1365. """
  1366. Indicates read connection was lost.
  1367. """
  1368. class ISystemHandle(Interface):
  1369. """
  1370. An object that wraps a networking OS-specific handle.
  1371. """
  1372. def getHandle() -> object:
  1373. """
  1374. Return a system- and reactor-specific handle.
  1375. This might be a socket.socket() object, or some other type of
  1376. object, depending on which reactor is being used. Use and
  1377. manipulate at your own risk.
  1378. This might be used in cases where you want to set specific
  1379. options not exposed by the Twisted APIs.
  1380. """
  1381. class IConsumer(Interface):
  1382. """
  1383. A consumer consumes data from a producer.
  1384. """
  1385. def registerProducer(producer: "IProducer", streaming: bool) -> None:
  1386. """
  1387. Register to receive data from a producer.
  1388. This sets self to be a consumer for a producer. When this object runs
  1389. out of data (as when a send(2) call on a socket succeeds in moving the
  1390. last data from a userspace buffer into a kernelspace buffer), it will
  1391. ask the producer to resumeProducing().
  1392. For L{IPullProducer} providers, C{resumeProducing} will be called once
  1393. each time data is required.
  1394. For L{IPushProducer} providers, C{pauseProducing} will be called
  1395. whenever the write buffer fills up and C{resumeProducing} will only be
  1396. called when it empties. The consumer will only call C{resumeProducing}
  1397. to balance a previous C{pauseProducing} call; the producer is assumed
  1398. to start in an un-paused state.
  1399. @param streaming: C{True} if C{producer} provides L{IPushProducer},
  1400. C{False} if C{producer} provides L{IPullProducer}.
  1401. @raise RuntimeError: If a producer is already registered.
  1402. """
  1403. def unregisterProducer() -> None:
  1404. """
  1405. Stop consuming data from a producer, without disconnecting.
  1406. """
  1407. def write(data: bytes) -> None:
  1408. """
  1409. The producer will write data by calling this method.
  1410. The implementation must be non-blocking and perform whatever
  1411. buffering is necessary. If the producer has provided enough data
  1412. for now and it is a L{IPushProducer}, the consumer may call its
  1413. C{pauseProducing} method.
  1414. """
  1415. class IProducer(Interface):
  1416. """
  1417. A producer produces data for a consumer.
  1418. Typically producing is done by calling the C{write} method of a class
  1419. implementing L{IConsumer}.
  1420. """
  1421. def stopProducing() -> None:
  1422. """
  1423. Stop producing data.
  1424. This tells a producer that its consumer has died, so it must stop
  1425. producing data for good.
  1426. """
  1427. class IPushProducer(IProducer):
  1428. """
  1429. A push producer, also known as a streaming producer is expected to
  1430. produce (write to this consumer) data on a continuous basis, unless
  1431. it has been paused. A paused push producer will resume producing
  1432. after its C{resumeProducing()} method is called. For a push producer
  1433. which is not pauseable, these functions may be noops.
  1434. """
  1435. def pauseProducing() -> None:
  1436. """
  1437. Pause producing data.
  1438. Tells a producer that it has produced too much data to process for
  1439. the time being, and to stop until C{resumeProducing()} is called.
  1440. """
  1441. def resumeProducing() -> None:
  1442. """
  1443. Resume producing data.
  1444. This tells a producer to re-add itself to the main loop and produce
  1445. more data for its consumer.
  1446. """
  1447. class IPullProducer(IProducer):
  1448. """
  1449. A pull producer, also known as a non-streaming producer, is
  1450. expected to produce data each time L{resumeProducing()} is called.
  1451. """
  1452. def resumeProducing() -> None:
  1453. """
  1454. Produce data for the consumer a single time.
  1455. This tells a producer to produce data for the consumer once
  1456. (not repeatedly, once only). Typically this will be done
  1457. by calling the consumer's C{write} method a single time with
  1458. produced data. The producer should produce data before returning
  1459. from C{resumeProducing()}, that is, it should not schedule a deferred
  1460. write.
  1461. """
  1462. class IProtocol(Interface):
  1463. def dataReceived(data: bytes) -> None:
  1464. """
  1465. Called whenever data is received.
  1466. Use this method to translate to a higher-level message. Usually, some
  1467. callback will be made upon the receipt of each complete protocol
  1468. message.
  1469. Please keep in mind that you will probably need to buffer some data
  1470. as partial (or multiple) protocol messages may be received! We
  1471. recommend that unit tests for protocols call through to this method
  1472. with differing chunk sizes, down to one byte at a time.
  1473. @param data: bytes of indeterminate length
  1474. """
  1475. def connectionLost(reason: Failure) -> None:
  1476. """
  1477. Called when the connection is shut down.
  1478. Clear any circular references here, and any external references
  1479. to this Protocol. The connection has been closed. The C{reason}
  1480. Failure wraps a L{twisted.internet.error.ConnectionDone} or
  1481. L{twisted.internet.error.ConnectionLost} instance (or a subclass
  1482. of one of those).
  1483. """
  1484. def makeConnection(transport: "ITransport") -> None:
  1485. """
  1486. Make a connection to a transport and a server.
  1487. """
  1488. def connectionMade() -> None:
  1489. """
  1490. Called when a connection is made.
  1491. This may be considered the initializer of the protocol, because
  1492. it is called when the connection is completed. For clients,
  1493. this is called once the connection to the server has been
  1494. established; for servers, this is called after an accept() call
  1495. stops blocking and a socket has been received. If you need to
  1496. send any greeting or initial message, do it here.
  1497. """
  1498. class IProcessProtocol(Interface):
  1499. """
  1500. Interface for process-related event handlers.
  1501. """
  1502. def makeConnection(process: "IProcessTransport") -> None:
  1503. """
  1504. Called when the process has been created.
  1505. @param process: An object representing the process which has been
  1506. created and associated with this protocol.
  1507. """
  1508. def childDataReceived(childFD: int, data: bytes) -> None:
  1509. """
  1510. Called when data arrives from the child process.
  1511. @param childFD: The file descriptor from which the data was
  1512. received.
  1513. @param data: The data read from the child's file descriptor.
  1514. """
  1515. def childConnectionLost(childFD: int) -> None:
  1516. """
  1517. Called when a file descriptor associated with the child process is
  1518. closed.
  1519. @param childFD: The file descriptor which was closed.
  1520. """
  1521. def processExited(reason: Failure) -> None:
  1522. """
  1523. Called when the child process exits.
  1524. @param reason: A failure giving the reason the child process
  1525. terminated. The type of exception for this failure is either
  1526. L{twisted.internet.error.ProcessDone} or
  1527. L{twisted.internet.error.ProcessTerminated}.
  1528. @since: 8.2
  1529. """
  1530. def processEnded(reason: Failure) -> None:
  1531. """
  1532. Called when the child process exits and all file descriptors associated
  1533. with it have been closed.
  1534. @param reason: A failure giving the reason the child process
  1535. terminated. The type of exception for this failure is either
  1536. L{twisted.internet.error.ProcessDone} or
  1537. L{twisted.internet.error.ProcessTerminated}.
  1538. """
  1539. class IHalfCloseableProtocol(Interface):
  1540. """
  1541. Implemented to indicate they want notification of half-closes.
  1542. TCP supports the notion of half-closing the connection, e.g.
  1543. closing the write side but still not stopping reading. A protocol
  1544. that implements this interface will be notified of such events,
  1545. instead of having connectionLost called.
  1546. """
  1547. def readConnectionLost() -> None:
  1548. """
  1549. Notification of the read connection being closed.
  1550. This indicates peer did half-close of write side. It is now
  1551. the responsibility of the this protocol to call
  1552. loseConnection(). In addition, the protocol MUST make sure a
  1553. reference to it still exists (i.e. by doing a callLater with
  1554. one of its methods, etc.) as the reactor will only have a
  1555. reference to it if it is writing.
  1556. If the protocol does not do so, it might get garbage collected
  1557. without the connectionLost method ever being called.
  1558. """
  1559. def writeConnectionLost() -> None:
  1560. """
  1561. Notification of the write connection being closed.
  1562. This will never be called for TCP connections as TCP does not
  1563. support notification of this type of half-close.
  1564. """
  1565. class IHandshakeListener(Interface):
  1566. """
  1567. An interface implemented by a L{IProtocol} to indicate that it would like
  1568. to be notified when TLS handshakes complete when run over a TLS-based
  1569. transport.
  1570. This interface is only guaranteed to be called when run over a TLS-based
  1571. transport: non TLS-based transports will not respect this interface.
  1572. """
  1573. def handshakeCompleted() -> None:
  1574. """
  1575. Notification of the TLS handshake being completed.
  1576. This notification fires when OpenSSL has completed the TLS handshake.
  1577. At this point the TLS connection is established, and the protocol can
  1578. interrogate its transport (usually an L{ISSLTransport}) for details of
  1579. the TLS connection.
  1580. This notification *also* fires whenever the TLS session is
  1581. renegotiated. As a result, protocols that have certain minimum security
  1582. requirements should implement this interface to ensure that they are
  1583. able to re-evaluate the security of the TLS session if it changes.
  1584. """
  1585. class IFileDescriptorReceiver(Interface):
  1586. """
  1587. Protocols may implement L{IFileDescriptorReceiver} to receive file
  1588. descriptors sent to them. This is useful in conjunction with
  1589. L{IUNIXTransport}, which allows file descriptors to be sent between
  1590. processes on a single host.
  1591. """
  1592. def fileDescriptorReceived(descriptor: int) -> None:
  1593. """
  1594. Called when a file descriptor is received over the connection.
  1595. @param descriptor: The descriptor which was received.
  1596. @return: L{None}
  1597. """
  1598. class IProtocolFactory(Interface):
  1599. """
  1600. Interface for protocol factories.
  1601. """
  1602. def buildProtocol(addr: IAddress) -> Optional[IProtocol]:
  1603. """
  1604. Called when a connection has been established to addr.
  1605. If None is returned, the connection is assumed to have been refused,
  1606. and the Port will close the connection.
  1607. @param addr: The address of the newly-established connection
  1608. @return: None if the connection was refused, otherwise an object
  1609. providing L{IProtocol}.
  1610. """
  1611. def doStart() -> None:
  1612. """
  1613. Called every time this is connected to a Port or Connector.
  1614. """
  1615. def doStop() -> None:
  1616. """
  1617. Called every time this is unconnected from a Port or Connector.
  1618. """
  1619. class ITransport(Interface):
  1620. """
  1621. I am a transport for bytes.
  1622. I represent (and wrap) the physical connection and synchronicity
  1623. of the framework which is talking to the network. I make no
  1624. representations about whether calls to me will happen immediately
  1625. or require returning to a control loop, or whether they will happen
  1626. in the same or another thread. Consider methods of this class
  1627. (aside from getPeer) to be 'thrown over the wall', to happen at some
  1628. indeterminate time.
  1629. """
  1630. def write(data: bytes) -> None:
  1631. """
  1632. Write some data to the physical connection, in sequence, in a
  1633. non-blocking fashion.
  1634. If possible, make sure that it is all written. No data will
  1635. ever be lost, although (obviously) the connection may be closed
  1636. before it all gets through.
  1637. @param data: The data to write.
  1638. """
  1639. def writeSequence(data: Iterable[bytes]) -> None:
  1640. """
  1641. Write an iterable of byte strings to the physical connection.
  1642. If possible, make sure that all of the data is written to
  1643. the socket at once, without first copying it all into a
  1644. single byte string.
  1645. @param data: The data to write.
  1646. """
  1647. def loseConnection() -> None:
  1648. """
  1649. Close my connection, after writing all pending data.
  1650. Note that if there is a registered producer on a transport it
  1651. will not be closed until the producer has been unregistered.
  1652. """
  1653. def getPeer() -> IAddress:
  1654. """
  1655. Get the remote address of this connection.
  1656. Treat this method with caution. It is the unfortunate result of the
  1657. CGI and Jabber standards, but should not be considered reliable for
  1658. the usual host of reasons; port forwarding, proxying, firewalls, IP
  1659. masquerading, etc.
  1660. @return: An L{IAddress} provider.
  1661. """
  1662. def getHost() -> IAddress:
  1663. """
  1664. Similar to getPeer, but returns an address describing this side of the
  1665. connection.
  1666. @return: An L{IAddress} provider.
  1667. """
  1668. class ITCPTransport(ITransport):
  1669. """
  1670. A TCP based transport.
  1671. """
  1672. def loseWriteConnection() -> None:
  1673. """
  1674. Half-close the write side of a TCP connection.
  1675. If the protocol instance this is attached to provides
  1676. IHalfCloseableProtocol, it will get notified when the operation is
  1677. done. When closing write connection, as with loseConnection this will
  1678. only happen when buffer has emptied and there is no registered
  1679. producer.
  1680. """
  1681. def abortConnection() -> None:
  1682. """
  1683. Close the connection abruptly.
  1684. Discards any buffered data, stops any registered producer,
  1685. and, if possible, notifies the other end of the unclean
  1686. closure.
  1687. @since: 11.1
  1688. """
  1689. def getTcpNoDelay() -> bool:
  1690. """
  1691. Return if C{TCP_NODELAY} is enabled.
  1692. """
  1693. def setTcpNoDelay(enabled: bool) -> None:
  1694. """
  1695. Enable/disable C{TCP_NODELAY}.
  1696. Enabling C{TCP_NODELAY} turns off Nagle's algorithm. Small packets are
  1697. sent sooner, possibly at the expense of overall throughput.
  1698. """
  1699. def getTcpKeepAlive() -> bool:
  1700. """
  1701. Return if C{SO_KEEPALIVE} is enabled.
  1702. """
  1703. def setTcpKeepAlive(enabled: bool) -> None:
  1704. """
  1705. Enable/disable C{SO_KEEPALIVE}.
  1706. Enabling C{SO_KEEPALIVE} sends packets periodically when the connection
  1707. is otherwise idle, usually once every two hours. They are intended
  1708. to allow detection of lost peers in a non-infinite amount of time.
  1709. """
  1710. def getHost() -> Union["IPv4Address", "IPv6Address"]:
  1711. """
  1712. Returns L{IPv4Address} or L{IPv6Address}.
  1713. """
  1714. def getPeer() -> Union["IPv4Address", "IPv6Address"]:
  1715. """
  1716. Returns L{IPv4Address} or L{IPv6Address}.
  1717. """
  1718. class IUNIXTransport(ITransport):
  1719. """
  1720. Transport for stream-oriented unix domain connections.
  1721. """
  1722. def sendFileDescriptor(descriptor: int) -> None:
  1723. """
  1724. Send a duplicate of this (file, socket, pipe, etc) descriptor to the
  1725. other end of this connection.
  1726. The send is non-blocking and will be queued if it cannot be performed
  1727. immediately. The send will be processed in order with respect to other
  1728. C{sendFileDescriptor} calls on this transport, but not necessarily with
  1729. respect to C{write} calls on this transport. The send can only be
  1730. processed if there are also bytes in the normal connection-oriented send
  1731. buffer (ie, you must call C{write} at least as many times as you call
  1732. C{sendFileDescriptor}).
  1733. @param descriptor: An C{int} giving a valid file descriptor in this
  1734. process. Note that a I{file descriptor} may actually refer to a
  1735. socket, a pipe, or anything else POSIX tries to treat in the same
  1736. way as a file.
  1737. """
  1738. class IOpenSSLServerConnectionCreator(Interface):
  1739. """
  1740. A provider of L{IOpenSSLServerConnectionCreator} can create
  1741. L{OpenSSL.SSL.Connection} objects for TLS servers.
  1742. @see: L{twisted.internet.ssl}
  1743. @note: Creating OpenSSL connection objects is subtle, error-prone, and
  1744. security-critical. Before implementing this interface yourself,
  1745. consider using L{twisted.internet.ssl.CertificateOptions} as your
  1746. C{contextFactory}. (For historical reasons, that class does not
  1747. actually I{implement} this interface; nevertheless it is usable in all
  1748. Twisted APIs which require a provider of this interface.)
  1749. """
  1750. def serverConnectionForTLS(
  1751. tlsProtocol: "TLSMemoryBIOProtocol",
  1752. ) -> "OpenSSLConnection":
  1753. """
  1754. Create a connection for the given server protocol.
  1755. @return: an OpenSSL connection object configured appropriately for the
  1756. given Twisted protocol.
  1757. """
  1758. class IOpenSSLClientConnectionCreator(Interface):
  1759. """
  1760. A provider of L{IOpenSSLClientConnectionCreator} can create
  1761. L{OpenSSL.SSL.Connection} objects for TLS clients.
  1762. @see: L{twisted.internet.ssl}
  1763. @note: Creating OpenSSL connection objects is subtle, error-prone, and
  1764. security-critical. Before implementing this interface yourself,
  1765. consider using L{twisted.internet.ssl.optionsForClientTLS} as your
  1766. C{contextFactory}.
  1767. """
  1768. def clientConnectionForTLS(
  1769. tlsProtocol: "TLSMemoryBIOProtocol",
  1770. ) -> "OpenSSLConnection":
  1771. """
  1772. Create a connection for the given client protocol.
  1773. @param tlsProtocol: the client protocol making the request.
  1774. @return: an OpenSSL connection object configured appropriately for the
  1775. given Twisted protocol.
  1776. """
  1777. class IProtocolNegotiationFactory(Interface):
  1778. """
  1779. A provider of L{IProtocolNegotiationFactory} can provide information about
  1780. the various protocols that the factory can create implementations of. This
  1781. can be used, for example, to provide protocol names for Next Protocol
  1782. Negotiation and Application Layer Protocol Negotiation.
  1783. @see: L{twisted.internet.ssl}
  1784. """
  1785. def acceptableProtocols() -> List[bytes]:
  1786. """
  1787. Returns a list of protocols that can be spoken by the connection
  1788. factory in the form of ALPN tokens, as laid out in the IANA registry
  1789. for ALPN tokens.
  1790. @return: a list of ALPN tokens in order of preference.
  1791. """
  1792. class IOpenSSLContextFactory(Interface):
  1793. """
  1794. A provider of L{IOpenSSLContextFactory} is capable of generating
  1795. L{OpenSSL.SSL.Context} classes suitable for configuring TLS on a
  1796. connection. A provider will store enough state to be able to generate these
  1797. contexts as needed for individual connections.
  1798. @see: L{twisted.internet.ssl}
  1799. """
  1800. def getContext() -> "OpenSSLContext":
  1801. """
  1802. Returns a TLS context object, suitable for securing a TLS connection.
  1803. This context object will be appropriately customized for the connection
  1804. based on the state in this object.
  1805. @return: A TLS context object.
  1806. """
  1807. class ITLSTransport(ITCPTransport):
  1808. """
  1809. A TCP transport that supports switching to TLS midstream.
  1810. Once TLS mode is started the transport will implement L{ISSLTransport}.
  1811. """
  1812. def startTLS(
  1813. contextFactory: Union[
  1814. IOpenSSLClientConnectionCreator, IOpenSSLServerConnectionCreator
  1815. ]
  1816. ) -> None:
  1817. """
  1818. Initiate TLS negotiation.
  1819. @param contextFactory: An object which creates appropriately configured
  1820. TLS connections.
  1821. For clients, use L{twisted.internet.ssl.optionsForClientTLS}; for
  1822. servers, use L{twisted.internet.ssl.CertificateOptions}.
  1823. @type contextFactory: L{IOpenSSLClientConnectionCreator} or
  1824. L{IOpenSSLServerConnectionCreator}, depending on whether this
  1825. L{ITLSTransport} is a server or not. If the appropriate interface
  1826. is not provided by the value given for C{contextFactory}, it must
  1827. be an implementor of L{IOpenSSLContextFactory}.
  1828. """
  1829. class ISSLTransport(ITCPTransport):
  1830. """
  1831. A SSL/TLS based transport.
  1832. """
  1833. def getPeerCertificate() -> object:
  1834. """
  1835. Return an object with the peer's certificate info.
  1836. """
  1837. class INegotiated(ISSLTransport):
  1838. """
  1839. A TLS based transport that supports using ALPN/NPN to negotiate the
  1840. protocol to be used inside the encrypted tunnel.
  1841. """
  1842. negotiatedProtocol = Attribute(
  1843. """
  1844. The protocol selected to be spoken using ALPN/NPN. The result from ALPN
  1845. is preferred to the result from NPN if both were used. If the remote
  1846. peer does not support ALPN or NPN, or neither NPN or ALPN are available
  1847. on this machine, will be L{None}. Otherwise, will be the name of the
  1848. selected protocol as C{bytes}. Note that until the handshake has
  1849. completed this property may incorrectly return L{None}: wait until data
  1850. has been received before trusting it (see
  1851. https://twistedmatrix.com/trac/ticket/6024).
  1852. """
  1853. )
  1854. class ICipher(Interface):
  1855. """
  1856. A TLS cipher.
  1857. """
  1858. fullName = Attribute("The fully qualified name of the cipher in L{unicode}.")
  1859. class IAcceptableCiphers(Interface):
  1860. """
  1861. A list of acceptable ciphers for a TLS context.
  1862. """
  1863. def selectCiphers(availableCiphers: Tuple[ICipher]) -> Tuple[ICipher]:
  1864. """
  1865. Choose which ciphers to allow to be negotiated on a TLS connection.
  1866. @param availableCiphers: A L{tuple} of L{ICipher} which gives the names
  1867. of all ciphers supported by the TLS implementation in use.
  1868. @return: A L{tuple} of L{ICipher} which represents the ciphers
  1869. which may be negotiated on the TLS connection. The result is
  1870. ordered by preference with more preferred ciphers appearing
  1871. earlier.
  1872. """
  1873. class IProcessTransport(ITransport):
  1874. """
  1875. A process transport.
  1876. """
  1877. pid = Attribute(
  1878. "From before L{IProcessProtocol.makeConnection} is called to before "
  1879. "L{IProcessProtocol.processEnded} is called, C{pid} is an L{int} "
  1880. "giving the platform process ID of this process. C{pid} is L{None} "
  1881. "at all other times."
  1882. )
  1883. def closeStdin() -> None:
  1884. """
  1885. Close stdin after all data has been written out.
  1886. """
  1887. def closeStdout() -> None:
  1888. """
  1889. Close stdout.
  1890. """
  1891. def closeStderr() -> None:
  1892. """
  1893. Close stderr.
  1894. """
  1895. def closeChildFD(descriptor: int) -> None:
  1896. """
  1897. Close a file descriptor which is connected to the child process, identified
  1898. by its FD in the child process.
  1899. """
  1900. def writeToChild(childFD: int, data: bytes) -> None:
  1901. """
  1902. Similar to L{ITransport.write} but also allows the file descriptor in
  1903. the child process which will receive the bytes to be specified.
  1904. @param childFD: The file descriptor to which to write.
  1905. @param data: The bytes to write.
  1906. @raise KeyError: If C{childFD} is not a file descriptor that was mapped
  1907. in the child when L{IReactorProcess.spawnProcess} was used to create
  1908. it.
  1909. """
  1910. def loseConnection() -> None:
  1911. """
  1912. Close stdin, stderr and stdout.
  1913. """
  1914. def signalProcess(signalID: Union[str, int]) -> None:
  1915. """
  1916. Send a signal to the process.
  1917. @param signalID: can be
  1918. - one of C{"KILL"}, C{"TERM"}, or C{"INT"}.
  1919. These will be implemented in a
  1920. cross-platform manner, and so should be used
  1921. if possible.
  1922. - an integer, where it represents a POSIX
  1923. signal ID.
  1924. @raise twisted.internet.error.ProcessExitedAlready: If the process has
  1925. already exited.
  1926. @raise OSError: If the C{os.kill} call fails with an errno different
  1927. from C{ESRCH}.
  1928. """
  1929. class IServiceCollection(Interface):
  1930. """
  1931. An object which provides access to a collection of services.
  1932. """
  1933. def getServiceNamed(serviceName: str) -> object:
  1934. """
  1935. Retrieve the named service from this application.
  1936. Raise a C{KeyError} if there is no such service name.
  1937. """
  1938. def addService(service: object) -> None:
  1939. """
  1940. Add a service to this collection.
  1941. """
  1942. def removeService(service: object) -> None:
  1943. """
  1944. Remove a service from this collection.
  1945. """
  1946. class IUDPTransport(Interface):
  1947. """
  1948. Transport for UDP DatagramProtocols.
  1949. """
  1950. def write(packet: bytes, addr: Optional[Tuple[str, int]]) -> None:
  1951. """
  1952. Write packet to given address.
  1953. @param addr: a tuple of (ip, port). For connected transports must
  1954. be the address the transport is connected to, or None.
  1955. In non-connected mode this is mandatory.
  1956. @raise twisted.internet.error.MessageLengthError: C{packet} was too
  1957. long.
  1958. """
  1959. def connect(host: str, port: int) -> None:
  1960. """
  1961. Connect the transport to an address.
  1962. This changes it to connected mode. Datagrams can only be sent to
  1963. this address, and will only be received from this address. In addition
  1964. the protocol's connectionRefused method might get called if destination
  1965. is not receiving datagrams.
  1966. @param host: an IP address, not a domain name ('127.0.0.1', not 'localhost')
  1967. @param port: port to connect to.
  1968. """
  1969. def getHost() -> Union["IPv4Address", "IPv6Address"]:
  1970. """
  1971. Get this port's host address.
  1972. @return: an address describing the listening port.
  1973. """
  1974. def stopListening() -> Optional["Deferred[None]"]:
  1975. """
  1976. Stop listening on this port.
  1977. If it does not complete immediately, will return L{Deferred} that fires
  1978. upon completion.
  1979. """
  1980. def setBroadcastAllowed(enabled: bool) -> None:
  1981. """
  1982. Set whether this port may broadcast.
  1983. @param enabled: Whether the port may broadcast.
  1984. """
  1985. def getBroadcastAllowed() -> bool:
  1986. """
  1987. Checks if broadcast is currently allowed on this port.
  1988. @return: Whether this port may broadcast.
  1989. """
  1990. class IUNIXDatagramTransport(Interface):
  1991. """
  1992. Transport for UDP PacketProtocols.
  1993. """
  1994. def write(packet: bytes, addr: str) -> None:
  1995. """
  1996. Write packet to given address.
  1997. """
  1998. def getHost() -> "UNIXAddress":
  1999. """
  2000. Returns L{UNIXAddress}.
  2001. """
  2002. class IUNIXDatagramConnectedTransport(Interface):
  2003. """
  2004. Transport for UDP ConnectedPacketProtocols.
  2005. """
  2006. def write(packet: bytes) -> None:
  2007. """
  2008. Write packet to address we are connected to.
  2009. """
  2010. def getHost() -> "UNIXAddress":
  2011. """
  2012. Returns L{UNIXAddress}.
  2013. """
  2014. def getPeer() -> "UNIXAddress":
  2015. """
  2016. Returns L{UNIXAddress}.
  2017. """
  2018. class IMulticastTransport(Interface):
  2019. """
  2020. Additional functionality for multicast UDP.
  2021. """
  2022. def getOutgoingInterface() -> str:
  2023. """
  2024. Return interface of outgoing multicast packets.
  2025. """
  2026. def setOutgoingInterface(addr: str) -> None:
  2027. """
  2028. Set interface for outgoing multicast packets.
  2029. Returns Deferred of success.
  2030. """
  2031. def getLoopbackMode() -> bool:
  2032. """
  2033. Return if loopback mode is enabled.
  2034. """
  2035. def setLoopbackMode(mode: bool) -> None:
  2036. """
  2037. Set if loopback mode is enabled.
  2038. """
  2039. def getTTL() -> int:
  2040. """
  2041. Get time to live for multicast packets.
  2042. """
  2043. def setTTL(ttl: int) -> None:
  2044. """
  2045. Set time to live on multicast packets.
  2046. """
  2047. def joinGroup(addr: str, interface: str) -> "Deferred[None]":
  2048. """
  2049. Join a multicast group. Returns L{Deferred} of success or failure.
  2050. If an error occurs, the returned L{Deferred} will fail with
  2051. L{error.MulticastJoinError}.
  2052. """
  2053. def leaveGroup(addr: str, interface: str) -> "Deferred[None]":
  2054. """
  2055. Leave multicast group, return L{Deferred} of success.
  2056. """
  2057. class IStreamClientEndpoint(Interface):
  2058. """
  2059. A stream client endpoint is a place that L{ClientFactory} can connect to.
  2060. For example, a remote TCP host/port pair would be a TCP client endpoint.
  2061. @since: 10.1
  2062. """
  2063. def connect(protocolFactory: IProtocolFactory) -> "Deferred[IProtocol]":
  2064. """
  2065. Connect the C{protocolFactory} to the location specified by this
  2066. L{IStreamClientEndpoint} provider.
  2067. @param protocolFactory: A provider of L{IProtocolFactory}
  2068. @return: A L{Deferred} that results in an L{IProtocol} upon successful
  2069. connection otherwise a L{Failure} wrapping L{ConnectError} or
  2070. L{NoProtocol <twisted.internet.error.NoProtocol>}.
  2071. """
  2072. class IStreamServerEndpoint(Interface):
  2073. """
  2074. A stream server endpoint is a place that a L{Factory} can listen for
  2075. incoming connections.
  2076. @since: 10.1
  2077. """
  2078. def listen(protocolFactory: IProtocolFactory) -> "Deferred[IListeningPort]":
  2079. """
  2080. Listen with C{protocolFactory} at the location specified by this
  2081. L{IStreamServerEndpoint} provider.
  2082. @param protocolFactory: A provider of L{IProtocolFactory}
  2083. @return: A L{Deferred} that results in an L{IListeningPort} or an
  2084. L{CannotListenError}
  2085. """
  2086. class IStreamServerEndpointStringParser(Interface):
  2087. """
  2088. An L{IStreamServerEndpointStringParser} is like an
  2089. L{IStreamClientEndpointStringParserWithReactor}, except for
  2090. L{IStreamServerEndpoint}s instead of clients. It integrates with
  2091. L{endpoints.serverFromString} in much the same way.
  2092. """
  2093. prefix = Attribute(
  2094. """
  2095. A C{str}, the description prefix to respond to. For example, an
  2096. L{IStreamServerEndpointStringParser} plugin which had C{"foo"} for its
  2097. C{prefix} attribute would be called for endpoint descriptions like
  2098. C{"foo:bar:baz"} or C{"foo:"}.
  2099. """
  2100. )
  2101. def parseStreamServer(
  2102. reactor: IReactorCore, *args: object, **kwargs: object
  2103. ) -> IStreamServerEndpoint:
  2104. """
  2105. Parse a stream server endpoint from a reactor and string-only arguments
  2106. and keyword arguments.
  2107. @see: L{IStreamClientEndpointStringParserWithReactor.parseStreamClient}
  2108. @return: a stream server endpoint
  2109. """
  2110. class IStreamClientEndpointStringParserWithReactor(Interface):
  2111. """
  2112. An L{IStreamClientEndpointStringParserWithReactor} is a parser which can
  2113. convert a set of string C{*args} and C{**kwargs} into an
  2114. L{IStreamClientEndpoint} provider.
  2115. This interface is really only useful in the context of the plugin system
  2116. for L{endpoints.clientFromString}. See the document entitled "I{The
  2117. Twisted Plugin System}" for more details on how to write a plugin.
  2118. If you place an L{IStreamClientEndpointStringParserWithReactor} plugin in
  2119. the C{twisted.plugins} package, that plugin's C{parseStreamClient} method
  2120. will be used to produce endpoints for any description string that begins
  2121. with the result of that L{IStreamClientEndpointStringParserWithReactor}'s
  2122. prefix attribute.
  2123. """
  2124. prefix = Attribute(
  2125. """
  2126. L{bytes}, the description prefix to respond to. For example, an
  2127. L{IStreamClientEndpointStringParserWithReactor} plugin which had
  2128. C{b"foo"} for its C{prefix} attribute would be called for endpoint
  2129. descriptions like C{b"foo:bar:baz"} or C{b"foo:"}.
  2130. """
  2131. )
  2132. def parseStreamClient(
  2133. reactor: IReactorCore, *args: object, **kwargs: object
  2134. ) -> IStreamClientEndpoint:
  2135. """
  2136. This method is invoked by L{endpoints.clientFromString}, if the type of
  2137. endpoint matches the return value from this
  2138. L{IStreamClientEndpointStringParserWithReactor}'s C{prefix} method.
  2139. @param reactor: The reactor passed to L{endpoints.clientFromString}.
  2140. @param args: The byte string arguments, minus the endpoint type, in the
  2141. endpoint description string, parsed according to the rules
  2142. described in L{endpoints.quoteStringArgument}. For example, if the
  2143. description were C{b"my-type:foo:bar:baz=qux"}, C{args} would be
  2144. C{(b'foo', b'bar')}
  2145. @param kwargs: The byte string arguments from the endpoint description
  2146. passed as keyword arguments. For example, if the description were
  2147. C{b"my-type:foo:bar:baz=qux"}, C{kwargs} would be
  2148. C{dict(baz=b'qux')}.
  2149. @return: a client endpoint
  2150. """
  2151. class _ISupportsExitSignalCapturing(Interface):
  2152. """
  2153. An implementor of L{_ISupportsExitSignalCapturing} will capture the
  2154. value of any delivered exit signal (SIGINT, SIGTERM, SIGBREAK) for which
  2155. it has installed a handler. The caught signal number is made available in
  2156. the _exitSignal attribute.
  2157. """
  2158. _exitSignal = Attribute(
  2159. """
  2160. C{int} or C{None}, the integer exit signal delivered to the
  2161. application, or None if no signal was delivered.
  2162. """
  2163. )