interfaces.py 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799
  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,
  568. factory: "ServerFactory",
  569. backlog: int = 50,
  570. interface: str = "",
  571. ) -> "IListeningPort":
  572. """
  573. Connects a given protocol factory to the given numeric TCP/IP port.
  574. @param port: a port number on which to listen
  575. @param factory: a L{twisted.internet.protocol.ServerFactory} instance
  576. @param backlog: size of the listen queue
  577. @param interface: The local IPv4 or IPv6 address to which to bind;
  578. defaults to '', ie all IPv4 addresses. To bind to all IPv4 and IPv6
  579. addresses, you must call this method twice.
  580. @return: an object that provides L{IListeningPort}.
  581. @raise CannotListenError: as defined here
  582. L{twisted.internet.error.CannotListenError},
  583. if it cannot listen on this port (e.g., it
  584. cannot bind to the required port number)
  585. """
  586. def connectTCP(
  587. host: str,
  588. port: int,
  589. factory: "ClientFactory",
  590. timeout: float = 30.0,
  591. bindAddress: Optional[Tuple[str, int]] = None,
  592. ) -> IConnector:
  593. """
  594. Connect a TCP client.
  595. @param host: A hostname or an IPv4 or IPv6 address literal.
  596. @param port: a port number
  597. @param factory: a L{twisted.internet.protocol.ClientFactory} instance
  598. @param timeout: number of seconds to wait before assuming the
  599. connection has failed.
  600. @param bindAddress: a (host, port) tuple of local address to bind
  601. to, or None.
  602. @return: An object which provides L{IConnector}. This connector will
  603. call various callbacks on the factory when a connection is
  604. made, failed, or lost - see
  605. L{ClientFactory<twisted.internet.protocol.ClientFactory>}
  606. docs for details.
  607. """
  608. class IReactorSSL(Interface):
  609. def connectSSL(
  610. host: str,
  611. port: int,
  612. factory: "ClientFactory",
  613. contextFactory: "ClientContextFactory",
  614. timeout: float,
  615. bindAddress: Optional[Tuple[str, int]],
  616. ) -> IConnector:
  617. """
  618. Connect a client Protocol to a remote SSL socket.
  619. @param host: a host name
  620. @param port: a port number
  621. @param factory: a L{twisted.internet.protocol.ClientFactory} instance
  622. @param contextFactory: a L{twisted.internet.ssl.ClientContextFactory} object.
  623. @param timeout: number of seconds to wait before assuming the
  624. connection has failed.
  625. @param bindAddress: a (host, port) tuple of local address to bind to,
  626. or L{None}.
  627. @return: An object which provides L{IConnector}.
  628. """
  629. def listenSSL(
  630. port: int,
  631. factory: "ServerFactory",
  632. contextFactory: "IOpenSSLContextFactory",
  633. backlog: int,
  634. interface: str,
  635. ) -> "IListeningPort":
  636. """
  637. Connects a given protocol factory to the given numeric TCP/IP port.
  638. The connection is a SSL one, using contexts created by the context
  639. factory.
  640. @param port: a port number on which to listen
  641. @param factory: a L{twisted.internet.protocol.ServerFactory} instance
  642. @param contextFactory: an implementor of L{IOpenSSLContextFactory}
  643. @param backlog: size of the listen queue
  644. @param interface: the hostname to bind to, defaults to '' (all)
  645. """
  646. class IReactorUNIX(Interface):
  647. """
  648. UNIX socket methods.
  649. """
  650. def connectUNIX(
  651. address: str,
  652. factory: "ClientFactory",
  653. timeout: float = 30,
  654. checkPID: bool = False,
  655. ) -> IConnector:
  656. """
  657. Connect a client protocol to a UNIX socket.
  658. @param address: a path to a unix socket on the filesystem.
  659. @param factory: a L{twisted.internet.protocol.ClientFactory} instance
  660. @param timeout: number of seconds to wait before assuming the connection
  661. has failed.
  662. @param checkPID: if True, check for a pid file to verify that a server
  663. is listening. If C{address} is a Linux abstract namespace path,
  664. this must be C{False}.
  665. @return: An object which provides L{IConnector}.
  666. """
  667. def listenUNIX(
  668. address: str,
  669. factory: "Factory",
  670. backlog: int = 50,
  671. mode: int = 0o666,
  672. wantPID: bool = False,
  673. ) -> "IListeningPort":
  674. """
  675. Listen on a UNIX socket.
  676. @param address: a path to a unix socket on the filesystem.
  677. @param factory: a L{twisted.internet.protocol.Factory} instance.
  678. @param backlog: number of connections to allow in backlog.
  679. @param mode: The mode (B{not} umask) to set on the unix socket. See
  680. platform specific documentation for information about how this
  681. might affect connection attempts.
  682. @param wantPID: if True, create a pidfile for the socket. If C{address}
  683. is a Linux abstract namespace path, this must be C{False}.
  684. @return: An object which provides L{IListeningPort}.
  685. """
  686. class IReactorUNIXDatagram(Interface):
  687. """
  688. Datagram UNIX socket methods.
  689. """
  690. def connectUNIXDatagram(
  691. address: str,
  692. protocol: "ConnectedDatagramProtocol",
  693. maxPacketSize: int,
  694. mode: int,
  695. bindAddress: Optional[Tuple[str, int]],
  696. ) -> IConnector:
  697. """
  698. Connect a client protocol to a datagram UNIX socket.
  699. @param address: a path to a unix socket on the filesystem.
  700. @param protocol: a L{twisted.internet.protocol.ConnectedDatagramProtocol} instance
  701. @param maxPacketSize: maximum packet size to accept
  702. @param mode: The mode (B{not} umask) to set on the unix socket. See
  703. platform specific documentation for information about how this
  704. might affect connection attempts.
  705. @param bindAddress: address to bind to
  706. @return: An object which provides L{IConnector}.
  707. """
  708. def listenUNIXDatagram(
  709. address: str, protocol: "DatagramProtocol", maxPacketSize: int, mode: int
  710. ) -> "IListeningPort":
  711. """
  712. Listen on a datagram UNIX socket.
  713. @param address: a path to a unix socket on the filesystem.
  714. @param protocol: a L{twisted.internet.protocol.DatagramProtocol} instance.
  715. @param maxPacketSize: maximum packet size to accept
  716. @param mode: The mode (B{not} umask) to set on the unix socket. See
  717. platform specific documentation for information about how this
  718. might affect connection attempts.
  719. @return: An object which provides L{IListeningPort}.
  720. """
  721. class IReactorWin32Events(Interface):
  722. """
  723. Win32 Event API methods
  724. @since: 10.2
  725. """
  726. def addEvent(event: object, fd: "FileDescriptor", action: str) -> None:
  727. """
  728. Add a new win32 event to the event loop.
  729. @param event: a Win32 event object created using win32event.CreateEvent()
  730. @param fd: an instance of L{twisted.internet.abstract.FileDescriptor}
  731. @param action: a string that is a method name of the fd instance.
  732. This method is called in response to the event.
  733. """
  734. def removeEvent(event: object) -> None:
  735. """
  736. Remove an event.
  737. @param event: a Win32 event object added using L{IReactorWin32Events.addEvent}
  738. @return: None
  739. """
  740. class IReactorUDP(Interface):
  741. """
  742. UDP socket methods.
  743. """
  744. def listenUDP(
  745. port: int, protocol: "DatagramProtocol", interface: str, maxPacketSize: int
  746. ) -> "IListeningPort":
  747. """
  748. Connects a given L{DatagramProtocol} to the given numeric UDP port.
  749. @param port: A port number on which to listen.
  750. @param protocol: A L{DatagramProtocol} instance which will be
  751. connected to the given C{port}.
  752. @param interface: The local IPv4 or IPv6 address to which to bind;
  753. defaults to '', ie all IPv4 addresses.
  754. @param maxPacketSize: The maximum packet size to accept.
  755. @return: object which provides L{IListeningPort}.
  756. """
  757. class IReactorMulticast(Interface):
  758. """
  759. UDP socket methods that support multicast.
  760. IMPORTANT: This is an experimental new interface. It may change
  761. without backwards compatibility. Suggestions are welcome.
  762. """
  763. def listenMulticast(
  764. port: int,
  765. protocol: "DatagramProtocol",
  766. interface: str = "",
  767. maxPacketSize: int = 8192,
  768. listenMultiple: bool = False,
  769. ) -> IMulticastTransport:
  770. """
  771. Connects a given
  772. L{DatagramProtocol<twisted.internet.protocol.DatagramProtocol>} to the
  773. given numeric UDP port.
  774. @param port: The port number to bind to.
  775. @param protocol: the datagram receiver that will receive multicast
  776. packets sent to the given interface and port.
  777. @param interface: The IP address literal of the network interface to
  778. bind to. By default, this will be C{"0.0.0.0"}, i.e. all IPv4
  779. interfaces. Note that the format of this literal determines the
  780. address family of the resulting multicast transport: passing an
  781. IPv6 literal, such as C{"::"}, will result in an IPv6 multicast
  782. transport.
  783. @param maxPacketSize: The maximum packet size to accept.
  784. @param listenMultiple: If set to True, allows multiple sockets to bind
  785. to the same address and port number at the same time.
  786. @returns: An L{IMulticastTransport} that can send multicast traffic to
  787. C{interface}.
  788. @see: U{http://twistedmatrix.com/documents/current/core/howto/udp.html}
  789. """
  790. class IReactorSocket(Interface):
  791. """
  792. Methods which allow a reactor to use externally created sockets.
  793. For example, to use C{adoptStreamPort} to implement behavior equivalent
  794. to that of L{IReactorTCP.listenTCP}, you might write code like this::
  795. from socket import SOMAXCONN, AF_INET, SOCK_STREAM, socket
  796. portSocket = socket(AF_INET, SOCK_STREAM)
  797. # Set FD_CLOEXEC on port, left as an exercise. Then make it into a
  798. # non-blocking listening port:
  799. portSocket.setblocking(False)
  800. portSocket.bind(('192.168.1.2', 12345))
  801. portSocket.listen(SOMAXCONN)
  802. # Now have the reactor use it as a TCP port
  803. port = reactor.adoptStreamPort(
  804. portSocket.fileno(), AF_INET, YourFactory())
  805. # portSocket itself is no longer necessary, and needs to be cleaned
  806. # up by us.
  807. portSocket.close()
  808. # Whenever the server is no longer needed, stop it as usual.
  809. stoppedDeferred = port.stopListening()
  810. Another potential use is to inherit a listening descriptor from a parent
  811. process (for example, systemd or launchd), or to receive one over a UNIX
  812. domain socket.
  813. Some plans for extending this interface exist. See:
  814. - U{http://twistedmatrix.com/trac/ticket/6594}: AF_UNIX SOCK_DGRAM ports
  815. """
  816. def adoptStreamPort(
  817. fileDescriptor: int, addressFamily: "AddressFamily", factory: "ServerFactory"
  818. ) -> "IListeningPort":
  819. """
  820. Add an existing listening I{SOCK_STREAM} socket to the reactor to
  821. monitor for new connections to accept and handle.
  822. @param fileDescriptor: A file descriptor associated with a socket which
  823. is already bound to an address and marked as listening. The socket
  824. must be set non-blocking. Any additional flags (for example,
  825. close-on-exec) must also be set by application code. Application
  826. code is responsible for closing the file descriptor, which may be
  827. done as soon as C{adoptStreamPort} returns.
  828. @param addressFamily: The address family (or I{domain}) of the socket.
  829. For example, L{socket.AF_INET6}.
  830. @param factory: A L{ServerFactory} instance to use to create new
  831. protocols to handle connections accepted via this socket.
  832. @return: An object providing L{IListeningPort}.
  833. @raise twisted.internet.error.UnsupportedAddressFamily: If the
  834. given address family is not supported by this reactor, or
  835. not supported with the given socket type.
  836. @raise twisted.internet.error.UnsupportedSocketType: If the
  837. given socket type is not supported by this reactor, or not
  838. supported with the given socket type.
  839. """
  840. def adoptStreamConnection(
  841. fileDescriptor: int, addressFamily: "AddressFamily", factory: "ServerFactory"
  842. ) -> None:
  843. """
  844. Add an existing connected I{SOCK_STREAM} socket to the reactor to
  845. monitor for data.
  846. Note that the given factory won't have its C{startFactory} and
  847. C{stopFactory} methods called, as there is no sensible time to call
  848. them in this situation.
  849. @param fileDescriptor: A file descriptor associated with a socket which
  850. is already connected. The socket must be set non-blocking. Any
  851. additional flags (for example, close-on-exec) must also be set by
  852. application code. Application code is responsible for closing the
  853. file descriptor, which may be done as soon as
  854. C{adoptStreamConnection} returns.
  855. @param addressFamily: The address family (or I{domain}) of the socket.
  856. For example, L{socket.AF_INET6}.
  857. @param factory: A L{ServerFactory} instance to use to create a new
  858. protocol to handle the connection via this socket.
  859. @raise UnsupportedAddressFamily: If the given address family is not
  860. supported by this reactor, or not supported with the given socket
  861. type.
  862. @raise UnsupportedSocketType: If the given socket type is not supported
  863. by this reactor, or not supported with the given socket type.
  864. """
  865. def adoptDatagramPort(
  866. fileDescriptor: int,
  867. addressFamily: "AddressFamily",
  868. protocol: "DatagramProtocol",
  869. maxPacketSize: int,
  870. ) -> "IListeningPort":
  871. """
  872. Add an existing listening I{SOCK_DGRAM} socket to the reactor to
  873. monitor for read and write readiness.
  874. @param fileDescriptor: A file descriptor associated with a socket which
  875. is already bound to an address and marked as listening. The socket
  876. must be set non-blocking. Any additional flags (for example,
  877. close-on-exec) must also be set by application code. Application
  878. code is responsible for closing the file descriptor, which may be
  879. done as soon as C{adoptDatagramPort} returns.
  880. @param addressFamily: The address family or I{domain} of the socket.
  881. For example, L{socket.AF_INET6}.
  882. @param protocol: A L{DatagramProtocol} instance to connect to
  883. a UDP transport.
  884. @param maxPacketSize: The maximum packet size to accept.
  885. @return: An object providing L{IListeningPort}.
  886. @raise UnsupportedAddressFamily: If the given address family is not
  887. supported by this reactor, or not supported with the given socket
  888. type.
  889. @raise UnsupportedSocketType: If the given socket type is not supported
  890. by this reactor, or not supported with the given socket type.
  891. """
  892. class IReactorProcess(Interface):
  893. def spawnProcess(
  894. processProtocol: "IProcessProtocol",
  895. executable: Union[bytes, str],
  896. args: Sequence[Union[bytes, str]],
  897. env: Optional[Mapping[AnyStr, AnyStr]] = None,
  898. path: Union[None, bytes, str] = None,
  899. uid: Optional[int] = None,
  900. gid: Optional[int] = None,
  901. usePTY: bool = False,
  902. childFDs: Optional[Mapping[int, Union[int, str]]] = None,
  903. ) -> "IProcessTransport":
  904. """
  905. Spawn a process, with a process protocol.
  906. Arguments given to this function that are listed as L{bytes} or
  907. L{unicode} may be encoded or decoded depending on the platform and the
  908. argument type given. On UNIX systems (Linux, FreeBSD, macOS) and
  909. Python 2 on Windows, L{unicode} arguments will be encoded down to
  910. L{bytes} using the encoding given by L{sys.getfilesystemencoding}, to be
  911. used with the "narrow" OS APIs. On Python 3 on Windows, L{bytes}
  912. arguments will be decoded up to L{unicode} using the encoding given by
  913. L{sys.getfilesystemencoding} (C{utf8}) and given to Windows's native "wide" APIs.
  914. @param processProtocol: An object which will be notified of all events
  915. related to the created process.
  916. @param executable: the file name to spawn - the full path should be
  917. used.
  918. @param args: the command line arguments to pass to the process; a
  919. sequence of strings. The first string should be the executable's
  920. name.
  921. @param env: the environment variables to pass to the child process.
  922. The resulting behavior varies between platforms. If:
  923. - C{env} is not set:
  924. - On POSIX: pass an empty environment.
  925. - On Windows: pass L{os.environ}.
  926. - C{env} is L{None}:
  927. - On POSIX: pass L{os.environ}.
  928. - On Windows: pass L{os.environ}.
  929. - C{env} is a L{dict}:
  930. - On POSIX: pass the key/value pairs in C{env} as the
  931. complete environment.
  932. - On Windows: update L{os.environ} with the key/value
  933. pairs in the L{dict} before passing it. As a
  934. consequence of U{bug #1640
  935. <http://twistedmatrix.com/trac/ticket/1640>}, passing
  936. keys with empty values in an effort to unset
  937. environment variables I{won't} unset them.
  938. @param path: the path to run the subprocess in - defaults to the
  939. current directory.
  940. @param uid: user ID to run the subprocess as. (Only available on POSIX
  941. systems.)
  942. @param gid: group ID to run the subprocess as. (Only available on
  943. POSIX systems.)
  944. @param usePTY: if true, run this process in a pseudo-terminal.
  945. optionally a tuple of C{(masterfd, slavefd, ttyname)}, in which
  946. case use those file descriptors. (Not available on all systems.)
  947. @param childFDs: A dictionary mapping file descriptors in the new child
  948. process to an integer or to the string 'r' or 'w'.
  949. If the value is an integer, it specifies a file descriptor in the
  950. parent process which will be mapped to a file descriptor (specified
  951. by the key) in the child process. This is useful for things like
  952. inetd and shell-like file redirection.
  953. If it is the string 'r', a pipe will be created and attached to the
  954. child at that file descriptor: the child will be able to write to
  955. that file descriptor and the parent will receive read notification
  956. via the L{IProcessProtocol.childDataReceived} callback. This is
  957. useful for the child's stdout and stderr.
  958. If it is the string 'w', similar setup to the previous case will
  959. occur, with the pipe being readable by the child instead of
  960. writeable. The parent process can write to that file descriptor
  961. using L{IProcessTransport.writeToChild}. This is useful for the
  962. child's stdin.
  963. If childFDs is not passed, the default behaviour is to use a
  964. mapping that opens the usual stdin/stdout/stderr pipes.
  965. @see: L{twisted.internet.protocol.ProcessProtocol}
  966. @return: An object which provides L{IProcessTransport}.
  967. @raise OSError: Raised with errno C{EAGAIN} or C{ENOMEM} if there are
  968. insufficient system resources to create a new process.
  969. """
  970. class IReactorTime(Interface):
  971. """
  972. Time methods that a Reactor should implement.
  973. """
  974. def seconds() -> float:
  975. """
  976. Get the current time in seconds.
  977. @return: A number-like object of some sort.
  978. """
  979. def callLater(
  980. delay: float, callable: Callable[..., Any], *args: object, **kwargs: object
  981. ) -> "IDelayedCall":
  982. """
  983. Call a function later.
  984. @param delay: the number of seconds to wait.
  985. @param callable: the callable object to call later.
  986. @param args: the arguments to call it with.
  987. @param kwargs: the keyword arguments to call it with.
  988. @return: An object which provides L{IDelayedCall} and can be used to
  989. cancel the scheduled call, by calling its C{cancel()} method.
  990. It also may be rescheduled by calling its C{delay()} or
  991. C{reset()} methods.
  992. """
  993. def getDelayedCalls() -> Sequence["IDelayedCall"]:
  994. """
  995. See L{twisted.internet.interfaces.IReactorTime.getDelayedCalls}
  996. """
  997. class IDelayedCall(Interface):
  998. """
  999. A scheduled call.
  1000. There are probably other useful methods we can add to this interface;
  1001. suggestions are welcome.
  1002. """
  1003. def getTime() -> float:
  1004. """
  1005. Get time when delayed call will happen.
  1006. @return: time in seconds since epoch (a float).
  1007. """
  1008. def cancel() -> None:
  1009. """
  1010. Cancel the scheduled call.
  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 delay(secondsLater: float) -> None:
  1017. """
  1018. Delay the scheduled call.
  1019. @param secondsLater: how many seconds from its current firing time to delay
  1020. @raises twisted.internet.error.AlreadyCalled: if the call has already
  1021. happened.
  1022. @raises twisted.internet.error.AlreadyCancelled: if the call has already
  1023. been cancelled.
  1024. """
  1025. def reset(secondsFromNow: float) -> None:
  1026. """
  1027. Reset the scheduled call's timer.
  1028. @param secondsFromNow: how many seconds from now it should fire,
  1029. equivalent to C{.cancel()} and then doing another
  1030. C{reactor.callLater(secondsLater, ...)}
  1031. @raises twisted.internet.error.AlreadyCalled: if the call has already
  1032. happened.
  1033. @raises twisted.internet.error.AlreadyCancelled: if the call has already
  1034. been cancelled.
  1035. """
  1036. def active() -> bool:
  1037. """
  1038. @return: True if this call is still active, False if it has been
  1039. called or cancelled.
  1040. """
  1041. class IReactorFromThreads(Interface):
  1042. """
  1043. This interface is the set of thread-safe methods which may be invoked on
  1044. the reactor from other threads.
  1045. @since: 15.4
  1046. """
  1047. def callFromThread(
  1048. callable: Callable[..., Any], *args: object, **kwargs: object
  1049. ) -> None:
  1050. """
  1051. Cause a function to be executed by the reactor thread.
  1052. Use this method when you want to run a function in the reactor's thread
  1053. from another thread. Calling L{callFromThread} should wake up the main
  1054. thread (where L{reactor.run() <IReactorCore.run>} is executing) and run
  1055. the given callable in that thread.
  1056. If you're writing a multi-threaded application the C{callable}
  1057. may need to be thread safe, but this method doesn't require it as such.
  1058. If you want to call a function in the next mainloop iteration, but
  1059. you're in the same thread, use L{callLater} with a delay of 0.
  1060. """
  1061. class IReactorInThreads(Interface):
  1062. """
  1063. This interface contains the methods exposed by a reactor which will let you
  1064. run functions in another thread.
  1065. @since: 15.4
  1066. """
  1067. def callInThread(
  1068. callable: Callable[..., Any], *args: object, **kwargs: object
  1069. ) -> None:
  1070. """
  1071. Run the given callable object in a separate thread, with the given
  1072. arguments and keyword arguments.
  1073. """
  1074. class IReactorThreads(IReactorFromThreads, IReactorInThreads):
  1075. """
  1076. Dispatch methods to be run in threads.
  1077. Internally, this should use a thread pool and dispatch methods to them.
  1078. """
  1079. def getThreadPool() -> "ThreadPool":
  1080. """
  1081. Return the threadpool used by L{IReactorInThreads.callInThread}.
  1082. Create it first if necessary.
  1083. """
  1084. def suggestThreadPoolSize(size: int) -> None:
  1085. """
  1086. Suggest the size of the internal threadpool used to dispatch functions
  1087. passed to L{IReactorInThreads.callInThread}.
  1088. """
  1089. class IReactorCore(Interface):
  1090. """
  1091. Core methods that a Reactor must implement.
  1092. """
  1093. running = Attribute(
  1094. "A C{bool} which is C{True} from I{during startup} to "
  1095. "I{during shutdown} and C{False} the rest of the time."
  1096. )
  1097. def resolve(name: str, timeout: Sequence[int] = (1, 3, 11, 45)) -> "Deferred[str]":
  1098. """
  1099. Asynchronously resolve a hostname to a single IPv4 address.
  1100. @note: Rather than calling this API directly, you probably want to use
  1101. L{twisted.internet.endpoints.HostnameEndpoint} to connect to a
  1102. hostname. If you do want to resolve a hostname without connecting
  1103. to it, see L{IReactorPluggableNameResolver} and
  1104. L{IHostnameResolver} so that you can receive multiple results and
  1105. IPv6 addresses.
  1106. @param name: The hostname to resolve.
  1107. @param timeout: A sequence of timeouts, meant to mirror the sequence of
  1108. timeouts used for each hop in recursive queries. Note that
  1109. different implementations of the resolver backend may not honor
  1110. this timeout as such, or at all; if the underlying platform API
  1111. supports it, implementations make a best-effort attempt to cancel
  1112. the underlying resolution if the sum of these timeouts elapses.
  1113. """
  1114. def run() -> None:
  1115. """
  1116. Fire 'startup' System Events, move the reactor to the 'running'
  1117. state, then run the main loop until it is stopped with C{stop()} or
  1118. C{crash()}.
  1119. """
  1120. def stop() -> None:
  1121. """
  1122. Fire 'shutdown' System Events, which will move the reactor to the
  1123. 'stopped' state and cause C{reactor.run()} to exit.
  1124. """
  1125. def crash() -> None:
  1126. """
  1127. Stop the main loop *immediately*, without firing any system events.
  1128. This is named as it is because this is an extremely "rude" thing to do;
  1129. it is possible to lose data and put your system in an inconsistent
  1130. state by calling this. However, it is necessary, as sometimes a system
  1131. can become wedged in a pre-shutdown call.
  1132. """
  1133. def iterate(delay: float) -> None:
  1134. """
  1135. Run the main loop's I/O polling function for a period of time.
  1136. This is most useful in applications where the UI is being drawn "as
  1137. fast as possible", such as games. All pending L{IDelayedCall}s will
  1138. be called.
  1139. The reactor must have been started (via the C{run()} method) prior to
  1140. any invocations of this method. It must also be stopped manually
  1141. after the last call to this method (via the C{stop()} method). This
  1142. method is not re-entrant: you must not call it recursively; in
  1143. particular, you must not call it while the reactor is running.
  1144. """
  1145. def fireSystemEvent(eventType: str) -> None:
  1146. """
  1147. Fire a system-wide event.
  1148. System-wide events are things like 'startup', 'shutdown', and
  1149. 'persist'.
  1150. """
  1151. def addSystemEventTrigger(
  1152. phase: str,
  1153. eventType: str,
  1154. callable: Callable[..., Any],
  1155. *args: object,
  1156. **kwargs: object,
  1157. ) -> Any:
  1158. """
  1159. Add a function to be called when a system event occurs.
  1160. Each "system event" in Twisted, such as 'startup', 'shutdown', and
  1161. 'persist', has 3 phases: 'before', 'during', and 'after' (in that
  1162. order, of course). These events will be fired internally by the
  1163. Reactor.
  1164. An implementor of this interface must only implement those events
  1165. described here.
  1166. Callbacks registered for the "before" phase may return either None or a
  1167. Deferred. The "during" phase will not execute until all of the
  1168. Deferreds from the "before" phase have fired.
  1169. Once the "during" phase is running, all of the remaining triggers must
  1170. execute; their return values must be ignored.
  1171. @param phase: a time to call the event -- either the string 'before',
  1172. 'after', or 'during', describing when to call it
  1173. relative to the event's execution.
  1174. @param eventType: this is a string describing the type of event.
  1175. @param callable: the object to call before shutdown.
  1176. @param args: the arguments to call it with.
  1177. @param kwargs: the keyword arguments to call it with.
  1178. @return: an ID that can be used to remove this call with
  1179. removeSystemEventTrigger.
  1180. """
  1181. def removeSystemEventTrigger(triggerID: Any) -> None:
  1182. """
  1183. Removes a trigger added with addSystemEventTrigger.
  1184. @param triggerID: a value returned from addSystemEventTrigger.
  1185. @raise KeyError: If there is no system event trigger for the given
  1186. C{triggerID}.
  1187. @raise ValueError: If there is no system event trigger for the given
  1188. C{triggerID}.
  1189. @raise TypeError: If there is no system event trigger for the given
  1190. C{triggerID}.
  1191. """
  1192. def callWhenRunning(
  1193. callable: Callable[..., Any], *args: object, **kwargs: object
  1194. ) -> Optional[Any]:
  1195. """
  1196. Call a function when the reactor is running.
  1197. If the reactor has not started, the callable will be scheduled
  1198. to run when it does start. Otherwise, the callable will be invoked
  1199. immediately.
  1200. @param callable: the callable object to call later.
  1201. @param args: the arguments to call it with.
  1202. @param kwargs: the keyword arguments to call it with.
  1203. @return: None if the callable was invoked, otherwise a system
  1204. event id for the scheduled call.
  1205. """
  1206. class IReactorPluggableResolver(Interface):
  1207. """
  1208. An L{IReactorPluggableResolver} is a reactor which can be customized with
  1209. an L{IResolverSimple}. This is a fairly limited interface, that supports
  1210. only IPv4; you should use L{IReactorPluggableNameResolver} instead.
  1211. @see: L{IReactorPluggableNameResolver}
  1212. """
  1213. def installResolver(resolver: IResolverSimple) -> IResolverSimple:
  1214. """
  1215. Set the internal resolver to use to for name lookups.
  1216. @param resolver: The new resolver to use.
  1217. @return: The previously installed resolver.
  1218. """
  1219. class IReactorPluggableNameResolver(Interface):
  1220. """
  1221. An L{IReactorPluggableNameResolver} is a reactor whose name resolver can be
  1222. set to a user-supplied object.
  1223. """
  1224. nameResolver: IHostnameResolver = Attribute(
  1225. """
  1226. Read-only attribute; the resolver installed with L{installResolver}.
  1227. An L{IHostnameResolver}.
  1228. """
  1229. )
  1230. def installNameResolver(resolver: IHostnameResolver) -> IHostnameResolver:
  1231. """
  1232. Set the internal resolver to use for name lookups.
  1233. @param resolver: The new resolver to use.
  1234. @return: The previously installed resolver.
  1235. """
  1236. class IReactorDaemonize(Interface):
  1237. """
  1238. A reactor which provides hooks that need to be called before and after
  1239. daemonization.
  1240. Notes:
  1241. - This interface SHOULD NOT be called by applications.
  1242. - This interface should only be implemented by reactors as a workaround
  1243. (in particular, it's implemented currently only by kqueue()).
  1244. For details please see the comments on ticket #1918.
  1245. """
  1246. def beforeDaemonize() -> None:
  1247. """
  1248. Hook to be called immediately before daemonization. No reactor methods
  1249. may be called until L{afterDaemonize} is called.
  1250. """
  1251. def afterDaemonize() -> None:
  1252. """
  1253. Hook to be called immediately after daemonization. This may only be
  1254. called after L{beforeDaemonize} had been called previously.
  1255. """
  1256. class IReactorFDSet(Interface):
  1257. """
  1258. Implement me to be able to use L{IFileDescriptor} type resources.
  1259. This assumes that your main-loop uses UNIX-style numeric file descriptors
  1260. (or at least similarly opaque IDs returned from a .fileno() method)
  1261. """
  1262. def addReader(reader: "IReadDescriptor") -> None:
  1263. """
  1264. I add reader to the set of file descriptors to get read events for.
  1265. @param reader: An L{IReadDescriptor} provider that will be checked for
  1266. read events until it is removed from the reactor with
  1267. L{removeReader}.
  1268. """
  1269. def addWriter(writer: "IWriteDescriptor") -> None:
  1270. """
  1271. I add writer to the set of file descriptors to get write events for.
  1272. @param writer: An L{IWriteDescriptor} provider that will be checked for
  1273. write events until it is removed from the reactor with
  1274. L{removeWriter}.
  1275. """
  1276. def removeReader(reader: "IReadDescriptor") -> None:
  1277. """
  1278. Removes an object previously added with L{addReader}.
  1279. """
  1280. def removeWriter(writer: "IWriteDescriptor") -> None:
  1281. """
  1282. Removes an object previously added with L{addWriter}.
  1283. """
  1284. def removeAll() -> List[Union["IReadDescriptor", "IWriteDescriptor"]]:
  1285. """
  1286. Remove all readers and writers.
  1287. Should not remove reactor internal reactor connections (like a waker).
  1288. @return: A list of L{IReadDescriptor} and L{IWriteDescriptor} providers
  1289. which were removed.
  1290. """
  1291. def getReaders() -> List["IReadDescriptor"]:
  1292. """
  1293. Return the list of file descriptors currently monitored for input
  1294. events by the reactor.
  1295. @return: the list of file descriptors monitored for input events.
  1296. """
  1297. def getWriters() -> List["IWriteDescriptor"]:
  1298. """
  1299. Return the list file descriptors currently monitored for output events
  1300. by the reactor.
  1301. @return: the list of file descriptors monitored for output events.
  1302. """
  1303. class IListeningPort(Interface):
  1304. """
  1305. A listening port.
  1306. """
  1307. def startListening() -> None:
  1308. """
  1309. Start listening on this port.
  1310. @raise CannotListenError: If it cannot listen on this port (e.g., it is
  1311. a TCP port and it cannot bind to the required
  1312. port number).
  1313. """
  1314. def stopListening() -> Optional["Deferred[None]"]:
  1315. """
  1316. Stop listening on this port.
  1317. If it does not complete immediately, will return Deferred that fires
  1318. upon completion.
  1319. """
  1320. def getHost() -> IAddress:
  1321. """
  1322. Get the host that this port is listening for.
  1323. @return: An L{IAddress} provider.
  1324. """
  1325. class ILoggingContext(Interface):
  1326. """
  1327. Give context information that will be used to log events generated by
  1328. this item.
  1329. """
  1330. def logPrefix() -> str:
  1331. """
  1332. @return: Prefix used during log formatting to indicate context.
  1333. """
  1334. class IFileDescriptor(ILoggingContext):
  1335. """
  1336. An interface representing a UNIX-style numeric file descriptor.
  1337. """
  1338. def fileno() -> object:
  1339. """
  1340. @return: The platform-specified representation of a file descriptor
  1341. number. Or C{-1} if the descriptor no longer has a valid file
  1342. descriptor number associated with it. As long as the descriptor
  1343. is valid, calls to this method on a particular instance must
  1344. return the same value.
  1345. """
  1346. def connectionLost(reason: Failure) -> None:
  1347. """
  1348. Called when the connection was lost.
  1349. This is called when the connection on a selectable object has been
  1350. lost. It will be called whether the connection was closed explicitly,
  1351. an exception occurred in an event handler, or the other end of the
  1352. connection closed it first.
  1353. See also L{IHalfCloseableDescriptor} if your descriptor wants to be
  1354. notified separately of the two halves of the connection being closed.
  1355. @param reason: A failure instance indicating the reason why the
  1356. connection was lost. L{error.ConnectionLost} and
  1357. L{error.ConnectionDone} are of special note, but the
  1358. failure may be of other classes as well.
  1359. """
  1360. class IReadDescriptor(IFileDescriptor):
  1361. """
  1362. An L{IFileDescriptor} that can read.
  1363. This interface is generally used in conjunction with L{IReactorFDSet}.
  1364. """
  1365. def doRead() -> Optional[Failure]:
  1366. """
  1367. Some data is available for reading on your descriptor.
  1368. @return: If an error is encountered which causes the descriptor to
  1369. no longer be valid, a L{Failure} should be returned. Otherwise,
  1370. L{None}.
  1371. """
  1372. class IWriteDescriptor(IFileDescriptor):
  1373. """
  1374. An L{IFileDescriptor} that can write.
  1375. This interface is generally used in conjunction with L{IReactorFDSet}.
  1376. """
  1377. def doWrite() -> Optional[Failure]:
  1378. """
  1379. Some data can be written to your descriptor.
  1380. @return: If an error is encountered which causes the descriptor to
  1381. no longer be valid, a L{Failure} should be returned. Otherwise,
  1382. L{None}.
  1383. """
  1384. class IReadWriteDescriptor(IReadDescriptor, IWriteDescriptor):
  1385. """
  1386. An L{IFileDescriptor} that can both read and write.
  1387. """
  1388. class IHalfCloseableDescriptor(Interface):
  1389. """
  1390. A descriptor that can be half-closed.
  1391. """
  1392. def writeConnectionLost(reason: Failure) -> None:
  1393. """
  1394. Indicates write connection was lost.
  1395. """
  1396. def readConnectionLost(reason: Failure) -> None:
  1397. """
  1398. Indicates read connection was lost.
  1399. """
  1400. class ISystemHandle(Interface):
  1401. """
  1402. An object that wraps a networking OS-specific handle.
  1403. """
  1404. def getHandle() -> object:
  1405. """
  1406. Return a system- and reactor-specific handle.
  1407. This might be a socket.socket() object, or some other type of
  1408. object, depending on which reactor is being used. Use and
  1409. manipulate at your own risk.
  1410. This might be used in cases where you want to set specific
  1411. options not exposed by the Twisted APIs.
  1412. """
  1413. class IConsumer(Interface):
  1414. """
  1415. A consumer consumes data from a producer.
  1416. """
  1417. def registerProducer(producer: "IProducer", streaming: bool) -> None:
  1418. """
  1419. Register to receive data from a producer.
  1420. This sets self to be a consumer for a producer. When this object runs
  1421. out of data (as when a send(2) call on a socket succeeds in moving the
  1422. last data from a userspace buffer into a kernelspace buffer), it will
  1423. ask the producer to resumeProducing().
  1424. For L{IPullProducer} providers, C{resumeProducing} will be called once
  1425. each time data is required.
  1426. For L{IPushProducer} providers, C{pauseProducing} will be called
  1427. whenever the write buffer fills up and C{resumeProducing} will only be
  1428. called when it empties. The consumer will only call C{resumeProducing}
  1429. to balance a previous C{pauseProducing} call; the producer is assumed
  1430. to start in an un-paused state.
  1431. @param streaming: C{True} if C{producer} provides L{IPushProducer},
  1432. C{False} if C{producer} provides L{IPullProducer}.
  1433. @raise RuntimeError: If a producer is already registered.
  1434. """
  1435. def unregisterProducer() -> None:
  1436. """
  1437. Stop consuming data from a producer, without disconnecting.
  1438. """
  1439. def write(data: bytes) -> None:
  1440. """
  1441. The producer will write data by calling this method.
  1442. The implementation must be non-blocking and perform whatever
  1443. buffering is necessary. If the producer has provided enough data
  1444. for now and it is a L{IPushProducer}, the consumer may call its
  1445. C{pauseProducing} method.
  1446. """
  1447. class IProducer(Interface):
  1448. """
  1449. A producer produces data for a consumer.
  1450. Typically producing is done by calling the C{write} method of a class
  1451. implementing L{IConsumer}.
  1452. """
  1453. def stopProducing() -> None:
  1454. """
  1455. Stop producing data.
  1456. This tells a producer that its consumer has died, so it must stop
  1457. producing data for good.
  1458. """
  1459. class IPushProducer(IProducer):
  1460. """
  1461. A push producer, also known as a streaming producer is expected to
  1462. produce (write to this consumer) data on a continuous basis, unless
  1463. it has been paused. A paused push producer will resume producing
  1464. after its C{resumeProducing()} method is called. For a push producer
  1465. which is not pauseable, these functions may be noops.
  1466. """
  1467. def pauseProducing() -> None:
  1468. """
  1469. Pause producing data.
  1470. Tells a producer that it has produced too much data to process for
  1471. the time being, and to stop until C{resumeProducing()} is called.
  1472. """
  1473. def resumeProducing() -> None:
  1474. """
  1475. Resume producing data.
  1476. This tells a producer to re-add itself to the main loop and produce
  1477. more data for its consumer.
  1478. """
  1479. class IPullProducer(IProducer):
  1480. """
  1481. A pull producer, also known as a non-streaming producer, is
  1482. expected to produce data each time L{resumeProducing()} is called.
  1483. """
  1484. def resumeProducing() -> None:
  1485. """
  1486. Produce data for the consumer a single time.
  1487. This tells a producer to produce data for the consumer once
  1488. (not repeatedly, once only). Typically this will be done
  1489. by calling the consumer's C{write} method a single time with
  1490. produced data. The producer should produce data before returning
  1491. from C{resumeProducing()}, that is, it should not schedule a deferred
  1492. write.
  1493. """
  1494. class IProtocol(Interface):
  1495. def dataReceived(data: bytes) -> None:
  1496. """
  1497. Called whenever data is received.
  1498. Use this method to translate to a higher-level message. Usually, some
  1499. callback will be made upon the receipt of each complete protocol
  1500. message.
  1501. Please keep in mind that you will probably need to buffer some data
  1502. as partial (or multiple) protocol messages may be received! We
  1503. recommend that unit tests for protocols call through to this method
  1504. with differing chunk sizes, down to one byte at a time.
  1505. @param data: bytes of indeterminate length
  1506. """
  1507. def connectionLost(reason: Failure) -> None:
  1508. """
  1509. Called when the connection is shut down.
  1510. Clear any circular references here, and any external references
  1511. to this Protocol. The connection has been closed. The C{reason}
  1512. Failure wraps a L{twisted.internet.error.ConnectionDone} or
  1513. L{twisted.internet.error.ConnectionLost} instance (or a subclass
  1514. of one of those).
  1515. """
  1516. def makeConnection(transport: "ITransport") -> None:
  1517. """
  1518. Make a connection to a transport and a server.
  1519. """
  1520. def connectionMade() -> None:
  1521. """
  1522. Called when a connection is made.
  1523. This may be considered the initializer of the protocol, because
  1524. it is called when the connection is completed. For clients,
  1525. this is called once the connection to the server has been
  1526. established; for servers, this is called after an accept() call
  1527. stops blocking and a socket has been received. If you need to
  1528. send any greeting or initial message, do it here.
  1529. """
  1530. class IProcessProtocol(Interface):
  1531. """
  1532. Interface for process-related event handlers.
  1533. """
  1534. def makeConnection(process: "IProcessTransport") -> None:
  1535. """
  1536. Called when the process has been created.
  1537. @param process: An object representing the process which has been
  1538. created and associated with this protocol.
  1539. """
  1540. def childDataReceived(childFD: int, data: bytes) -> None:
  1541. """
  1542. Called when data arrives from the child process.
  1543. @param childFD: The file descriptor from which the data was
  1544. received.
  1545. @param data: The data read from the child's file descriptor.
  1546. """
  1547. def childConnectionLost(childFD: int) -> None:
  1548. """
  1549. Called when a file descriptor associated with the child process is
  1550. closed.
  1551. @param childFD: The file descriptor which was closed.
  1552. """
  1553. def processExited(reason: Failure) -> None:
  1554. """
  1555. Called when the child process exits.
  1556. @param reason: A failure giving the reason the child process
  1557. terminated. The type of exception for this failure is either
  1558. L{twisted.internet.error.ProcessDone} or
  1559. L{twisted.internet.error.ProcessTerminated}.
  1560. @since: 8.2
  1561. """
  1562. def processEnded(reason: Failure) -> None:
  1563. """
  1564. Called when the child process exits and all file descriptors associated
  1565. with it have been closed.
  1566. @param reason: A failure giving the reason the child process
  1567. terminated. The type of exception for this failure is either
  1568. L{twisted.internet.error.ProcessDone} or
  1569. L{twisted.internet.error.ProcessTerminated}.
  1570. """
  1571. class IHalfCloseableProtocol(Interface):
  1572. """
  1573. Implemented to indicate they want notification of half-closes.
  1574. TCP supports the notion of half-closing the connection, e.g.
  1575. closing the write side but still not stopping reading. A protocol
  1576. that implements this interface will be notified of such events,
  1577. instead of having connectionLost called.
  1578. """
  1579. def readConnectionLost() -> None:
  1580. """
  1581. Notification of the read connection being closed.
  1582. This indicates peer did half-close of write side. It is now
  1583. the responsibility of the this protocol to call
  1584. loseConnection(). In addition, the protocol MUST make sure a
  1585. reference to it still exists (i.e. by doing a callLater with
  1586. one of its methods, etc.) as the reactor will only have a
  1587. reference to it if it is writing.
  1588. If the protocol does not do so, it might get garbage collected
  1589. without the connectionLost method ever being called.
  1590. """
  1591. def writeConnectionLost() -> None:
  1592. """
  1593. Notification of the write connection being closed.
  1594. This will never be called for TCP connections as TCP does not
  1595. support notification of this type of half-close.
  1596. """
  1597. class IHandshakeListener(Interface):
  1598. """
  1599. An interface implemented by a L{IProtocol} to indicate that it would like
  1600. to be notified when TLS handshakes complete when run over a TLS-based
  1601. transport.
  1602. This interface is only guaranteed to be called when run over a TLS-based
  1603. transport: non TLS-based transports will not respect this interface.
  1604. """
  1605. def handshakeCompleted() -> None:
  1606. """
  1607. Notification of the TLS handshake being completed.
  1608. This notification fires when OpenSSL has completed the TLS handshake.
  1609. At this point the TLS connection is established, and the protocol can
  1610. interrogate its transport (usually an L{ISSLTransport}) for details of
  1611. the TLS connection.
  1612. This notification *also* fires whenever the TLS session is
  1613. renegotiated. As a result, protocols that have certain minimum security
  1614. requirements should implement this interface to ensure that they are
  1615. able to re-evaluate the security of the TLS session if it changes.
  1616. """
  1617. class IFileDescriptorReceiver(Interface):
  1618. """
  1619. Protocols may implement L{IFileDescriptorReceiver} to receive file
  1620. descriptors sent to them. This is useful in conjunction with
  1621. L{IUNIXTransport}, which allows file descriptors to be sent between
  1622. processes on a single host.
  1623. """
  1624. def fileDescriptorReceived(descriptor: int) -> None:
  1625. """
  1626. Called when a file descriptor is received over the connection.
  1627. @param descriptor: The descriptor which was received.
  1628. @return: L{None}
  1629. """
  1630. class IProtocolFactory(Interface):
  1631. """
  1632. Interface for protocol factories.
  1633. """
  1634. def buildProtocol(addr: IAddress) -> Optional[IProtocol]:
  1635. """
  1636. Called when a connection has been established to addr.
  1637. If None is returned, the connection is assumed to have been refused,
  1638. and the Port will close the connection.
  1639. @param addr: The address of the newly-established connection
  1640. @return: None if the connection was refused, otherwise an object
  1641. providing L{IProtocol}.
  1642. """
  1643. def doStart() -> None:
  1644. """
  1645. Called every time this is connected to a Port or Connector.
  1646. """
  1647. def doStop() -> None:
  1648. """
  1649. Called every time this is unconnected from a Port or Connector.
  1650. """
  1651. class ITransport(Interface):
  1652. """
  1653. I am a transport for bytes.
  1654. I represent (and wrap) the physical connection and synchronicity
  1655. of the framework which is talking to the network. I make no
  1656. representations about whether calls to me will happen immediately
  1657. or require returning to a control loop, or whether they will happen
  1658. in the same or another thread. Consider methods of this class
  1659. (aside from getPeer) to be 'thrown over the wall', to happen at some
  1660. indeterminate time.
  1661. """
  1662. def write(data: bytes) -> None:
  1663. """
  1664. Write some data to the physical connection, in sequence, in a
  1665. non-blocking fashion.
  1666. If possible, make sure that it is all written. No data will
  1667. ever be lost, although (obviously) the connection may be closed
  1668. before it all gets through.
  1669. @param data: The data to write.
  1670. """
  1671. def writeSequence(data: Iterable[bytes]) -> None:
  1672. """
  1673. Write an iterable of byte strings to the physical connection.
  1674. If possible, make sure that all of the data is written to
  1675. the socket at once, without first copying it all into a
  1676. single byte string.
  1677. @param data: The data to write.
  1678. """
  1679. def loseConnection() -> None:
  1680. """
  1681. Close my connection, after writing all pending data.
  1682. Note that if there is a registered producer on a transport it
  1683. will not be closed until the producer has been unregistered.
  1684. """
  1685. def getPeer() -> IAddress:
  1686. """
  1687. Get the remote address of this connection.
  1688. Treat this method with caution. It is the unfortunate result of the
  1689. CGI and Jabber standards, but should not be considered reliable for
  1690. the usual host of reasons; port forwarding, proxying, firewalls, IP
  1691. masquerading, etc.
  1692. @return: An L{IAddress} provider.
  1693. """
  1694. def getHost() -> IAddress:
  1695. """
  1696. Similar to getPeer, but returns an address describing this side of the
  1697. connection.
  1698. @return: An L{IAddress} provider.
  1699. """
  1700. class ITCPTransport(ITransport):
  1701. """
  1702. A TCP based transport.
  1703. """
  1704. def loseWriteConnection() -> None:
  1705. """
  1706. Half-close the write side of a TCP connection.
  1707. If the protocol instance this is attached to provides
  1708. IHalfCloseableProtocol, it will get notified when the operation is
  1709. done. When closing write connection, as with loseConnection this will
  1710. only happen when buffer has emptied and there is no registered
  1711. producer.
  1712. """
  1713. def abortConnection() -> None:
  1714. """
  1715. Close the connection abruptly.
  1716. Discards any buffered data, stops any registered producer,
  1717. and, if possible, notifies the other end of the unclean
  1718. closure.
  1719. @since: 11.1
  1720. """
  1721. def getTcpNoDelay() -> bool:
  1722. """
  1723. Return if C{TCP_NODELAY} is enabled.
  1724. """
  1725. def setTcpNoDelay(enabled: bool) -> None:
  1726. """
  1727. Enable/disable C{TCP_NODELAY}.
  1728. Enabling C{TCP_NODELAY} turns off Nagle's algorithm. Small packets are
  1729. sent sooner, possibly at the expense of overall throughput.
  1730. """
  1731. def getTcpKeepAlive() -> bool:
  1732. """
  1733. Return if C{SO_KEEPALIVE} is enabled.
  1734. """
  1735. def setTcpKeepAlive(enabled: bool) -> None:
  1736. """
  1737. Enable/disable C{SO_KEEPALIVE}.
  1738. Enabling C{SO_KEEPALIVE} sends packets periodically when the connection
  1739. is otherwise idle, usually once every two hours. They are intended
  1740. to allow detection of lost peers in a non-infinite amount of time.
  1741. """
  1742. def getHost() -> Union["IPv4Address", "IPv6Address"]:
  1743. """
  1744. Returns L{IPv4Address} or L{IPv6Address}.
  1745. """
  1746. def getPeer() -> Union["IPv4Address", "IPv6Address"]:
  1747. """
  1748. Returns L{IPv4Address} or L{IPv6Address}.
  1749. """
  1750. class IUNIXTransport(ITransport):
  1751. """
  1752. Transport for stream-oriented unix domain connections.
  1753. """
  1754. def sendFileDescriptor(descriptor: int) -> None:
  1755. """
  1756. Send a duplicate of this (file, socket, pipe, etc) descriptor to the
  1757. other end of this connection.
  1758. The send is non-blocking and will be queued if it cannot be performed
  1759. immediately. The send will be processed in order with respect to other
  1760. C{sendFileDescriptor} calls on this transport, but not necessarily with
  1761. respect to C{write} calls on this transport. The send can only be
  1762. processed if there are also bytes in the normal connection-oriented send
  1763. buffer (ie, you must call C{write} at least as many times as you call
  1764. C{sendFileDescriptor}).
  1765. @param descriptor: An C{int} giving a valid file descriptor in this
  1766. process. Note that a I{file descriptor} may actually refer to a
  1767. socket, a pipe, or anything else POSIX tries to treat in the same
  1768. way as a file.
  1769. """
  1770. class IOpenSSLServerConnectionCreator(Interface):
  1771. """
  1772. A provider of L{IOpenSSLServerConnectionCreator} can create
  1773. L{OpenSSL.SSL.Connection} objects for TLS servers.
  1774. @see: L{twisted.internet.ssl}
  1775. @note: Creating OpenSSL connection objects is subtle, error-prone, and
  1776. security-critical. Before implementing this interface yourself,
  1777. consider using L{twisted.internet.ssl.CertificateOptions} as your
  1778. C{contextFactory}. (For historical reasons, that class does not
  1779. actually I{implement} this interface; nevertheless it is usable in all
  1780. Twisted APIs which require a provider of this interface.)
  1781. """
  1782. def serverConnectionForTLS(
  1783. tlsProtocol: "TLSMemoryBIOProtocol",
  1784. ) -> "OpenSSLConnection":
  1785. """
  1786. Create a connection for the given server protocol.
  1787. @return: an OpenSSL connection object configured appropriately for the
  1788. given Twisted protocol.
  1789. """
  1790. class IOpenSSLClientConnectionCreator(Interface):
  1791. """
  1792. A provider of L{IOpenSSLClientConnectionCreator} can create
  1793. L{OpenSSL.SSL.Connection} objects for TLS clients.
  1794. @see: L{twisted.internet.ssl}
  1795. @note: Creating OpenSSL connection objects is subtle, error-prone, and
  1796. security-critical. Before implementing this interface yourself,
  1797. consider using L{twisted.internet.ssl.optionsForClientTLS} as your
  1798. C{contextFactory}.
  1799. """
  1800. def clientConnectionForTLS(
  1801. tlsProtocol: "TLSMemoryBIOProtocol",
  1802. ) -> "OpenSSLConnection":
  1803. """
  1804. Create a connection for the given client protocol.
  1805. @param tlsProtocol: the client protocol making the request.
  1806. @return: an OpenSSL connection object configured appropriately for the
  1807. given Twisted protocol.
  1808. """
  1809. class IProtocolNegotiationFactory(Interface):
  1810. """
  1811. A provider of L{IProtocolNegotiationFactory} can provide information about
  1812. the various protocols that the factory can create implementations of. This
  1813. can be used, for example, to provide protocol names for Next Protocol
  1814. Negotiation and Application Layer Protocol Negotiation.
  1815. @see: L{twisted.internet.ssl}
  1816. """
  1817. def acceptableProtocols() -> List[bytes]:
  1818. """
  1819. Returns a list of protocols that can be spoken by the connection
  1820. factory in the form of ALPN tokens, as laid out in the IANA registry
  1821. for ALPN tokens.
  1822. @return: a list of ALPN tokens in order of preference.
  1823. """
  1824. class IOpenSSLContextFactory(Interface):
  1825. """
  1826. A provider of L{IOpenSSLContextFactory} is capable of generating
  1827. L{OpenSSL.SSL.Context} classes suitable for configuring TLS on a
  1828. connection. A provider will store enough state to be able to generate these
  1829. contexts as needed for individual connections.
  1830. @see: L{twisted.internet.ssl}
  1831. """
  1832. def getContext() -> "OpenSSLContext":
  1833. """
  1834. Returns a TLS context object, suitable for securing a TLS connection.
  1835. This context object will be appropriately customized for the connection
  1836. based on the state in this object.
  1837. @return: A TLS context object.
  1838. """
  1839. class ITLSTransport(ITCPTransport):
  1840. """
  1841. A TCP transport that supports switching to TLS midstream.
  1842. Once TLS mode is started the transport will implement L{ISSLTransport}.
  1843. """
  1844. def startTLS(
  1845. contextFactory: Union[
  1846. IOpenSSLClientConnectionCreator, IOpenSSLServerConnectionCreator
  1847. ]
  1848. ) -> None:
  1849. """
  1850. Initiate TLS negotiation.
  1851. @param contextFactory: An object which creates appropriately configured
  1852. TLS connections.
  1853. For clients, use L{twisted.internet.ssl.optionsForClientTLS}; for
  1854. servers, use L{twisted.internet.ssl.CertificateOptions}.
  1855. @type contextFactory: L{IOpenSSLClientConnectionCreator} or
  1856. L{IOpenSSLServerConnectionCreator}, depending on whether this
  1857. L{ITLSTransport} is a server or not. If the appropriate interface
  1858. is not provided by the value given for C{contextFactory}, it must
  1859. be an implementor of L{IOpenSSLContextFactory}.
  1860. """
  1861. class ISSLTransport(ITCPTransport):
  1862. """
  1863. A SSL/TLS based transport.
  1864. """
  1865. def getPeerCertificate() -> object:
  1866. """
  1867. Return an object with the peer's certificate info.
  1868. """
  1869. class INegotiated(ISSLTransport):
  1870. """
  1871. A TLS based transport that supports using ALPN/NPN to negotiate the
  1872. protocol to be used inside the encrypted tunnel.
  1873. """
  1874. negotiatedProtocol = Attribute(
  1875. """
  1876. The protocol selected to be spoken using ALPN/NPN. The result from ALPN
  1877. is preferred to the result from NPN if both were used. If the remote
  1878. peer does not support ALPN or NPN, or neither NPN or ALPN are available
  1879. on this machine, will be L{None}. Otherwise, will be the name of the
  1880. selected protocol as C{bytes}. Note that until the handshake has
  1881. completed this property may incorrectly return L{None}: wait until data
  1882. has been received before trusting it (see
  1883. https://twistedmatrix.com/trac/ticket/6024).
  1884. """
  1885. )
  1886. class ICipher(Interface):
  1887. """
  1888. A TLS cipher.
  1889. """
  1890. fullName = Attribute("The fully qualified name of the cipher in L{unicode}.")
  1891. class IAcceptableCiphers(Interface):
  1892. """
  1893. A list of acceptable ciphers for a TLS context.
  1894. """
  1895. def selectCiphers(availableCiphers: Tuple[ICipher]) -> Tuple[ICipher]:
  1896. """
  1897. Choose which ciphers to allow to be negotiated on a TLS connection.
  1898. @param availableCiphers: A L{tuple} of L{ICipher} which gives the names
  1899. of all ciphers supported by the TLS implementation in use.
  1900. @return: A L{tuple} of L{ICipher} which represents the ciphers
  1901. which may be negotiated on the TLS connection. The result is
  1902. ordered by preference with more preferred ciphers appearing
  1903. earlier.
  1904. """
  1905. class IProcessTransport(ITransport):
  1906. """
  1907. A process transport.
  1908. """
  1909. pid = Attribute(
  1910. "From before L{IProcessProtocol.makeConnection} is called to before "
  1911. "L{IProcessProtocol.processEnded} is called, C{pid} is an L{int} "
  1912. "giving the platform process ID of this process. C{pid} is L{None} "
  1913. "at all other times."
  1914. )
  1915. def closeStdin() -> None:
  1916. """
  1917. Close stdin after all data has been written out.
  1918. """
  1919. def closeStdout() -> None:
  1920. """
  1921. Close stdout.
  1922. """
  1923. def closeStderr() -> None:
  1924. """
  1925. Close stderr.
  1926. """
  1927. def closeChildFD(descriptor: int) -> None:
  1928. """
  1929. Close a file descriptor which is connected to the child process, identified
  1930. by its FD in the child process.
  1931. """
  1932. def writeToChild(childFD: int, data: bytes) -> None:
  1933. """
  1934. Similar to L{ITransport.write} but also allows the file descriptor in
  1935. the child process which will receive the bytes to be specified.
  1936. @param childFD: The file descriptor to which to write.
  1937. @param data: The bytes to write.
  1938. @raise KeyError: If C{childFD} is not a file descriptor that was mapped
  1939. in the child when L{IReactorProcess.spawnProcess} was used to create
  1940. it.
  1941. """
  1942. def loseConnection() -> None:
  1943. """
  1944. Close stdin, stderr and stdout.
  1945. """
  1946. def signalProcess(signalID: Union[str, int]) -> None:
  1947. """
  1948. Send a signal to the process.
  1949. @param signalID: can be
  1950. - one of C{"KILL"}, C{"TERM"}, or C{"INT"}.
  1951. These will be implemented in a
  1952. cross-platform manner, and so should be used
  1953. if possible.
  1954. - an integer, where it represents a POSIX
  1955. signal ID.
  1956. @raise twisted.internet.error.ProcessExitedAlready: If the process has
  1957. already exited.
  1958. @raise OSError: If the C{os.kill} call fails with an errno different
  1959. from C{ESRCH}.
  1960. """
  1961. class IServiceCollection(Interface):
  1962. """
  1963. An object which provides access to a collection of services.
  1964. """
  1965. def getServiceNamed(serviceName: str) -> object:
  1966. """
  1967. Retrieve the named service from this application.
  1968. Raise a C{KeyError} if there is no such service name.
  1969. """
  1970. def addService(service: object) -> None:
  1971. """
  1972. Add a service to this collection.
  1973. """
  1974. def removeService(service: object) -> None:
  1975. """
  1976. Remove a service from this collection.
  1977. """
  1978. class IUDPTransport(Interface):
  1979. """
  1980. Transport for UDP DatagramProtocols.
  1981. """
  1982. def write(packet: bytes, addr: Optional[Tuple[str, int]]) -> None:
  1983. """
  1984. Write packet to given address.
  1985. @param addr: a tuple of (ip, port). For connected transports must
  1986. be the address the transport is connected to, or None.
  1987. In non-connected mode this is mandatory.
  1988. @raise twisted.internet.error.MessageLengthError: C{packet} was too
  1989. long.
  1990. """
  1991. def connect(host: str, port: int) -> None:
  1992. """
  1993. Connect the transport to an address.
  1994. This changes it to connected mode. Datagrams can only be sent to
  1995. this address, and will only be received from this address. In addition
  1996. the protocol's connectionRefused method might get called if destination
  1997. is not receiving datagrams.
  1998. @param host: an IP address, not a domain name ('127.0.0.1', not 'localhost')
  1999. @param port: port to connect to.
  2000. """
  2001. def getHost() -> Union["IPv4Address", "IPv6Address"]:
  2002. """
  2003. Get this port's host address.
  2004. @return: an address describing the listening port.
  2005. """
  2006. def stopListening() -> Optional["Deferred[None]"]:
  2007. """
  2008. Stop listening on this port.
  2009. If it does not complete immediately, will return L{Deferred} that fires
  2010. upon completion.
  2011. """
  2012. def setBroadcastAllowed(enabled: bool) -> None:
  2013. """
  2014. Set whether this port may broadcast.
  2015. @param enabled: Whether the port may broadcast.
  2016. """
  2017. def getBroadcastAllowed() -> bool:
  2018. """
  2019. Checks if broadcast is currently allowed on this port.
  2020. @return: Whether this port may broadcast.
  2021. """
  2022. class IUNIXDatagramTransport(Interface):
  2023. """
  2024. Transport for UDP PacketProtocols.
  2025. """
  2026. def write(packet: bytes, addr: str) -> None:
  2027. """
  2028. Write packet to given address.
  2029. """
  2030. def getHost() -> "UNIXAddress":
  2031. """
  2032. Returns L{UNIXAddress}.
  2033. """
  2034. class IUNIXDatagramConnectedTransport(Interface):
  2035. """
  2036. Transport for UDP ConnectedPacketProtocols.
  2037. """
  2038. def write(packet: bytes) -> None:
  2039. """
  2040. Write packet to address we are connected to.
  2041. """
  2042. def getHost() -> "UNIXAddress":
  2043. """
  2044. Returns L{UNIXAddress}.
  2045. """
  2046. def getPeer() -> "UNIXAddress":
  2047. """
  2048. Returns L{UNIXAddress}.
  2049. """
  2050. class IMulticastTransport(IUDPTransport):
  2051. """
  2052. Additional functionality for multicast UDP.
  2053. """
  2054. def getOutgoingInterface() -> str | int:
  2055. """
  2056. Return interface of outgoing multicast packets.
  2057. """
  2058. def setOutgoingInterface(addr: str | int) -> Deferred[int]:
  2059. """
  2060. Set interface for outgoing multicast packets.
  2061. @note: For IPv4 multicast sockets, the address must be a hostname or IP
  2062. address. For IPv6 multicast sockets, the address must be an
  2063. interface index, as described in L{socket.if_nameindex}.
  2064. @returns: Deferred of (1: success, 0: failure).
  2065. """
  2066. def getLoopbackMode() -> bool:
  2067. """
  2068. Return if loopback mode is enabled.
  2069. """
  2070. def setLoopbackMode(mode: bool) -> None:
  2071. """
  2072. Set if loopback mode is enabled.
  2073. """
  2074. def getTTL() -> int:
  2075. """
  2076. Get time to live for multicast packets.
  2077. """
  2078. def setTTL(ttl: int) -> None:
  2079. """
  2080. Set time to live on multicast packets.
  2081. """
  2082. def joinGroup(addr: str, interface: str = "") -> "Deferred[None]":
  2083. """
  2084. Join a multicast group. Returns L{Deferred} of success or failure.
  2085. If an error occurs, the returned L{Deferred} will fail with
  2086. L{error.MulticastJoinError}.
  2087. """
  2088. def leaveGroup(addr: str, interface: str = "") -> "Deferred[None]":
  2089. """
  2090. Leave multicast group, return L{Deferred} of success.
  2091. """
  2092. class IStreamClientEndpoint(Interface):
  2093. """
  2094. A stream client endpoint is a place that L{ClientFactory} can connect to.
  2095. For example, a remote TCP host/port pair would be a TCP client endpoint.
  2096. @since: 10.1
  2097. """
  2098. def connect(protocolFactory: IProtocolFactory) -> "Deferred[IProtocol]":
  2099. """
  2100. Connect the C{protocolFactory} to the location specified by this
  2101. L{IStreamClientEndpoint} provider.
  2102. @param protocolFactory: A provider of L{IProtocolFactory}
  2103. @return: A L{Deferred} that results in an L{IProtocol} upon successful
  2104. connection otherwise a L{Failure} wrapping L{ConnectError} or
  2105. L{NoProtocol <twisted.internet.error.NoProtocol>}.
  2106. """
  2107. class IStreamServerEndpoint(Interface):
  2108. """
  2109. A stream server endpoint is a place that a L{Factory} can listen for
  2110. incoming connections.
  2111. @since: 10.1
  2112. """
  2113. def listen(protocolFactory: IProtocolFactory) -> "Deferred[IListeningPort]":
  2114. """
  2115. Listen with C{protocolFactory} at the location specified by this
  2116. L{IStreamServerEndpoint} provider.
  2117. @param protocolFactory: A provider of L{IProtocolFactory}
  2118. @return: A L{Deferred} that results in an L{IListeningPort} or an
  2119. L{CannotListenError}
  2120. """
  2121. class IStreamServerEndpointStringParser(Interface):
  2122. """
  2123. An L{IStreamServerEndpointStringParser} is like an
  2124. L{IStreamClientEndpointStringParserWithReactor}, except for
  2125. L{IStreamServerEndpoint}s instead of clients. It integrates with
  2126. L{endpoints.serverFromString} in much the same way.
  2127. """
  2128. prefix = Attribute(
  2129. """
  2130. A C{str}, the description prefix to respond to. For example, an
  2131. L{IStreamServerEndpointStringParser} plugin which had C{"foo"} for its
  2132. C{prefix} attribute would be called for endpoint descriptions like
  2133. C{"foo:bar:baz"} or C{"foo:"}.
  2134. """
  2135. )
  2136. def parseStreamServer(
  2137. reactor: IReactorCore, *args: object, **kwargs: object
  2138. ) -> IStreamServerEndpoint:
  2139. """
  2140. Parse a stream server endpoint from a reactor and string-only arguments
  2141. and keyword arguments.
  2142. @see: L{IStreamClientEndpointStringParserWithReactor.parseStreamClient}
  2143. @return: a stream server endpoint
  2144. """
  2145. class IStreamClientEndpointStringParserWithReactor(Interface):
  2146. """
  2147. An L{IStreamClientEndpointStringParserWithReactor} is a parser which can
  2148. convert a set of string C{*args} and C{**kwargs} into an
  2149. L{IStreamClientEndpoint} provider.
  2150. This interface is really only useful in the context of the plugin system
  2151. for L{endpoints.clientFromString}. See the document entitled "I{The
  2152. Twisted Plugin System}" for more details on how to write a plugin.
  2153. If you place an L{IStreamClientEndpointStringParserWithReactor} plugin in
  2154. the C{twisted.plugins} package, that plugin's C{parseStreamClient} method
  2155. will be used to produce endpoints for any description string that begins
  2156. with the result of that L{IStreamClientEndpointStringParserWithReactor}'s
  2157. prefix attribute.
  2158. """
  2159. prefix = Attribute(
  2160. """
  2161. L{bytes}, the description prefix to respond to. For example, an
  2162. L{IStreamClientEndpointStringParserWithReactor} plugin which had
  2163. C{b"foo"} for its C{prefix} attribute would be called for endpoint
  2164. descriptions like C{b"foo:bar:baz"} or C{b"foo:"}.
  2165. """
  2166. )
  2167. def parseStreamClient(
  2168. reactor: IReactorCore, *args: object, **kwargs: object
  2169. ) -> IStreamClientEndpoint:
  2170. """
  2171. This method is invoked by L{endpoints.clientFromString}, if the type of
  2172. endpoint matches the return value from this
  2173. L{IStreamClientEndpointStringParserWithReactor}'s C{prefix} method.
  2174. @param reactor: The reactor passed to L{endpoints.clientFromString}.
  2175. @param args: The byte string arguments, minus the endpoint type, in the
  2176. endpoint description string, parsed according to the rules
  2177. described in L{endpoints.quoteStringArgument}. For example, if the
  2178. description were C{b"my-type:foo:bar:baz=qux"}, C{args} would be
  2179. C{(b'foo', b'bar')}
  2180. @param kwargs: The byte string arguments from the endpoint description
  2181. passed as keyword arguments. For example, if the description were
  2182. C{b"my-type:foo:bar:baz=qux"}, C{kwargs} would be
  2183. C{dict(baz=b'qux')}.
  2184. @return: a client endpoint
  2185. """
  2186. class _ISupportsExitSignalCapturing(Interface):
  2187. """
  2188. An implementor of L{_ISupportsExitSignalCapturing} will capture the
  2189. value of any delivered exit signal (SIGINT, SIGTERM, SIGBREAK) for which
  2190. it has installed a handler. The caught signal number is made available in
  2191. the _exitSignal attribute.
  2192. """
  2193. _exitSignal = Attribute(
  2194. """
  2195. C{int} or C{None}, the integer exit signal delivered to the
  2196. application, or None if no signal was delivered.
  2197. """
  2198. )