interfaces.py 94 KB

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