interfaces.py 95 KB

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