Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dns.py 97KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356
  1. # -*- test-case-name: twisted.names.test.test_dns -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. DNS protocol implementation.
  6. Future Plans:
  7. - Get rid of some toplevels, maybe.
  8. """
  9. # System imports
  10. import inspect
  11. import random
  12. import socket
  13. import struct
  14. from io import BytesIO
  15. from itertools import chain
  16. from typing import Optional, SupportsInt, Union
  17. from zope.interface import Attribute, Interface, implementer
  18. # Twisted imports
  19. from twisted.internet import defer, protocol
  20. from twisted.internet.error import CannotListenError
  21. from twisted.python import failure, log, randbytes, util as tputil
  22. from twisted.python.compat import cmp, comparable, nativeString
  23. __all__ = [
  24. "IEncodable",
  25. "IRecord",
  26. "IEncodableRecord",
  27. "A",
  28. "A6",
  29. "AAAA",
  30. "AFSDB",
  31. "CNAME",
  32. "DNAME",
  33. "HINFO",
  34. "MAILA",
  35. "MAILB",
  36. "MB",
  37. "MD",
  38. "MF",
  39. "MG",
  40. "MINFO",
  41. "MR",
  42. "MX",
  43. "NAPTR",
  44. "NS",
  45. "NULL",
  46. "OPT",
  47. "PTR",
  48. "RP",
  49. "SOA",
  50. "SPF",
  51. "SRV",
  52. "TXT",
  53. "SSHFP",
  54. "TSIG",
  55. "WKS",
  56. "ANY",
  57. "CH",
  58. "CS",
  59. "HS",
  60. "IN",
  61. "ALL_RECORDS",
  62. "AXFR",
  63. "IXFR",
  64. "EFORMAT",
  65. "ENAME",
  66. "ENOTIMP",
  67. "EREFUSED",
  68. "ESERVER",
  69. "EBADVERSION",
  70. "EBADSIG",
  71. "EBADKEY",
  72. "EBADTIME",
  73. "Record_A",
  74. "Record_A6",
  75. "Record_AAAA",
  76. "Record_AFSDB",
  77. "Record_CNAME",
  78. "Record_DNAME",
  79. "Record_HINFO",
  80. "Record_MB",
  81. "Record_MD",
  82. "Record_MF",
  83. "Record_MG",
  84. "Record_MINFO",
  85. "Record_MR",
  86. "Record_MX",
  87. "Record_NAPTR",
  88. "Record_NS",
  89. "Record_NULL",
  90. "Record_PTR",
  91. "Record_RP",
  92. "Record_SOA",
  93. "Record_SPF",
  94. "Record_SRV",
  95. "Record_SSHFP",
  96. "Record_TSIG",
  97. "Record_TXT",
  98. "Record_WKS",
  99. "UnknownRecord",
  100. "QUERY_CLASSES",
  101. "QUERY_TYPES",
  102. "REV_CLASSES",
  103. "REV_TYPES",
  104. "EXT_QUERIES",
  105. "Charstr",
  106. "Message",
  107. "Name",
  108. "Query",
  109. "RRHeader",
  110. "SimpleRecord",
  111. "DNSDatagramProtocol",
  112. "DNSMixin",
  113. "DNSProtocol",
  114. "OK",
  115. "OP_INVERSE",
  116. "OP_NOTIFY",
  117. "OP_QUERY",
  118. "OP_STATUS",
  119. "OP_UPDATE",
  120. "PORT",
  121. "AuthoritativeDomainError",
  122. "DNSQueryTimeoutError",
  123. "DomainError",
  124. ]
  125. AF_INET6 = socket.AF_INET6
  126. def _ord2bytes(ordinal):
  127. """
  128. Construct a bytes object representing a single byte with the given
  129. ordinal value.
  130. @type ordinal: L{int}
  131. @rtype: L{bytes}
  132. """
  133. return bytes([ordinal])
  134. def _nicebytes(bytes):
  135. """
  136. Represent a mostly textful bytes object in a way suitable for
  137. presentation to an end user.
  138. @param bytes: The bytes to represent.
  139. @rtype: L{str}
  140. """
  141. return repr(bytes)[1:]
  142. def _nicebyteslist(list):
  143. """
  144. Represent a list of mostly textful bytes objects in a way suitable for
  145. presentation to an end user.
  146. @param list: The list of bytes to represent.
  147. @rtype: L{str}
  148. """
  149. return "[{}]".format(", ".join([_nicebytes(b) for b in list]))
  150. def randomSource():
  151. """
  152. Wrapper around L{twisted.python.randbytes.RandomFactory.secureRandom} to
  153. return 2 random bytes.
  154. @rtype: L{bytes}
  155. """
  156. return struct.unpack("H", randbytes.secureRandom(2, fallback=True))[0]
  157. PORT = 53
  158. (
  159. A,
  160. NS,
  161. MD,
  162. MF,
  163. CNAME,
  164. SOA,
  165. MB,
  166. MG,
  167. MR,
  168. NULL,
  169. WKS,
  170. PTR,
  171. HINFO,
  172. MINFO,
  173. MX,
  174. TXT,
  175. RP,
  176. AFSDB,
  177. ) = range(1, 19)
  178. AAAA = 28
  179. SRV = 33
  180. NAPTR = 35
  181. A6 = 38
  182. DNAME = 39
  183. OPT = 41
  184. SSHFP = 44
  185. SPF = 99
  186. # These record types do not exist in zones, but are transferred in
  187. # messages the same way normal RRs are.
  188. TKEY = 249
  189. TSIG = 250
  190. QUERY_TYPES = {
  191. A: "A",
  192. NS: "NS",
  193. MD: "MD",
  194. MF: "MF",
  195. CNAME: "CNAME",
  196. SOA: "SOA",
  197. MB: "MB",
  198. MG: "MG",
  199. MR: "MR",
  200. NULL: "NULL",
  201. WKS: "WKS",
  202. PTR: "PTR",
  203. HINFO: "HINFO",
  204. MINFO: "MINFO",
  205. MX: "MX",
  206. TXT: "TXT",
  207. RP: "RP",
  208. AFSDB: "AFSDB",
  209. # 19 through 27? Eh, I'll get to 'em.
  210. AAAA: "AAAA",
  211. SRV: "SRV",
  212. NAPTR: "NAPTR",
  213. A6: "A6",
  214. DNAME: "DNAME",
  215. OPT: "OPT",
  216. SSHFP: "SSHFP",
  217. SPF: "SPF",
  218. TKEY: "TKEY",
  219. TSIG: "TSIG",
  220. }
  221. IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = range(251, 256)
  222. # "Extended" queries (Hey, half of these are deprecated, good job)
  223. EXT_QUERIES = {
  224. IXFR: "IXFR",
  225. AXFR: "AXFR",
  226. MAILB: "MAILB",
  227. MAILA: "MAILA",
  228. ALL_RECORDS: "ALL_RECORDS",
  229. }
  230. REV_TYPES = {v: k for (k, v) in chain(QUERY_TYPES.items(), EXT_QUERIES.items())}
  231. IN, CS, CH, HS = range(1, 5)
  232. ANY = 255
  233. QUERY_CLASSES = {IN: "IN", CS: "CS", CH: "CH", HS: "HS", ANY: "ANY"}
  234. REV_CLASSES = {v: k for (k, v) in QUERY_CLASSES.items()}
  235. # Opcodes
  236. OP_QUERY, OP_INVERSE, OP_STATUS = range(3)
  237. OP_NOTIFY = 4 # RFC 1996
  238. OP_UPDATE = 5 # RFC 2136
  239. # Response Codes
  240. OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = range(6)
  241. # https://tools.ietf.org/html/rfc6891#section-9
  242. EBADVERSION = 16
  243. # RFC 2845
  244. EBADSIG, EBADKEY, EBADTIME = range(16, 19)
  245. class IRecord(Interface):
  246. """
  247. A single entry in a zone of authority.
  248. """
  249. TYPE = Attribute("An indicator of what kind of record this is.")
  250. # Backwards compatibility aliases - these should be deprecated or something I
  251. # suppose. -exarkun
  252. from twisted.names.error import (
  253. AuthoritativeDomainError,
  254. DNSQueryTimeoutError,
  255. DomainError,
  256. )
  257. def _nameToLabels(name):
  258. """
  259. Split a domain name into its constituent labels.
  260. @type name: L{bytes}
  261. @param name: A fully qualified domain name (with or without a
  262. trailing dot).
  263. @return: A L{list} of labels ending with an empty label
  264. representing the DNS root zone.
  265. @rtype: L{list} of L{bytes}
  266. """
  267. if name in (b"", b"."):
  268. return [b""]
  269. labels = name.split(b".")
  270. if labels[-1] != b"":
  271. labels.append(b"")
  272. return labels
  273. def domainString(domain):
  274. """
  275. Coerce a domain name string to bytes.
  276. L{twisted.names} represents domain names as L{bytes}, but many interfaces
  277. accept L{bytes} or a text string (L{unicode} on Python 2, L{str} on Python
  278. 3). This function coerces text strings using IDNA encoding --- see
  279. L{encodings.idna}.
  280. Note that DNS is I{case insensitive} but I{case preserving}. This function
  281. doesn't normalize case, so you'll still need to do that whenever comparing
  282. the strings it returns.
  283. @param domain: A domain name. If passed as a text string it will be
  284. C{idna} encoded.
  285. @type domain: L{bytes} or L{str}
  286. @returns: L{bytes} suitable for network transmission.
  287. @rtype: L{bytes}
  288. @since: Twisted 20.3.0
  289. """
  290. if isinstance(domain, str):
  291. domain = domain.encode("idna")
  292. if not isinstance(domain, bytes):
  293. raise TypeError(
  294. "Expected {} or {} but found {!r} of type {}".format(
  295. bytes.__name__, str.__name__, domain, type(domain)
  296. )
  297. )
  298. return domain
  299. def _isSubdomainOf(descendantName, ancestorName):
  300. """
  301. Test whether C{descendantName} is equal to or is a I{subdomain} of
  302. C{ancestorName}.
  303. The names are compared case-insensitively.
  304. The names are treated as byte strings containing one or more
  305. DNS labels separated by B{.}.
  306. C{descendantName} is considered equal if its sequence of labels
  307. exactly matches the labels of C{ancestorName}.
  308. C{descendantName} is considered a I{subdomain} if its sequence of
  309. labels ends with the labels of C{ancestorName}.
  310. @type descendantName: L{bytes}
  311. @param descendantName: The DNS subdomain name.
  312. @type ancestorName: L{bytes}
  313. @param ancestorName: The DNS parent or ancestor domain name.
  314. @return: C{True} if C{descendantName} is equal to or if it is a
  315. subdomain of C{ancestorName}. Otherwise returns C{False}.
  316. """
  317. descendantLabels = _nameToLabels(descendantName.lower())
  318. ancestorLabels = _nameToLabels(ancestorName.lower())
  319. return descendantLabels[-len(ancestorLabels) :] == ancestorLabels
  320. def str2time(s):
  321. """
  322. Parse a string description of an interval into an integer number of seconds.
  323. @param s: An interval definition constructed as an interval duration
  324. followed by an interval unit. An interval duration is a base ten
  325. representation of an integer. An interval unit is one of the following
  326. letters: S (seconds), M (minutes), H (hours), D (days), W (weeks), or Y
  327. (years). For example: C{"3S"} indicates an interval of three seconds;
  328. C{"5D"} indicates an interval of five days. Alternatively, C{s} may be
  329. any non-string and it will be returned unmodified.
  330. @type s: text string (L{bytes} or L{str}) for parsing; anything else
  331. for passthrough.
  332. @return: an L{int} giving the interval represented by the string C{s}, or
  333. whatever C{s} is if it is not a string.
  334. """
  335. suffixes = (
  336. ("S", 1),
  337. ("M", 60),
  338. ("H", 60 * 60),
  339. ("D", 60 * 60 * 24),
  340. ("W", 60 * 60 * 24 * 7),
  341. ("Y", 60 * 60 * 24 * 365),
  342. )
  343. if isinstance(s, bytes):
  344. s = s.decode("ascii")
  345. if isinstance(s, str):
  346. s = s.upper().strip()
  347. for (suff, mult) in suffixes:
  348. if s.endswith(suff):
  349. return int(float(s[:-1]) * mult)
  350. try:
  351. s = int(s)
  352. except ValueError:
  353. raise ValueError("Invalid time interval specifier: " + s)
  354. return s
  355. def readPrecisely(file, l):
  356. buff = file.read(l)
  357. if len(buff) < l:
  358. raise EOFError
  359. return buff
  360. class IEncodable(Interface):
  361. """
  362. Interface for something which can be encoded to and decoded
  363. to the DNS wire format.
  364. A binary-mode file object (such as L{io.BytesIO}) is used as a buffer when
  365. encoding or decoding.
  366. """
  367. def encode(strio, compDict=None):
  368. """
  369. Write a representation of this object to the given
  370. file object.
  371. @type strio: File-like object
  372. @param strio: The buffer to write to. It must have a C{tell()} method.
  373. @type compDict: L{dict} of L{bytes} to L{int} r L{None}
  374. @param compDict: A mapping of names to byte offsets that have already
  375. been written to the buffer, which may be used for compression (see RFC
  376. 1035 section 4.1.4). When L{None}, encode without compression.
  377. """
  378. def decode(strio, length=None):
  379. """
  380. Reconstruct an object from data read from the given
  381. file object.
  382. @type strio: File-like object
  383. @param strio: A seekable buffer from which bytes may be read.
  384. @type length: L{int} or L{None}
  385. @param length: The number of bytes in this RDATA field. Most
  386. implementations can ignore this value. Only in the case of
  387. records similar to TXT where the total length is in no way
  388. encoded in the data is it necessary.
  389. """
  390. class IEncodableRecord(IEncodable, IRecord):
  391. """
  392. Interface for DNS records that can be encoded and decoded.
  393. @since: Twisted 21.2.0
  394. """
  395. @implementer(IEncodable)
  396. class Charstr:
  397. def __init__(self, string=b""):
  398. if not isinstance(string, bytes):
  399. raise ValueError(f"{string!r} is not a byte string")
  400. self.string = string
  401. def encode(self, strio, compDict=None):
  402. """
  403. Encode this Character string into the appropriate byte format.
  404. @type strio: file
  405. @param strio: The byte representation of this Charstr will be written
  406. to this file.
  407. """
  408. string = self.string
  409. ind = len(string)
  410. strio.write(_ord2bytes(ind))
  411. strio.write(string)
  412. def decode(self, strio, length=None):
  413. """
  414. Decode a byte string into this Charstr.
  415. @type strio: file
  416. @param strio: Bytes will be read from this file until the full string
  417. is decoded.
  418. @raise EOFError: Raised when there are not enough bytes available from
  419. C{strio}.
  420. """
  421. self.string = b""
  422. l = ord(readPrecisely(strio, 1))
  423. self.string = readPrecisely(strio, l)
  424. def __eq__(self, other: object) -> bool:
  425. if isinstance(other, Charstr):
  426. return self.string == other.string
  427. return NotImplemented
  428. def __hash__(self):
  429. return hash(self.string)
  430. def __str__(self) -> str:
  431. """
  432. Represent this L{Charstr} instance by its string value.
  433. """
  434. return nativeString(self.string)
  435. @implementer(IEncodable)
  436. class Name:
  437. """
  438. A name in the domain name system, made up of multiple labels. For example,
  439. I{twistedmatrix.com}.
  440. @ivar name: A byte string giving the name.
  441. @type name: L{bytes}
  442. """
  443. def __init__(self, name=b""):
  444. """
  445. @param name: A name.
  446. @type name: L{bytes} or L{str}
  447. """
  448. self.name = domainString(name)
  449. def encode(self, strio, compDict=None):
  450. """
  451. Encode this Name into the appropriate byte format.
  452. @type strio: file
  453. @param strio: The byte representation of this Name will be written to
  454. this file.
  455. @type compDict: dict
  456. @param compDict: dictionary of Names that have already been encoded
  457. and whose addresses may be backreferenced by this Name (for the purpose
  458. of reducing the message size).
  459. """
  460. name = self.name
  461. while name:
  462. if compDict is not None:
  463. if name in compDict:
  464. strio.write(struct.pack("!H", 0xC000 | compDict[name]))
  465. return
  466. else:
  467. compDict[name] = strio.tell() + Message.headerSize
  468. ind = name.find(b".")
  469. if ind > 0:
  470. label, name = name[:ind], name[ind + 1 :]
  471. else:
  472. # This is the last label, end the loop after handling it.
  473. label = name
  474. name = None
  475. ind = len(label)
  476. strio.write(_ord2bytes(ind))
  477. strio.write(label)
  478. strio.write(b"\x00")
  479. def decode(self, strio, length=None):
  480. """
  481. Decode a byte string into this Name.
  482. @type strio: file
  483. @param strio: Bytes will be read from this file until the full Name
  484. is decoded.
  485. @raise EOFError: Raised when there are not enough bytes available
  486. from C{strio}.
  487. @raise ValueError: Raised when the name cannot be decoded (for example,
  488. because it contains a loop).
  489. """
  490. visited = set()
  491. self.name = b""
  492. off = 0
  493. while 1:
  494. l = ord(readPrecisely(strio, 1))
  495. if l == 0:
  496. if off > 0:
  497. strio.seek(off)
  498. return
  499. if (l >> 6) == 3:
  500. new_off = (l & 63) << 8 | ord(readPrecisely(strio, 1))
  501. if new_off in visited:
  502. raise ValueError("Compression loop in encoded name")
  503. visited.add(new_off)
  504. if off == 0:
  505. off = strio.tell()
  506. strio.seek(new_off)
  507. continue
  508. label = readPrecisely(strio, l)
  509. if self.name == b"":
  510. self.name = label
  511. else:
  512. self.name = self.name + b"." + label
  513. def __eq__(self, other: object) -> bool:
  514. if isinstance(other, Name):
  515. return self.name.lower() == other.name.lower()
  516. return NotImplemented
  517. def __hash__(self):
  518. return hash(self.name)
  519. def __str__(self) -> str:
  520. """
  521. Represent this L{Name} instance by its string name.
  522. """
  523. return nativeString(self.name)
  524. @comparable
  525. @implementer(IEncodable)
  526. class Query:
  527. """
  528. Represent a single DNS query.
  529. @ivar name: The name about which this query is requesting information.
  530. @type name: L{Name}
  531. @ivar type: The query type.
  532. @type type: L{int}
  533. @ivar cls: The query class.
  534. @type cls: L{int}
  535. """
  536. def __init__(self, name: Union[bytes, str] = b"", type: int = A, cls: int = IN):
  537. """
  538. @type name: L{bytes} or L{str}
  539. @param name: See L{Query.name}
  540. @type type: L{int}
  541. @param type: The query type.
  542. @type cls: L{int}
  543. @param cls: The query class.
  544. """
  545. self.name = Name(name)
  546. self.type = type
  547. self.cls = cls
  548. def encode(self, strio, compDict=None):
  549. self.name.encode(strio, compDict)
  550. strio.write(struct.pack("!HH", self.type, self.cls))
  551. def decode(self, strio, length=None):
  552. self.name.decode(strio)
  553. buff = readPrecisely(strio, 4)
  554. self.type, self.cls = struct.unpack("!HH", buff)
  555. def __hash__(self):
  556. return hash((self.name.name.lower(), self.type, self.cls))
  557. def __cmp__(self, other):
  558. if isinstance(other, Query):
  559. return cmp(
  560. (self.name.name.lower(), self.type, self.cls),
  561. (other.name.name.lower(), other.type, other.cls),
  562. )
  563. return NotImplemented
  564. def __str__(self) -> str:
  565. t = QUERY_TYPES.get(
  566. self.type, EXT_QUERIES.get(self.type, "UNKNOWN (%d)" % self.type)
  567. )
  568. c = QUERY_CLASSES.get(self.cls, "UNKNOWN (%d)" % self.cls)
  569. return f"<Query {self.name} {t} {c}>"
  570. def __repr__(self) -> str:
  571. return f"Query({self.name.name!r}, {self.type!r}, {self.cls!r})"
  572. @implementer(IEncodable)
  573. class _OPTHeader(tputil.FancyStrMixin, tputil.FancyEqMixin):
  574. """
  575. An OPT record header.
  576. @ivar name: The DNS name associated with this record. Since this
  577. is a pseudo record, the name is always an L{Name} instance
  578. with value b'', which represents the DNS root zone. This
  579. attribute is a readonly property.
  580. @ivar type: The DNS record type. This is a fixed value of 41
  581. C{dns.OPT} for OPT Record. This attribute is a readonly
  582. property.
  583. @see: L{_OPTHeader.__init__} for documentation of other public
  584. instance attributes.
  585. @see: U{https://tools.ietf.org/html/rfc6891#section-6.1.2}
  586. @since: 13.2
  587. """
  588. showAttributes = (
  589. ("name", lambda n: nativeString(n.name)),
  590. "type",
  591. "udpPayloadSize",
  592. "extendedRCODE",
  593. "version",
  594. "dnssecOK",
  595. "options",
  596. )
  597. compareAttributes = (
  598. "name",
  599. "type",
  600. "udpPayloadSize",
  601. "extendedRCODE",
  602. "version",
  603. "dnssecOK",
  604. "options",
  605. )
  606. def __init__(
  607. self,
  608. udpPayloadSize=4096,
  609. extendedRCODE=0,
  610. version=0,
  611. dnssecOK=False,
  612. options=None,
  613. ):
  614. """
  615. @type udpPayloadSize: L{int}
  616. @param udpPayloadSize: The number of octets of the largest UDP
  617. payload that can be reassembled and delivered in the
  618. requestor's network stack.
  619. @type extendedRCODE: L{int}
  620. @param extendedRCODE: Forms the upper 8 bits of extended
  621. 12-bit RCODE (together with the 4 bits defined in
  622. [RFC1035]. Note that EXTENDED-RCODE value 0 indicates
  623. that an unextended RCODE is in use (values 0 through 15).
  624. @type version: L{int}
  625. @param version: Indicates the implementation level of the
  626. setter. Full conformance with this specification is
  627. indicated by version C{0}.
  628. @type dnssecOK: L{bool}
  629. @param dnssecOK: DNSSEC OK bit as defined by [RFC3225].
  630. @type options: L{list}
  631. @param options: A L{list} of 0 or more L{_OPTVariableOption}
  632. instances.
  633. """
  634. self.udpPayloadSize = udpPayloadSize
  635. self.extendedRCODE = extendedRCODE
  636. self.version = version
  637. self.dnssecOK = dnssecOK
  638. if options is None:
  639. options = []
  640. self.options = options
  641. @property
  642. def name(self):
  643. """
  644. A readonly property for accessing the C{name} attribute of
  645. this record.
  646. @return: The DNS name associated with this record. Since this
  647. is a pseudo record, the name is always an L{Name} instance
  648. with value b'', which represents the DNS root zone.
  649. """
  650. return Name(b"")
  651. @property
  652. def type(self):
  653. """
  654. A readonly property for accessing the C{type} attribute of
  655. this record.
  656. @return: The DNS record type. This is a fixed value of 41
  657. (C{dns.OPT} for OPT Record.
  658. """
  659. return OPT
  660. def encode(self, strio, compDict=None):
  661. """
  662. Encode this L{_OPTHeader} instance to bytes.
  663. @type strio: file
  664. @param strio: the byte representation of this L{_OPTHeader}
  665. will be written to this file.
  666. @type compDict: L{dict} or L{None}
  667. @param compDict: A dictionary of backreference addresses that
  668. have already been written to this stream and that may
  669. be used for DNS name compression.
  670. """
  671. b = BytesIO()
  672. for o in self.options:
  673. o.encode(b)
  674. optionBytes = b.getvalue()
  675. RRHeader(
  676. name=self.name.name,
  677. type=self.type,
  678. cls=self.udpPayloadSize,
  679. ttl=(self.extendedRCODE << 24 | self.version << 16 | self.dnssecOK << 15),
  680. payload=UnknownRecord(optionBytes),
  681. ).encode(strio, compDict)
  682. def decode(self, strio, length=None):
  683. """
  684. Decode bytes into an L{_OPTHeader} instance.
  685. @type strio: file
  686. @param strio: Bytes will be read from this file until the full
  687. L{_OPTHeader} is decoded.
  688. @type length: L{int} or L{None}
  689. @param length: Not used.
  690. """
  691. h = RRHeader()
  692. h.decode(strio, length)
  693. h.payload = UnknownRecord(readPrecisely(strio, h.rdlength))
  694. newOptHeader = self.fromRRHeader(h)
  695. for attrName in self.compareAttributes:
  696. if attrName not in ("name", "type"):
  697. setattr(self, attrName, getattr(newOptHeader, attrName))
  698. @classmethod
  699. def fromRRHeader(cls, rrHeader):
  700. """
  701. A classmethod for constructing a new L{_OPTHeader} from the
  702. attributes and payload of an existing L{RRHeader} instance.
  703. @type rrHeader: L{RRHeader}
  704. @param rrHeader: An L{RRHeader} instance containing an
  705. L{UnknownRecord} payload.
  706. @return: An instance of L{_OPTHeader}.
  707. @rtype: L{_OPTHeader}
  708. """
  709. options = None
  710. if rrHeader.payload is not None:
  711. options = []
  712. optionsBytes = BytesIO(rrHeader.payload.data)
  713. optionsBytesLength = len(rrHeader.payload.data)
  714. while optionsBytes.tell() < optionsBytesLength:
  715. o = _OPTVariableOption()
  716. o.decode(optionsBytes)
  717. options.append(o)
  718. # Decode variable options if present
  719. return cls(
  720. udpPayloadSize=rrHeader.cls,
  721. extendedRCODE=rrHeader.ttl >> 24,
  722. version=rrHeader.ttl >> 16 & 0xFF,
  723. dnssecOK=(rrHeader.ttl & 0xFFFF) >> 15,
  724. options=options,
  725. )
  726. @implementer(IEncodable)
  727. class _OPTVariableOption(tputil.FancyStrMixin, tputil.FancyEqMixin):
  728. """
  729. A class to represent OPT record variable options.
  730. @see: L{_OPTVariableOption.__init__} for documentation of public
  731. instance attributes.
  732. @see: U{https://tools.ietf.org/html/rfc6891#section-6.1.2}
  733. @since: 13.2
  734. """
  735. showAttributes = ("code", ("data", nativeString))
  736. compareAttributes = ("code", "data")
  737. _fmt = "!HH"
  738. def __init__(self, code=0, data=b""):
  739. """
  740. @type code: L{int}
  741. @param code: The option code
  742. @type data: L{bytes}
  743. @param data: The option data
  744. """
  745. self.code = code
  746. self.data = data
  747. def encode(self, strio, compDict=None):
  748. """
  749. Encode this L{_OPTVariableOption} to bytes.
  750. @type strio: file
  751. @param strio: the byte representation of this
  752. L{_OPTVariableOption} will be written to this file.
  753. @type compDict: L{dict} or L{None}
  754. @param compDict: A dictionary of backreference addresses that
  755. have already been written to this stream and that may
  756. be used for DNS name compression.
  757. """
  758. strio.write(struct.pack(self._fmt, self.code, len(self.data)) + self.data)
  759. def decode(self, strio, length=None):
  760. """
  761. Decode bytes into an L{_OPTVariableOption} instance.
  762. @type strio: file
  763. @param strio: Bytes will be read from this file until the full
  764. L{_OPTVariableOption} is decoded.
  765. @type length: L{int} or L{None}
  766. @param length: Not used.
  767. """
  768. l = struct.calcsize(self._fmt)
  769. buff = readPrecisely(strio, l)
  770. self.code, length = struct.unpack(self._fmt, buff)
  771. self.data = readPrecisely(strio, length)
  772. @implementer(IEncodable)
  773. class RRHeader(tputil.FancyEqMixin):
  774. """
  775. A resource record header.
  776. @cvar fmt: L{str} specifying the byte format of an RR.
  777. @ivar name: The name about which this reply contains information.
  778. @type name: L{Name}
  779. @ivar type: The query type of the original request.
  780. @type type: L{int}
  781. @ivar cls: The query class of the original request.
  782. @ivar ttl: The time-to-live for this record.
  783. @type ttl: L{int}
  784. @ivar payload: The record described by this header.
  785. @type payload: L{IEncodableRecord} or L{None}
  786. @ivar auth: A L{bool} indicating whether this C{RRHeader} was parsed from
  787. an authoritative message.
  788. """
  789. compareAttributes = ("name", "type", "cls", "ttl", "payload", "auth")
  790. fmt = "!HHIH"
  791. rdlength = None
  792. cachedResponse = None
  793. def __init__(
  794. self,
  795. name: Union[bytes, str] = b"",
  796. type: int = A,
  797. cls: int = IN,
  798. ttl: SupportsInt = 0,
  799. payload: Optional[IEncodableRecord] = None,
  800. auth: bool = False,
  801. ):
  802. """
  803. @type name: L{bytes} or L{str}
  804. @param name: See L{RRHeader.name}
  805. @type type: L{int}
  806. @param type: The query type.
  807. @type cls: L{int}
  808. @param cls: The query class.
  809. @type ttl: L{int}
  810. @param ttl: Time to live for this record. This will be
  811. converted to an L{int}.
  812. @type payload: L{IEncodableRecord} or L{None}
  813. @param payload: An optional Query Type specific data object.
  814. @raises TypeError: if the ttl cannot be converted to an L{int}.
  815. @raises ValueError: if the ttl is negative.
  816. @raises ValueError: if the payload type is not equal to the C{type}
  817. argument.
  818. """
  819. payloadType = None if payload is None else payload.TYPE
  820. if payloadType is not None and payloadType != type:
  821. raise ValueError(
  822. "Payload type (%s) does not match given type (%s)"
  823. % (
  824. QUERY_TYPES.get(payloadType, payloadType),
  825. QUERY_TYPES.get(type, type),
  826. )
  827. )
  828. integralTTL = int(ttl)
  829. if integralTTL < 0:
  830. raise ValueError("TTL cannot be negative")
  831. self.name = Name(name)
  832. self.type = type
  833. self.cls = cls
  834. self.ttl = integralTTL
  835. self.payload = payload
  836. self.auth = auth
  837. def encode(self, strio, compDict=None):
  838. self.name.encode(strio, compDict)
  839. strio.write(struct.pack(self.fmt, self.type, self.cls, self.ttl, 0))
  840. if self.payload:
  841. prefix = strio.tell()
  842. self.payload.encode(strio, compDict)
  843. aft = strio.tell()
  844. strio.seek(prefix - 2, 0)
  845. strio.write(struct.pack("!H", aft - prefix))
  846. strio.seek(aft, 0)
  847. def decode(self, strio, length=None):
  848. self.name.decode(strio)
  849. l = struct.calcsize(self.fmt)
  850. buff = readPrecisely(strio, l)
  851. r = struct.unpack(self.fmt, buff)
  852. self.type, self.cls, self.ttl, self.rdlength = r
  853. def isAuthoritative(self):
  854. return self.auth
  855. def __str__(self) -> str:
  856. t = QUERY_TYPES.get(
  857. self.type, EXT_QUERIES.get(self.type, "UNKNOWN (%d)" % self.type)
  858. )
  859. c = QUERY_CLASSES.get(self.cls, "UNKNOWN (%d)" % self.cls)
  860. return "<RR name=%s type=%s class=%s ttl=%ds auth=%s>" % (
  861. self.name,
  862. t,
  863. c,
  864. self.ttl,
  865. self.auth and "True" or "False",
  866. )
  867. __repr__ = __str__
  868. @implementer(IEncodableRecord)
  869. class SimpleRecord(tputil.FancyStrMixin, tputil.FancyEqMixin):
  870. """
  871. A Resource Record which consists of a single RFC 1035 domain-name.
  872. @type name: L{Name}
  873. @ivar name: The name associated with this record.
  874. @type ttl: L{int}
  875. @ivar ttl: The maximum number of seconds which this record should be
  876. cached.
  877. """
  878. showAttributes = (("name", "name", "%s"), "ttl")
  879. compareAttributes = ("name", "ttl")
  880. TYPE: Optional[int] = None
  881. name = None
  882. def __init__(self, name=b"", ttl=None):
  883. """
  884. @param name: See L{SimpleRecord.name}
  885. @type name: L{bytes} or L{str}
  886. """
  887. self.name = Name(name)
  888. self.ttl = str2time(ttl)
  889. def encode(self, strio, compDict=None):
  890. self.name.encode(strio, compDict)
  891. def decode(self, strio, length=None):
  892. self.name = Name()
  893. self.name.decode(strio)
  894. def __hash__(self):
  895. return hash(self.name)
  896. # Kinds of RRs - oh my!
  897. class Record_NS(SimpleRecord):
  898. """
  899. An authoritative nameserver.
  900. """
  901. TYPE = NS
  902. fancybasename = "NS"
  903. class Record_MD(SimpleRecord):
  904. """
  905. A mail destination.
  906. This record type is obsolete.
  907. @see: L{Record_MX}
  908. """
  909. TYPE = MD
  910. fancybasename = "MD"
  911. class Record_MF(SimpleRecord):
  912. """
  913. A mail forwarder.
  914. This record type is obsolete.
  915. @see: L{Record_MX}
  916. """
  917. TYPE = MF
  918. fancybasename = "MF"
  919. class Record_CNAME(SimpleRecord):
  920. """
  921. The canonical name for an alias.
  922. """
  923. TYPE = CNAME
  924. fancybasename = "CNAME"
  925. class Record_MB(SimpleRecord):
  926. """
  927. A mailbox domain name.
  928. This is an experimental record type.
  929. """
  930. TYPE = MB
  931. fancybasename = "MB"
  932. class Record_MG(SimpleRecord):
  933. """
  934. A mail group member.
  935. This is an experimental record type.
  936. """
  937. TYPE = MG
  938. fancybasename = "MG"
  939. class Record_MR(SimpleRecord):
  940. """
  941. A mail rename domain name.
  942. This is an experimental record type.
  943. """
  944. TYPE = MR
  945. fancybasename = "MR"
  946. class Record_PTR(SimpleRecord):
  947. """
  948. A domain name pointer.
  949. """
  950. TYPE = PTR
  951. fancybasename = "PTR"
  952. class Record_DNAME(SimpleRecord):
  953. """
  954. A non-terminal DNS name redirection.
  955. This record type provides the capability to map an entire subtree of the
  956. DNS name space to another domain. It differs from the CNAME record which
  957. maps a single node of the name space.
  958. @see: U{http://www.faqs.org/rfcs/rfc2672.html}
  959. @see: U{http://www.faqs.org/rfcs/rfc3363.html}
  960. """
  961. TYPE = DNAME
  962. fancybasename = "DNAME"
  963. @implementer(IEncodableRecord)
  964. class Record_A(tputil.FancyEqMixin):
  965. """
  966. An IPv4 host address.
  967. @type address: L{bytes}
  968. @ivar address: The packed network-order representation of the IPv4 address
  969. associated with this record.
  970. @type ttl: L{int}
  971. @ivar ttl: The maximum number of seconds which this record should be
  972. cached.
  973. """
  974. compareAttributes = ("address", "ttl")
  975. TYPE = A
  976. address = None
  977. def __init__(self, address="0.0.0.0", ttl=None):
  978. """
  979. @type address: L{bytes} or L{str}
  980. @param address: The IPv4 address associated with this record, in
  981. quad-dotted notation.
  982. """
  983. if isinstance(address, bytes):
  984. address = address.decode("ascii")
  985. address = socket.inet_aton(address)
  986. self.address = address
  987. self.ttl = str2time(ttl)
  988. def encode(self, strio, compDict=None):
  989. strio.write(self.address)
  990. def decode(self, strio, length=None):
  991. self.address = readPrecisely(strio, 4)
  992. def __hash__(self):
  993. return hash(self.address)
  994. def __str__(self) -> str:
  995. return f"<A address={self.dottedQuad()} ttl={self.ttl}>"
  996. __repr__ = __str__
  997. def dottedQuad(self):
  998. return socket.inet_ntoa(self.address)
  999. @implementer(IEncodableRecord)
  1000. class Record_SOA(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1001. """
  1002. Marks the start of a zone of authority.
  1003. This record describes parameters which are shared by all records within a
  1004. particular zone.
  1005. @type mname: L{Name}
  1006. @ivar mname: The domain-name of the name server that was the original or
  1007. primary source of data for this zone.
  1008. @type rname: L{Name}
  1009. @ivar rname: A domain-name which specifies the mailbox of the person
  1010. responsible for this zone.
  1011. @type serial: L{int}
  1012. @ivar serial: The unsigned 32 bit version number of the original copy of
  1013. the zone. Zone transfers preserve this value. This value wraps and
  1014. should be compared using sequence space arithmetic.
  1015. @type refresh: L{int}
  1016. @ivar refresh: A 32 bit time interval before the zone should be refreshed.
  1017. @type minimum: L{int}
  1018. @ivar minimum: The unsigned 32 bit minimum TTL field that should be
  1019. exported with any RR from this zone.
  1020. @type expire: L{int}
  1021. @ivar expire: A 32 bit time value that specifies the upper limit on the
  1022. time interval that can elapse before the zone is no longer
  1023. authoritative.
  1024. @type retry: L{int}
  1025. @ivar retry: A 32 bit time interval that should elapse before a failed
  1026. refresh should be retried.
  1027. @type ttl: L{int}
  1028. @ivar ttl: The default TTL to use for records served from this zone.
  1029. """
  1030. fancybasename = "SOA"
  1031. compareAttributes = (
  1032. "serial",
  1033. "mname",
  1034. "rname",
  1035. "refresh",
  1036. "expire",
  1037. "retry",
  1038. "minimum",
  1039. "ttl",
  1040. )
  1041. showAttributes = (
  1042. ("mname", "mname", "%s"),
  1043. ("rname", "rname", "%s"),
  1044. "serial",
  1045. "refresh",
  1046. "retry",
  1047. "expire",
  1048. "minimum",
  1049. "ttl",
  1050. )
  1051. TYPE = SOA
  1052. def __init__(
  1053. self,
  1054. mname=b"",
  1055. rname=b"",
  1056. serial=0,
  1057. refresh=0,
  1058. retry=0,
  1059. expire=0,
  1060. minimum=0,
  1061. ttl=None,
  1062. ):
  1063. """
  1064. @param mname: See L{Record_SOA.mname}
  1065. @type mname: L{bytes} or L{str}
  1066. @param rname: See L{Record_SOA.rname}
  1067. @type rname: L{bytes} or L{str}
  1068. """
  1069. self.mname, self.rname = Name(mname), Name(rname)
  1070. self.serial, self.refresh = str2time(serial), str2time(refresh)
  1071. self.minimum, self.expire = str2time(minimum), str2time(expire)
  1072. self.retry = str2time(retry)
  1073. self.ttl = str2time(ttl)
  1074. def encode(self, strio, compDict=None):
  1075. self.mname.encode(strio, compDict)
  1076. self.rname.encode(strio, compDict)
  1077. strio.write(
  1078. struct.pack(
  1079. "!LlllL",
  1080. self.serial,
  1081. self.refresh,
  1082. self.retry,
  1083. self.expire,
  1084. self.minimum,
  1085. )
  1086. )
  1087. def decode(self, strio, length=None):
  1088. self.mname, self.rname = Name(), Name()
  1089. self.mname.decode(strio)
  1090. self.rname.decode(strio)
  1091. r = struct.unpack("!LlllL", readPrecisely(strio, 20))
  1092. self.serial, self.refresh, self.retry, self.expire, self.minimum = r
  1093. def __hash__(self):
  1094. return hash(
  1095. (self.serial, self.mname, self.rname, self.refresh, self.expire, self.retry)
  1096. )
  1097. @implementer(IEncodableRecord)
  1098. class Record_NULL(tputil.FancyStrMixin, tputil.FancyEqMixin):
  1099. """
  1100. A null record.
  1101. This is an experimental record type.
  1102. @type ttl: L{int}
  1103. @ivar ttl: The maximum number of seconds which this record should be
  1104. cached.
  1105. """
  1106. fancybasename = "NULL"
  1107. showAttributes = (("payload", _nicebytes), "ttl")
  1108. compareAttributes = ("payload", "ttl")
  1109. TYPE = NULL
  1110. def __init__(self, payload=None, ttl=None):
  1111. self.payload = payload
  1112. self.ttl = str2time(ttl)
  1113. def encode(self, strio, compDict=None):
  1114. strio.write(self.payload)
  1115. def decode(self, strio, length=None):
  1116. self.payload = readPrecisely(strio, length)
  1117. def __hash__(self):
  1118. return hash(self.payload)
  1119. @implementer(IEncodableRecord)
  1120. class Record_WKS(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1121. """
  1122. A well known service description.
  1123. This record type is obsolete. See L{Record_SRV}.
  1124. @type address: L{bytes}
  1125. @ivar address: The packed network-order representation of the IPv4 address
  1126. associated with this record.
  1127. @type protocol: L{int}
  1128. @ivar protocol: The 8 bit IP protocol number for which this service map is
  1129. relevant.
  1130. @type map: L{bytes}
  1131. @ivar map: A bitvector indicating the services available at the specified
  1132. address.
  1133. @type ttl: L{int}
  1134. @ivar ttl: The maximum number of seconds which this record should be
  1135. cached.
  1136. """
  1137. fancybasename = "WKS"
  1138. compareAttributes = ("address", "protocol", "map", "ttl")
  1139. showAttributes = [("_address", "address", "%s"), "protocol", "ttl"]
  1140. TYPE = WKS
  1141. @property
  1142. def _address(self):
  1143. return socket.inet_ntoa(self.address)
  1144. def __init__(self, address="0.0.0.0", protocol=0, map=b"", ttl=None):
  1145. """
  1146. @type address: L{bytes} or L{str}
  1147. @param address: The IPv4 address associated with this record, in
  1148. quad-dotted notation.
  1149. """
  1150. if isinstance(address, bytes):
  1151. address = address.decode("idna")
  1152. self.address = socket.inet_aton(address)
  1153. self.protocol, self.map = protocol, map
  1154. self.ttl = str2time(ttl)
  1155. def encode(self, strio, compDict=None):
  1156. strio.write(self.address)
  1157. strio.write(struct.pack("!B", self.protocol))
  1158. strio.write(self.map)
  1159. def decode(self, strio, length=None):
  1160. self.address = readPrecisely(strio, 4)
  1161. self.protocol = struct.unpack("!B", readPrecisely(strio, 1))[0]
  1162. self.map = readPrecisely(strio, length - 5)
  1163. def __hash__(self):
  1164. return hash((self.address, self.protocol, self.map))
  1165. @implementer(IEncodableRecord)
  1166. class Record_AAAA(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1167. """
  1168. An IPv6 host address.
  1169. @type address: L{bytes}
  1170. @ivar address: The packed network-order representation of the IPv6 address
  1171. associated with this record.
  1172. @type ttl: L{int}
  1173. @ivar ttl: The maximum number of seconds which this record should be
  1174. cached.
  1175. @see: U{http://www.faqs.org/rfcs/rfc1886.html}
  1176. """
  1177. TYPE = AAAA
  1178. fancybasename = "AAAA"
  1179. showAttributes = (("_address", "address", "%s"), "ttl")
  1180. compareAttributes = ("address", "ttl")
  1181. @property
  1182. def _address(self):
  1183. return socket.inet_ntop(AF_INET6, self.address)
  1184. def __init__(self, address="::", ttl=None):
  1185. """
  1186. @type address: L{bytes} or L{str}
  1187. @param address: The IPv6 address for this host, in RFC 2373 format.
  1188. """
  1189. if isinstance(address, bytes):
  1190. address = address.decode("idna")
  1191. self.address = socket.inet_pton(AF_INET6, address)
  1192. self.ttl = str2time(ttl)
  1193. def encode(self, strio, compDict=None):
  1194. strio.write(self.address)
  1195. def decode(self, strio, length=None):
  1196. self.address = readPrecisely(strio, 16)
  1197. def __hash__(self):
  1198. return hash(self.address)
  1199. @implementer(IEncodableRecord)
  1200. class Record_A6(tputil.FancyStrMixin, tputil.FancyEqMixin):
  1201. """
  1202. An IPv6 address.
  1203. This is an experimental record type.
  1204. @type prefixLen: L{int}
  1205. @ivar prefixLen: The length of the suffix.
  1206. @type suffix: L{bytes}
  1207. @ivar suffix: An IPv6 address suffix in network order.
  1208. @type prefix: L{Name}
  1209. @ivar prefix: If specified, a name which will be used as a prefix for other
  1210. A6 records.
  1211. @type bytes: L{int}
  1212. @ivar bytes: The length of the prefix.
  1213. @type ttl: L{int}
  1214. @ivar ttl: The maximum number of seconds which this record should be
  1215. cached.
  1216. @see: U{http://www.faqs.org/rfcs/rfc2874.html}
  1217. @see: U{http://www.faqs.org/rfcs/rfc3363.html}
  1218. @see: U{http://www.faqs.org/rfcs/rfc3364.html}
  1219. """
  1220. TYPE = A6
  1221. fancybasename = "A6"
  1222. showAttributes = (("_suffix", "suffix", "%s"), ("prefix", "prefix", "%s"), "ttl")
  1223. compareAttributes = ("prefixLen", "prefix", "suffix", "ttl")
  1224. @property
  1225. def _suffix(self):
  1226. return socket.inet_ntop(AF_INET6, self.suffix)
  1227. def __init__(self, prefixLen=0, suffix="::", prefix=b"", ttl=None):
  1228. """
  1229. @param suffix: An IPv6 address suffix in in RFC 2373 format.
  1230. @type suffix: L{bytes} or L{str}
  1231. @param prefix: An IPv6 address prefix for other A6 records.
  1232. @type prefix: L{bytes} or L{str}
  1233. """
  1234. if isinstance(suffix, bytes):
  1235. suffix = suffix.decode("idna")
  1236. self.prefixLen = prefixLen
  1237. self.suffix = socket.inet_pton(AF_INET6, suffix)
  1238. self.prefix = Name(prefix)
  1239. self.bytes = int((128 - self.prefixLen) / 8.0)
  1240. self.ttl = str2time(ttl)
  1241. def encode(self, strio, compDict=None):
  1242. strio.write(struct.pack("!B", self.prefixLen))
  1243. if self.bytes:
  1244. strio.write(self.suffix[-self.bytes :])
  1245. if self.prefixLen:
  1246. # This may not be compressed
  1247. self.prefix.encode(strio, None)
  1248. def decode(self, strio, length=None):
  1249. self.prefixLen = struct.unpack("!B", readPrecisely(strio, 1))[0]
  1250. self.bytes = int((128 - self.prefixLen) / 8.0)
  1251. if self.bytes:
  1252. self.suffix = b"\x00" * (16 - self.bytes) + readPrecisely(strio, self.bytes)
  1253. if self.prefixLen:
  1254. self.prefix.decode(strio)
  1255. def __eq__(self, other: object) -> bool:
  1256. if isinstance(other, Record_A6):
  1257. return (
  1258. self.prefixLen == other.prefixLen
  1259. and self.suffix[-self.bytes :] == other.suffix[-self.bytes :]
  1260. and self.prefix == other.prefix
  1261. and self.ttl == other.ttl
  1262. )
  1263. return NotImplemented
  1264. def __hash__(self):
  1265. return hash((self.prefixLen, self.suffix[-self.bytes :], self.prefix))
  1266. def __str__(self) -> str:
  1267. return "<A6 %s %s (%d) ttl=%s>" % (
  1268. self.prefix,
  1269. socket.inet_ntop(AF_INET6, self.suffix),
  1270. self.prefixLen,
  1271. self.ttl,
  1272. )
  1273. @implementer(IEncodableRecord)
  1274. class Record_SRV(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1275. """
  1276. The location of the server(s) for a specific protocol and domain.
  1277. This is an experimental record type.
  1278. @type priority: L{int}
  1279. @ivar priority: The priority of this target host. A client MUST attempt to
  1280. contact the target host with the lowest-numbered priority it can reach;
  1281. target hosts with the same priority SHOULD be tried in an order defined
  1282. by the weight field.
  1283. @type weight: L{int}
  1284. @ivar weight: Specifies a relative weight for entries with the same
  1285. priority. Larger weights SHOULD be given a proportionately higher
  1286. probability of being selected.
  1287. @type port: L{int}
  1288. @ivar port: The port on this target host of this service.
  1289. @type target: L{Name}
  1290. @ivar target: The domain name of the target host. There MUST be one or
  1291. more address records for this name, the name MUST NOT be an alias (in
  1292. the sense of RFC 1034 or RFC 2181). Implementors are urged, but not
  1293. required, to return the address record(s) in the Additional Data
  1294. section. Unless and until permitted by future standards action, name
  1295. compression is not to be used for this field.
  1296. @type ttl: L{int}
  1297. @ivar ttl: The maximum number of seconds which this record should be
  1298. cached.
  1299. @see: U{http://www.faqs.org/rfcs/rfc2782.html}
  1300. """
  1301. TYPE = SRV
  1302. fancybasename = "SRV"
  1303. compareAttributes = ("priority", "weight", "target", "port", "ttl")
  1304. showAttributes = ("priority", "weight", ("target", "target", "%s"), "port", "ttl")
  1305. def __init__(self, priority=0, weight=0, port=0, target=b"", ttl=None):
  1306. """
  1307. @param target: See L{Record_SRV.target}
  1308. @type target: L{bytes} or L{str}
  1309. """
  1310. self.priority = int(priority)
  1311. self.weight = int(weight)
  1312. self.port = int(port)
  1313. self.target = Name(target)
  1314. self.ttl = str2time(ttl)
  1315. def encode(self, strio, compDict=None):
  1316. strio.write(struct.pack("!HHH", self.priority, self.weight, self.port))
  1317. # This can't be compressed
  1318. self.target.encode(strio, None)
  1319. def decode(self, strio, length=None):
  1320. r = struct.unpack("!HHH", readPrecisely(strio, struct.calcsize("!HHH")))
  1321. self.priority, self.weight, self.port = r
  1322. self.target = Name()
  1323. self.target.decode(strio)
  1324. def __hash__(self):
  1325. return hash((self.priority, self.weight, self.port, self.target))
  1326. @implementer(IEncodableRecord)
  1327. class Record_NAPTR(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1328. """
  1329. The location of the server(s) for a specific protocol and domain.
  1330. @type order: L{int}
  1331. @ivar order: An integer specifying the order in which the NAPTR records
  1332. MUST be processed to ensure the correct ordering of rules. Low numbers
  1333. are processed before high numbers.
  1334. @type preference: L{int}
  1335. @ivar preference: An integer that specifies the order in which NAPTR
  1336. records with equal "order" values SHOULD be processed, low numbers
  1337. being processed before high numbers.
  1338. @type flag: L{Charstr}
  1339. @ivar flag: A <character-string> containing flags to control aspects of the
  1340. rewriting and interpretation of the fields in the record. Flags
  1341. are single characters from the set [A-Z0-9]. The case of the alphabetic
  1342. characters is not significant.
  1343. At this time only four flags, "S", "A", "U", and "P", are defined.
  1344. @type service: L{Charstr}
  1345. @ivar service: Specifies the service(s) available down this rewrite path.
  1346. It may also specify the particular protocol that is used to talk with a
  1347. service. A protocol MUST be specified if the flags field states that
  1348. the NAPTR is terminal.
  1349. @type regexp: L{Charstr}
  1350. @ivar regexp: A STRING containing a substitution expression that is applied
  1351. to the original string held by the client in order to construct the
  1352. next domain name to lookup.
  1353. @type replacement: L{Name}
  1354. @ivar replacement: The next NAME to query for NAPTR, SRV, or address
  1355. records depending on the value of the flags field. This MUST be a
  1356. fully qualified domain-name.
  1357. @type ttl: L{int}
  1358. @ivar ttl: The maximum number of seconds which this record should be
  1359. cached.
  1360. @see: U{http://www.faqs.org/rfcs/rfc2915.html}
  1361. """
  1362. TYPE = NAPTR
  1363. compareAttributes = (
  1364. "order",
  1365. "preference",
  1366. "flags",
  1367. "service",
  1368. "regexp",
  1369. "replacement",
  1370. )
  1371. fancybasename = "NAPTR"
  1372. showAttributes = (
  1373. "order",
  1374. "preference",
  1375. ("flags", "flags", "%s"),
  1376. ("service", "service", "%s"),
  1377. ("regexp", "regexp", "%s"),
  1378. ("replacement", "replacement", "%s"),
  1379. "ttl",
  1380. )
  1381. def __init__(
  1382. self,
  1383. order=0,
  1384. preference=0,
  1385. flags=b"",
  1386. service=b"",
  1387. regexp=b"",
  1388. replacement=b"",
  1389. ttl=None,
  1390. ):
  1391. """
  1392. @param replacement: See L{Record_NAPTR.replacement}
  1393. @type replacement: L{bytes} or L{str}
  1394. """
  1395. self.order = int(order)
  1396. self.preference = int(preference)
  1397. self.flags = Charstr(flags)
  1398. self.service = Charstr(service)
  1399. self.regexp = Charstr(regexp)
  1400. self.replacement = Name(replacement)
  1401. self.ttl = str2time(ttl)
  1402. def encode(self, strio, compDict=None):
  1403. strio.write(struct.pack("!HH", self.order, self.preference))
  1404. # This can't be compressed
  1405. self.flags.encode(strio, None)
  1406. self.service.encode(strio, None)
  1407. self.regexp.encode(strio, None)
  1408. self.replacement.encode(strio, None)
  1409. def decode(self, strio, length=None):
  1410. r = struct.unpack("!HH", readPrecisely(strio, struct.calcsize("!HH")))
  1411. self.order, self.preference = r
  1412. self.flags = Charstr()
  1413. self.service = Charstr()
  1414. self.regexp = Charstr()
  1415. self.replacement = Name()
  1416. self.flags.decode(strio)
  1417. self.service.decode(strio)
  1418. self.regexp.decode(strio)
  1419. self.replacement.decode(strio)
  1420. def __hash__(self):
  1421. return hash(
  1422. (
  1423. self.order,
  1424. self.preference,
  1425. self.flags,
  1426. self.service,
  1427. self.regexp,
  1428. self.replacement,
  1429. )
  1430. )
  1431. @implementer(IEncodableRecord)
  1432. class Record_AFSDB(tputil.FancyStrMixin, tputil.FancyEqMixin):
  1433. """
  1434. Map from a domain name to the name of an AFS cell database server.
  1435. @type subtype: L{int}
  1436. @ivar subtype: In the case of subtype 1, the host has an AFS version 3.0
  1437. Volume Location Server for the named AFS cell. In the case of subtype
  1438. 2, the host has an authenticated name server holding the cell-root
  1439. directory node for the named DCE/NCA cell.
  1440. @type hostname: L{Name}
  1441. @ivar hostname: The domain name of a host that has a server for the cell
  1442. named by this record.
  1443. @type ttl: L{int}
  1444. @ivar ttl: The maximum number of seconds which this record should be
  1445. cached.
  1446. @see: U{http://www.faqs.org/rfcs/rfc1183.html}
  1447. """
  1448. TYPE = AFSDB
  1449. fancybasename = "AFSDB"
  1450. compareAttributes = ("subtype", "hostname", "ttl")
  1451. showAttributes = ("subtype", ("hostname", "hostname", "%s"), "ttl")
  1452. def __init__(self, subtype=0, hostname=b"", ttl=None):
  1453. """
  1454. @param hostname: See L{Record_AFSDB.hostname}
  1455. @type hostname: L{bytes} or L{str}
  1456. """
  1457. self.subtype = int(subtype)
  1458. self.hostname = Name(hostname)
  1459. self.ttl = str2time(ttl)
  1460. def encode(self, strio, compDict=None):
  1461. strio.write(struct.pack("!H", self.subtype))
  1462. self.hostname.encode(strio, compDict)
  1463. def decode(self, strio, length=None):
  1464. r = struct.unpack("!H", readPrecisely(strio, struct.calcsize("!H")))
  1465. (self.subtype,) = r
  1466. self.hostname.decode(strio)
  1467. def __hash__(self):
  1468. return hash((self.subtype, self.hostname))
  1469. @implementer(IEncodableRecord)
  1470. class Record_RP(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1471. """
  1472. The responsible person for a domain.
  1473. @type mbox: L{Name}
  1474. @ivar mbox: A domain name that specifies the mailbox for the responsible
  1475. person.
  1476. @type txt: L{Name}
  1477. @ivar txt: A domain name for which TXT RR's exist (indirection through
  1478. which allows information sharing about the contents of this RP record).
  1479. @type ttl: L{int}
  1480. @ivar ttl: The maximum number of seconds which this record should be
  1481. cached.
  1482. @see: U{http://www.faqs.org/rfcs/rfc1183.html}
  1483. """
  1484. TYPE = RP
  1485. fancybasename = "RP"
  1486. compareAttributes = ("mbox", "txt", "ttl")
  1487. showAttributes = (("mbox", "mbox", "%s"), ("txt", "txt", "%s"), "ttl")
  1488. def __init__(self, mbox=b"", txt=b"", ttl=None):
  1489. """
  1490. @param mbox: See L{Record_RP.mbox}.
  1491. @type mbox: L{bytes} or L{str}
  1492. @param txt: See L{Record_RP.txt}
  1493. @type txt: L{bytes} or L{str}
  1494. """
  1495. self.mbox = Name(mbox)
  1496. self.txt = Name(txt)
  1497. self.ttl = str2time(ttl)
  1498. def encode(self, strio, compDict=None):
  1499. self.mbox.encode(strio, compDict)
  1500. self.txt.encode(strio, compDict)
  1501. def decode(self, strio, length=None):
  1502. self.mbox = Name()
  1503. self.txt = Name()
  1504. self.mbox.decode(strio)
  1505. self.txt.decode(strio)
  1506. def __hash__(self):
  1507. return hash((self.mbox, self.txt))
  1508. @implementer(IEncodableRecord)
  1509. class Record_HINFO(tputil.FancyStrMixin, tputil.FancyEqMixin):
  1510. """
  1511. Host information.
  1512. @type cpu: L{bytes}
  1513. @ivar cpu: Specifies the CPU type.
  1514. @type os: L{bytes}
  1515. @ivar os: Specifies the OS.
  1516. @type ttl: L{int}
  1517. @ivar ttl: The maximum number of seconds which this record should be
  1518. cached.
  1519. """
  1520. TYPE = HINFO
  1521. fancybasename = "HINFO"
  1522. showAttributes = (("cpu", _nicebytes), ("os", _nicebytes), "ttl")
  1523. compareAttributes = ("cpu", "os", "ttl")
  1524. def __init__(self, cpu=b"", os=b"", ttl=None):
  1525. self.cpu, self.os = cpu, os
  1526. self.ttl = str2time(ttl)
  1527. def encode(self, strio, compDict=None):
  1528. strio.write(struct.pack("!B", len(self.cpu)) + self.cpu)
  1529. strio.write(struct.pack("!B", len(self.os)) + self.os)
  1530. def decode(self, strio, length=None):
  1531. cpu = struct.unpack("!B", readPrecisely(strio, 1))[0]
  1532. self.cpu = readPrecisely(strio, cpu)
  1533. os = struct.unpack("!B", readPrecisely(strio, 1))[0]
  1534. self.os = readPrecisely(strio, os)
  1535. def __eq__(self, other: object) -> bool:
  1536. if isinstance(other, Record_HINFO):
  1537. return (
  1538. self.os.lower() == other.os.lower()
  1539. and self.cpu.lower() == other.cpu.lower()
  1540. and self.ttl == other.ttl
  1541. )
  1542. return NotImplemented
  1543. def __hash__(self):
  1544. return hash((self.os.lower(), self.cpu.lower()))
  1545. @implementer(IEncodableRecord)
  1546. class Record_MINFO(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1547. """
  1548. Mailbox or mail list information.
  1549. This is an experimental record type.
  1550. @type rmailbx: L{Name}
  1551. @ivar rmailbx: A domain-name which specifies a mailbox which is responsible
  1552. for the mailing list or mailbox. If this domain name names the root,
  1553. the owner of the MINFO RR is responsible for itself.
  1554. @type emailbx: L{Name}
  1555. @ivar emailbx: A domain-name which specifies a mailbox which is to receive
  1556. error messages related to the mailing list or mailbox specified by the
  1557. owner of the MINFO record. If this domain name names the root, errors
  1558. should be returned to the sender of the message.
  1559. @type ttl: L{int}
  1560. @ivar ttl: The maximum number of seconds which this record should be
  1561. cached.
  1562. """
  1563. TYPE = MINFO
  1564. rmailbx = None
  1565. emailbx = None
  1566. fancybasename = "MINFO"
  1567. compareAttributes = ("rmailbx", "emailbx", "ttl")
  1568. showAttributes = (
  1569. ("rmailbx", "responsibility", "%s"),
  1570. ("emailbx", "errors", "%s"),
  1571. "ttl",
  1572. )
  1573. def __init__(self, rmailbx=b"", emailbx=b"", ttl=None):
  1574. """
  1575. @param rmailbx: See L{Record_MINFO.rmailbx}.
  1576. @type rmailbx: L{bytes} or L{str}
  1577. @param emailbx: See L{Record_MINFO.rmailbx}.
  1578. @type emailbx: L{bytes} or L{str}
  1579. """
  1580. self.rmailbx, self.emailbx = Name(rmailbx), Name(emailbx)
  1581. self.ttl = str2time(ttl)
  1582. def encode(self, strio, compDict=None):
  1583. self.rmailbx.encode(strio, compDict)
  1584. self.emailbx.encode(strio, compDict)
  1585. def decode(self, strio, length=None):
  1586. self.rmailbx, self.emailbx = Name(), Name()
  1587. self.rmailbx.decode(strio)
  1588. self.emailbx.decode(strio)
  1589. def __hash__(self):
  1590. return hash((self.rmailbx, self.emailbx))
  1591. @implementer(IEncodableRecord)
  1592. class Record_MX(tputil.FancyStrMixin, tputil.FancyEqMixin):
  1593. """
  1594. Mail exchange.
  1595. @type preference: L{int}
  1596. @ivar preference: Specifies the preference given to this RR among others at
  1597. the same owner. Lower values are preferred.
  1598. @type name: L{Name}
  1599. @ivar name: A domain-name which specifies a host willing to act as a mail
  1600. exchange.
  1601. @type ttl: L{int}
  1602. @ivar ttl: The maximum number of seconds which this record should be
  1603. cached.
  1604. """
  1605. TYPE = MX
  1606. fancybasename = "MX"
  1607. compareAttributes = ("preference", "name", "ttl")
  1608. showAttributes = ("preference", ("name", "name", "%s"), "ttl")
  1609. def __init__(self, preference=0, name=b"", ttl=None, **kwargs):
  1610. """
  1611. @param name: See L{Record_MX.name}.
  1612. @type name: L{bytes} or L{str}
  1613. """
  1614. self.preference = int(preference)
  1615. self.name = Name(kwargs.get("exchange", name))
  1616. self.ttl = str2time(ttl)
  1617. def encode(self, strio, compDict=None):
  1618. strio.write(struct.pack("!H", self.preference))
  1619. self.name.encode(strio, compDict)
  1620. def decode(self, strio, length=None):
  1621. self.preference = struct.unpack("!H", readPrecisely(strio, 2))[0]
  1622. self.name = Name()
  1623. self.name.decode(strio)
  1624. def __hash__(self):
  1625. return hash((self.preference, self.name))
  1626. @implementer(IEncodableRecord)
  1627. class Record_SSHFP(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1628. """
  1629. A record containing the fingerprint of an SSH key.
  1630. @type algorithm: L{int}
  1631. @ivar algorithm: The SSH key's algorithm, such as L{ALGORITHM_RSA}.
  1632. Note that the numbering used for SSH key algorithms is specific
  1633. to the SSHFP record, and is not the same as the numbering
  1634. used for KEY or SIG records.
  1635. @type fingerprintType: L{int}
  1636. @ivar fingerprintType: The fingerprint type,
  1637. such as L{FINGERPRINT_TYPE_SHA256}.
  1638. @type fingerprint: L{bytes}
  1639. @ivar fingerprint: The key's fingerprint, e.g. a 32-byte SHA-256 digest.
  1640. @cvar ALGORITHM_RSA: The algorithm value for C{ssh-rsa} keys.
  1641. @cvar ALGORITHM_DSS: The algorithm value for C{ssh-dss} keys.
  1642. @cvar ALGORITHM_ECDSA: The algorithm value for C{ecdsa-sha2-*} keys.
  1643. @cvar ALGORITHM_Ed25519: The algorithm value for C{ed25519} keys.
  1644. @cvar FINGERPRINT_TYPE_SHA1: The type for SHA-1 fingerprints.
  1645. @cvar FINGERPRINT_TYPE_SHA256: The type for SHA-256 fingerprints.
  1646. @see: U{RFC 4255 <https://tools.ietf.org/html/rfc4255>}
  1647. and
  1648. U{RFC 6594 <https://tools.ietf.org/html/rfc6594>}
  1649. """
  1650. fancybasename = "SSHFP"
  1651. compareAttributes = ("algorithm", "fingerprintType", "fingerprint", "ttl")
  1652. showAttributes = ("algorithm", "fingerprintType", "fingerprint")
  1653. TYPE = SSHFP
  1654. ALGORITHM_RSA = 1
  1655. ALGORITHM_DSS = 2
  1656. ALGORITHM_ECDSA = 3
  1657. ALGORITHM_Ed25519 = 4
  1658. FINGERPRINT_TYPE_SHA1 = 1
  1659. FINGERPRINT_TYPE_SHA256 = 2
  1660. def __init__(self, algorithm=0, fingerprintType=0, fingerprint=b"", ttl=0):
  1661. self.algorithm = algorithm
  1662. self.fingerprintType = fingerprintType
  1663. self.fingerprint = fingerprint
  1664. self.ttl = ttl
  1665. def encode(self, strio, compDict=None):
  1666. strio.write(struct.pack("!BB", self.algorithm, self.fingerprintType))
  1667. strio.write(self.fingerprint)
  1668. def decode(self, strio, length=None):
  1669. r = struct.unpack("!BB", readPrecisely(strio, 2))
  1670. (self.algorithm, self.fingerprintType) = r
  1671. self.fingerprint = readPrecisely(strio, length - 2)
  1672. def __hash__(self):
  1673. return hash((self.algorithm, self.fingerprintType, self.fingerprint))
  1674. @implementer(IEncodableRecord)
  1675. class Record_TXT(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1676. """
  1677. Freeform text.
  1678. @type data: L{list} of L{bytes}
  1679. @ivar data: Freeform text which makes up this record.
  1680. @type ttl: L{int}
  1681. @ivar ttl: The maximum number of seconds which this record should be cached.
  1682. """
  1683. TYPE = TXT
  1684. fancybasename = "TXT"
  1685. showAttributes = (("data", _nicebyteslist), "ttl")
  1686. compareAttributes = ("data", "ttl")
  1687. def __init__(self, *data, **kw):
  1688. self.data = list(data)
  1689. # arg man python sucks so bad
  1690. self.ttl = str2time(kw.get("ttl", None))
  1691. def encode(self, strio, compDict=None):
  1692. for d in self.data:
  1693. strio.write(struct.pack("!B", len(d)) + d)
  1694. def decode(self, strio, length=None):
  1695. soFar = 0
  1696. self.data = []
  1697. while soFar < length:
  1698. L = struct.unpack("!B", readPrecisely(strio, 1))[0]
  1699. self.data.append(readPrecisely(strio, L))
  1700. soFar += L + 1
  1701. if soFar != length:
  1702. log.msg(
  1703. "Decoded %d bytes in %s record, but rdlength is %d"
  1704. % (soFar, self.fancybasename, length)
  1705. )
  1706. def __hash__(self):
  1707. return hash(tuple(self.data))
  1708. @implementer(IEncodableRecord)
  1709. class UnknownRecord(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1710. """
  1711. Encapsulate the wire data for unknown record types so that they can
  1712. pass through the system unchanged.
  1713. @type data: L{bytes}
  1714. @ivar data: Wire data which makes up this record.
  1715. @type ttl: L{int}
  1716. @ivar ttl: The maximum number of seconds which this record should be cached.
  1717. @since: 11.1
  1718. """
  1719. TYPE = None
  1720. fancybasename = "UNKNOWN"
  1721. compareAttributes = ("data", "ttl")
  1722. showAttributes = (("data", _nicebytes), "ttl")
  1723. def __init__(self, data=b"", ttl=None):
  1724. self.data = data
  1725. self.ttl = str2time(ttl)
  1726. def encode(self, strio, compDict=None):
  1727. """
  1728. Write the raw bytes corresponding to this record's payload to the
  1729. stream.
  1730. """
  1731. strio.write(self.data)
  1732. def decode(self, strio, length=None):
  1733. """
  1734. Load the bytes which are part of this record from the stream and store
  1735. them unparsed and unmodified.
  1736. """
  1737. if length is None:
  1738. raise Exception("must know length for unknown record types")
  1739. self.data = readPrecisely(strio, length)
  1740. def __hash__(self):
  1741. return hash((self.data, self.ttl))
  1742. class Record_SPF(Record_TXT):
  1743. """
  1744. Structurally, freeform text. Semantically, a policy definition, formatted
  1745. as defined in U{rfc 4408<http://www.faqs.org/rfcs/rfc4408.html>}.
  1746. @type data: L{list} of L{bytes}
  1747. @ivar data: Freeform text which makes up this record.
  1748. @type ttl: L{int}
  1749. @ivar ttl: The maximum number of seconds
  1750. which this record should be cached.
  1751. """
  1752. TYPE = SPF
  1753. fancybasename = "SPF"
  1754. @implementer(IEncodableRecord)
  1755. class Record_TSIG(tputil.FancyEqMixin, tputil.FancyStrMixin):
  1756. """
  1757. A transaction signature, encapsulated in a RR, as described
  1758. in U{RFC 2845 <https://tools.ietf.org/html/rfc2845>}.
  1759. @type algorithm: L{Name}
  1760. @ivar algorithm: The name of the signature or MAC algorithm.
  1761. @type timeSigned: L{int}
  1762. @ivar timeSigned: Signing time, as seconds from the POSIX epoch.
  1763. @type fudge: L{int}
  1764. @ivar fudge: Allowable time skew, in seconds.
  1765. @type MAC: L{bytes}
  1766. @ivar MAC: The message digest or signature.
  1767. @type originalID: L{int}
  1768. @ivar originalID: A message ID.
  1769. @type error: L{int}
  1770. @ivar error: An error code (extended C{RCODE}) carried
  1771. in exceptional cases.
  1772. @type otherData: L{bytes}
  1773. @ivar otherData: Other data carried in exceptional cases.
  1774. """
  1775. fancybasename = "TSIG"
  1776. compareAttributes = (
  1777. "algorithm",
  1778. "timeSigned",
  1779. "fudge",
  1780. "MAC",
  1781. "originalID",
  1782. "error",
  1783. "otherData",
  1784. "ttl",
  1785. )
  1786. showAttributes = ["algorithm", "timeSigned", "MAC", "error", "otherData"]
  1787. TYPE = TSIG
  1788. def __init__(
  1789. self,
  1790. algorithm=None,
  1791. timeSigned=None,
  1792. fudge=5,
  1793. MAC=None,
  1794. originalID=0,
  1795. error=OK,
  1796. otherData=b"",
  1797. ttl=0,
  1798. ):
  1799. # All of our init arguments have to have defaults, because of
  1800. # the way IEncodable and Message.parseRecords() work, but for
  1801. # some of our arguments there is no reasonable default; we use
  1802. # invalid values here to prevent a user of this class from
  1803. # relying on what's really an internal implementation detail.
  1804. self.algorithm = None if algorithm is None else Name(algorithm)
  1805. self.timeSigned = timeSigned
  1806. self.fudge = str2time(fudge)
  1807. self.MAC = MAC
  1808. self.originalID = originalID
  1809. self.error = error
  1810. self.otherData = otherData
  1811. self.ttl = ttl
  1812. def encode(self, strio, compDict=None):
  1813. self.algorithm.encode(strio, compDict)
  1814. strio.write(struct.pack("!Q", self.timeSigned)[2:]) # 48-bit number
  1815. strio.write(struct.pack("!HH", self.fudge, len(self.MAC)))
  1816. strio.write(self.MAC)
  1817. strio.write(
  1818. struct.pack("!HHH", self.originalID, self.error, len(self.otherData))
  1819. )
  1820. strio.write(self.otherData)
  1821. def decode(self, strio, length=None):
  1822. algorithm = Name()
  1823. algorithm.decode(strio)
  1824. self.algorithm = algorithm
  1825. fields = struct.unpack("!QHH", b"\x00\x00" + readPrecisely(strio, 10))
  1826. self.timeSigned, self.fudge, macLength = fields
  1827. self.MAC = readPrecisely(strio, macLength)
  1828. fields = struct.unpack("!HHH", readPrecisely(strio, 6))
  1829. self.originalID, self.error, otherLength = fields
  1830. self.otherData = readPrecisely(strio, otherLength)
  1831. def __hash__(self):
  1832. return hash((self.algorithm, self.timeSigned, self.MAC, self.originalID))
  1833. def _responseFromMessage(responseConstructor, message, **kwargs):
  1834. """
  1835. Generate a L{Message} like instance suitable for use as the response to
  1836. C{message}.
  1837. The C{queries}, C{id} attributes will be copied from C{message} and the
  1838. C{answer} flag will be set to L{True}.
  1839. @param responseConstructor: A response message constructor with an
  1840. initializer signature matching L{dns.Message.__init__}.
  1841. @type responseConstructor: C{callable}
  1842. @param message: A request message.
  1843. @type message: L{Message}
  1844. @param kwargs: Keyword arguments which will be passed to the initialiser
  1845. of the response message.
  1846. @type kwargs: L{dict}
  1847. @return: A L{Message} like response instance.
  1848. @rtype: C{responseConstructor}
  1849. """
  1850. response = responseConstructor(id=message.id, answer=True, **kwargs)
  1851. response.queries = message.queries[:]
  1852. return response
  1853. def _getDisplayableArguments(obj, alwaysShow, fieldNames):
  1854. """
  1855. Inspect the function signature of C{obj}'s constructor,
  1856. and get a list of which arguments should be displayed.
  1857. This is a helper function for C{_compactRepr}.
  1858. @param obj: The instance whose repr is being generated.
  1859. @param alwaysShow: A L{list} of field names which should always be shown.
  1860. @param fieldNames: A L{list} of field attribute names which should be shown
  1861. if they have non-default values.
  1862. @return: A L{list} of displayable arguments.
  1863. """
  1864. displayableArgs = []
  1865. # Get the argument names and values from the constructor.
  1866. signature = inspect.signature(obj.__class__.__init__)
  1867. for name in fieldNames:
  1868. defaultValue = signature.parameters[name].default
  1869. fieldValue = getattr(obj, name, defaultValue)
  1870. if (name in alwaysShow) or (fieldValue != defaultValue):
  1871. displayableArgs.append(f" {name}={fieldValue!r}")
  1872. return displayableArgs
  1873. def _compactRepr(
  1874. obj, alwaysShow=None, flagNames=None, fieldNames=None, sectionNames=None
  1875. ):
  1876. """
  1877. Return a L{str} representation of C{obj} which only shows fields with
  1878. non-default values, flags which are True and sections which have been
  1879. explicitly set.
  1880. @param obj: The instance whose repr is being generated.
  1881. @param alwaysShow: A L{list} of field names which should always be shown.
  1882. @param flagNames: A L{list} of flag attribute names which should be shown if
  1883. they are L{True}.
  1884. @param fieldNames: A L{list} of field attribute names which should be shown
  1885. if they have non-default values.
  1886. @param sectionNames: A L{list} of section attribute names which should be
  1887. shown if they have been assigned a value.
  1888. @return: A L{str} representation of C{obj}.
  1889. """
  1890. if alwaysShow is None:
  1891. alwaysShow = []
  1892. if flagNames is None:
  1893. flagNames = []
  1894. if fieldNames is None:
  1895. fieldNames = []
  1896. if sectionNames is None:
  1897. sectionNames = []
  1898. setFlags = []
  1899. for name in flagNames:
  1900. if name in alwaysShow or getattr(obj, name, False) == True:
  1901. setFlags.append(name)
  1902. displayableArgs = _getDisplayableArguments(obj, alwaysShow, fieldNames)
  1903. out = ["<", obj.__class__.__name__] + displayableArgs
  1904. if setFlags:
  1905. out.append(" flags={}".format(",".join(setFlags)))
  1906. for name in sectionNames:
  1907. section = getattr(obj, name, [])
  1908. if section:
  1909. out.append(f" {name}={section!r}")
  1910. out.append(">")
  1911. return "".join(out)
  1912. class Message(tputil.FancyEqMixin):
  1913. """
  1914. L{Message} contains all the information represented by a single
  1915. DNS request or response.
  1916. @ivar id: See L{__init__}
  1917. @ivar answer: See L{__init__}
  1918. @ivar opCode: See L{__init__}
  1919. @ivar recDes: See L{__init__}
  1920. @ivar recAv: See L{__init__}
  1921. @ivar auth: See L{__init__}
  1922. @ivar rCode: See L{__init__}
  1923. @ivar trunc: See L{__init__}
  1924. @ivar maxSize: See L{__init__}
  1925. @ivar authenticData: See L{__init__}
  1926. @ivar checkingDisabled: See L{__init__}
  1927. @ivar queries: The queries which are being asked of or answered by
  1928. DNS server.
  1929. @type queries: L{list} of L{Query}
  1930. @ivar answers: Records containing the answers to C{queries} if
  1931. this is a response message.
  1932. @type answers: L{list} of L{RRHeader}
  1933. @ivar authority: Records containing information about the
  1934. authoritative DNS servers for the names in C{queries}.
  1935. @type authority: L{list} of L{RRHeader}
  1936. @ivar additional: Records containing IP addresses of host names
  1937. in C{answers} and C{authority}.
  1938. @type additional: L{list} of L{RRHeader}
  1939. @ivar _flagNames: The names of attributes representing the flag header
  1940. fields.
  1941. @ivar _fieldNames: The names of attributes representing non-flag fixed
  1942. header fields.
  1943. @ivar _sectionNames: The names of attributes representing the record
  1944. sections of this message.
  1945. """
  1946. compareAttributes = (
  1947. "id",
  1948. "answer",
  1949. "opCode",
  1950. "recDes",
  1951. "recAv",
  1952. "auth",
  1953. "rCode",
  1954. "trunc",
  1955. "maxSize",
  1956. "authenticData",
  1957. "checkingDisabled",
  1958. "queries",
  1959. "answers",
  1960. "authority",
  1961. "additional",
  1962. )
  1963. headerFmt = "!H2B4H"
  1964. headerSize = struct.calcsize(headerFmt)
  1965. # Question, answer, additional, and nameserver lists
  1966. queries = answers = add = ns = None
  1967. def __init__(
  1968. self,
  1969. id=0,
  1970. answer=0,
  1971. opCode=0,
  1972. recDes=0,
  1973. recAv=0,
  1974. auth=0,
  1975. rCode=OK,
  1976. trunc=0,
  1977. maxSize=512,
  1978. authenticData=0,
  1979. checkingDisabled=0,
  1980. ):
  1981. """
  1982. @param id: A 16 bit identifier assigned by the program that
  1983. generates any kind of query. This identifier is copied to
  1984. the corresponding reply and can be used by the requester
  1985. to match up replies to outstanding queries.
  1986. @type id: L{int}
  1987. @param answer: A one bit field that specifies whether this
  1988. message is a query (0), or a response (1).
  1989. @type answer: L{int}
  1990. @param opCode: A four bit field that specifies kind of query in
  1991. this message. This value is set by the originator of a query
  1992. and copied into the response.
  1993. @type opCode: L{int}
  1994. @param recDes: Recursion Desired - this bit may be set in a
  1995. query and is copied into the response. If RD is set, it
  1996. directs the name server to pursue the query recursively.
  1997. Recursive query support is optional.
  1998. @type recDes: L{int}
  1999. @param recAv: Recursion Available - this bit is set or cleared
  2000. in a response and denotes whether recursive query support
  2001. is available in the name server.
  2002. @type recAv: L{int}
  2003. @param auth: Authoritative Answer - this bit is valid in
  2004. responses and specifies that the responding name server
  2005. is an authority for the domain name in question section.
  2006. @type auth: L{int}
  2007. @ivar rCode: A response code, used to indicate success or failure in a
  2008. message which is a response from a server to a client request.
  2009. @type rCode: C{0 <= int < 16}
  2010. @param trunc: A flag indicating that this message was
  2011. truncated due to length greater than that permitted on the
  2012. transmission channel.
  2013. @type trunc: L{int}
  2014. @param maxSize: The requestor's UDP payload size is the number
  2015. of octets of the largest UDP payload that can be
  2016. reassembled and delivered in the requestor's network
  2017. stack.
  2018. @type maxSize: L{int}
  2019. @param authenticData: A flag indicating in a response that all
  2020. the data included in the answer and authority portion of
  2021. the response has been authenticated by the server
  2022. according to the policies of that server.
  2023. See U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}.
  2024. @type authenticData: L{int}
  2025. @param checkingDisabled: A flag indicating in a query that
  2026. pending (non-authenticated) data is acceptable to the
  2027. resolver sending the query.
  2028. See U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}.
  2029. @type authenticData: L{int}
  2030. """
  2031. self.maxSize = maxSize
  2032. self.id = id
  2033. self.answer = answer
  2034. self.opCode = opCode
  2035. self.auth = auth
  2036. self.trunc = trunc
  2037. self.recDes = recDes
  2038. self.recAv = recAv
  2039. self.rCode = rCode
  2040. self.authenticData = authenticData
  2041. self.checkingDisabled = checkingDisabled
  2042. self.queries = []
  2043. self.answers = []
  2044. self.authority = []
  2045. self.additional = []
  2046. def __repr__(self) -> str:
  2047. """
  2048. Generate a repr of this L{Message}.
  2049. Only includes the non-default fields and sections and only includes
  2050. flags which are set. The C{id} is always shown.
  2051. @return: The native string repr.
  2052. """
  2053. return _compactRepr(
  2054. self,
  2055. flagNames=(
  2056. "answer",
  2057. "auth",
  2058. "trunc",
  2059. "recDes",
  2060. "recAv",
  2061. "authenticData",
  2062. "checkingDisabled",
  2063. ),
  2064. fieldNames=("id", "opCode", "rCode", "maxSize"),
  2065. sectionNames=("queries", "answers", "authority", "additional"),
  2066. alwaysShow=("id",),
  2067. )
  2068. def addQuery(self, name, type=ALL_RECORDS, cls=IN):
  2069. """
  2070. Add another query to this Message.
  2071. @type name: L{bytes}
  2072. @param name: The name to query.
  2073. @type type: L{int}
  2074. @param type: Query type
  2075. @type cls: L{int}
  2076. @param cls: Query class
  2077. """
  2078. self.queries.append(Query(name, type, cls))
  2079. def encode(self, strio):
  2080. compDict = {}
  2081. body_tmp = BytesIO()
  2082. for q in self.queries:
  2083. q.encode(body_tmp, compDict)
  2084. for q in self.answers:
  2085. q.encode(body_tmp, compDict)
  2086. for q in self.authority:
  2087. q.encode(body_tmp, compDict)
  2088. for q in self.additional:
  2089. q.encode(body_tmp, compDict)
  2090. body = body_tmp.getvalue()
  2091. size = len(body) + self.headerSize
  2092. if self.maxSize and size > self.maxSize:
  2093. self.trunc = 1
  2094. body = body[: self.maxSize - self.headerSize]
  2095. byte3 = (
  2096. ((self.answer & 1) << 7)
  2097. | ((self.opCode & 0xF) << 3)
  2098. | ((self.auth & 1) << 2)
  2099. | ((self.trunc & 1) << 1)
  2100. | (self.recDes & 1)
  2101. )
  2102. byte4 = (
  2103. ((self.recAv & 1) << 7)
  2104. | ((self.authenticData & 1) << 5)
  2105. | ((self.checkingDisabled & 1) << 4)
  2106. | (self.rCode & 0xF)
  2107. )
  2108. strio.write(
  2109. struct.pack(
  2110. self.headerFmt,
  2111. self.id,
  2112. byte3,
  2113. byte4,
  2114. len(self.queries),
  2115. len(self.answers),
  2116. len(self.authority),
  2117. len(self.additional),
  2118. )
  2119. )
  2120. strio.write(body)
  2121. def decode(self, strio, length=None):
  2122. self.maxSize = 0
  2123. header = readPrecisely(strio, self.headerSize)
  2124. r = struct.unpack(self.headerFmt, header)
  2125. self.id, byte3, byte4, nqueries, nans, nns, nadd = r
  2126. self.answer = (byte3 >> 7) & 1
  2127. self.opCode = (byte3 >> 3) & 0xF
  2128. self.auth = (byte3 >> 2) & 1
  2129. self.trunc = (byte3 >> 1) & 1
  2130. self.recDes = byte3 & 1
  2131. self.recAv = (byte4 >> 7) & 1
  2132. self.authenticData = (byte4 >> 5) & 1
  2133. self.checkingDisabled = (byte4 >> 4) & 1
  2134. self.rCode = byte4 & 0xF
  2135. self.queries = []
  2136. for i in range(nqueries):
  2137. q = Query()
  2138. try:
  2139. q.decode(strio)
  2140. except EOFError:
  2141. return
  2142. self.queries.append(q)
  2143. items = ((self.answers, nans), (self.authority, nns), (self.additional, nadd))
  2144. for (l, n) in items:
  2145. self.parseRecords(l, n, strio)
  2146. def parseRecords(self, list, num, strio):
  2147. for i in range(num):
  2148. header = RRHeader(auth=self.auth)
  2149. try:
  2150. header.decode(strio)
  2151. except EOFError:
  2152. return
  2153. t = self.lookupRecordType(header.type)
  2154. if not t:
  2155. continue
  2156. header.payload = t(ttl=header.ttl)
  2157. try:
  2158. header.payload.decode(strio, header.rdlength)
  2159. except EOFError:
  2160. return
  2161. list.append(header)
  2162. # Create a mapping from record types to their corresponding Record_*
  2163. # classes. This relies on the global state which has been created so
  2164. # far in initializing this module (so don't define Record classes after
  2165. # this).
  2166. _recordTypes = {}
  2167. for name in globals():
  2168. if name.startswith("Record_"):
  2169. _recordTypes[globals()[name].TYPE] = globals()[name]
  2170. # Clear the iteration variable out of the class namespace so it
  2171. # doesn't become an attribute.
  2172. del name
  2173. def lookupRecordType(self, type):
  2174. """
  2175. Retrieve the L{IRecord} implementation for the given record type.
  2176. @param type: A record type, such as C{A} or L{NS}.
  2177. @type type: L{int}
  2178. @return: An object which implements L{IRecord} or L{None} if none
  2179. can be found for the given type.
  2180. @rtype: C{Type[IRecord]}
  2181. """
  2182. return self._recordTypes.get(type, UnknownRecord)
  2183. def toStr(self):
  2184. """
  2185. Encode this L{Message} into a byte string in the format described by RFC
  2186. 1035.
  2187. @rtype: L{bytes}
  2188. """
  2189. strio = BytesIO()
  2190. self.encode(strio)
  2191. return strio.getvalue()
  2192. def fromStr(self, str):
  2193. """
  2194. Decode a byte string in the format described by RFC 1035 into this
  2195. L{Message}.
  2196. @param str: L{bytes}
  2197. """
  2198. strio = BytesIO(str)
  2199. self.decode(strio)
  2200. class _EDNSMessage(tputil.FancyEqMixin):
  2201. """
  2202. An I{EDNS} message.
  2203. Designed for compatibility with L{Message} but with a narrower public
  2204. interface.
  2205. Most importantly, L{_EDNSMessage.fromStr} will interpret and remove I{OPT}
  2206. records that are present in the additional records section.
  2207. The I{OPT} records are used to populate certain I{EDNS} specific attributes.
  2208. L{_EDNSMessage.toStr} will add suitable I{OPT} records to the additional
  2209. section to represent the extended EDNS information.
  2210. @see: U{https://tools.ietf.org/html/rfc6891}
  2211. @ivar id: See L{__init__}
  2212. @ivar answer: See L{__init__}
  2213. @ivar opCode: See L{__init__}
  2214. @ivar auth: See L{__init__}
  2215. @ivar trunc: See L{__init__}
  2216. @ivar recDes: See L{__init__}
  2217. @ivar recAv: See L{__init__}
  2218. @ivar rCode: See L{__init__}
  2219. @ivar ednsVersion: See L{__init__}
  2220. @ivar dnssecOK: See L{__init__}
  2221. @ivar authenticData: See L{__init__}
  2222. @ivar checkingDisabled: See L{__init__}
  2223. @ivar maxSize: See L{__init__}
  2224. @ivar queries: See L{__init__}
  2225. @ivar answers: See L{__init__}
  2226. @ivar authority: See L{__init__}
  2227. @ivar additional: See L{__init__}
  2228. @ivar _messageFactory: A constructor of L{Message} instances. Called by
  2229. C{_toMessage} and C{_fromMessage}.
  2230. """
  2231. compareAttributes = (
  2232. "id",
  2233. "answer",
  2234. "opCode",
  2235. "auth",
  2236. "trunc",
  2237. "recDes",
  2238. "recAv",
  2239. "rCode",
  2240. "ednsVersion",
  2241. "dnssecOK",
  2242. "authenticData",
  2243. "checkingDisabled",
  2244. "maxSize",
  2245. "queries",
  2246. "answers",
  2247. "authority",
  2248. "additional",
  2249. )
  2250. _messageFactory = Message
  2251. def __init__(
  2252. self,
  2253. id=0,
  2254. answer=False,
  2255. opCode=OP_QUERY,
  2256. auth=False,
  2257. trunc=False,
  2258. recDes=False,
  2259. recAv=False,
  2260. rCode=0,
  2261. ednsVersion=0,
  2262. dnssecOK=False,
  2263. authenticData=False,
  2264. checkingDisabled=False,
  2265. maxSize=512,
  2266. queries=None,
  2267. answers=None,
  2268. authority=None,
  2269. additional=None,
  2270. ):
  2271. """
  2272. Construct a new L{_EDNSMessage}
  2273. @see: U{RFC1035 section-4.1.1<https://tools.ietf.org/html/rfc1035#section-4.1.1>}
  2274. @see: U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}
  2275. @see: U{RFC3225 section-3<https://tools.ietf.org/html/rfc3225#section-3>}
  2276. @see: U{RFC6891 section-6.1.3<https://tools.ietf.org/html/rfc6891#section-6.1.3>}
  2277. @param id: A 16 bit identifier assigned by the program that generates
  2278. any kind of query. This identifier is copied the corresponding
  2279. reply and can be used by the requester to match up replies to
  2280. outstanding queries.
  2281. @type id: L{int}
  2282. @param answer: A one bit field that specifies whether this message is a
  2283. query (0), or a response (1).
  2284. @type answer: L{bool}
  2285. @param opCode: A four bit field that specifies kind of query in this
  2286. message. This value is set by the originator of a query and copied
  2287. into the response.
  2288. @type opCode: L{int}
  2289. @param auth: Authoritative Answer - this bit is valid in responses, and
  2290. specifies that the responding name server is an authority for the
  2291. domain name in question section.
  2292. @type auth: L{bool}
  2293. @param trunc: Truncation - specifies that this message was truncated due
  2294. to length greater than that permitted on the transmission channel.
  2295. @type trunc: L{bool}
  2296. @param recDes: Recursion Desired - this bit may be set in a query and is
  2297. copied into the response. If set, it directs the name server to
  2298. pursue the query recursively. Recursive query support is optional.
  2299. @type recDes: L{bool}
  2300. @param recAv: Recursion Available - this bit is set or cleared in a
  2301. response, and denotes whether recursive query support is available
  2302. in the name server.
  2303. @type recAv: L{bool}
  2304. @param rCode: Extended 12-bit RCODE. Derived from the 4 bits defined in
  2305. U{RFC1035 4.1.1<https://tools.ietf.org/html/rfc1035#section-4.1.1>}
  2306. and the upper 8bits defined in U{RFC6891
  2307. 6.1.3<https://tools.ietf.org/html/rfc6891#section-6.1.3>}.
  2308. @type rCode: L{int}
  2309. @param ednsVersion: Indicates the EDNS implementation level. Set to
  2310. L{None} to prevent any EDNS attributes and options being added to
  2311. the encoded byte string.
  2312. @type ednsVersion: L{int} or L{None}
  2313. @param dnssecOK: DNSSEC OK bit as defined by
  2314. U{RFC3225 3<https://tools.ietf.org/html/rfc3225#section-3>}.
  2315. @type dnssecOK: L{bool}
  2316. @param authenticData: A flag indicating in a response that all the data
  2317. included in the answer and authority portion of the response has
  2318. been authenticated by the server according to the policies of that
  2319. server.
  2320. See U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}.
  2321. @type authenticData: L{bool}
  2322. @param checkingDisabled: A flag indicating in a query that pending
  2323. (non-authenticated) data is acceptable to the resolver sending the
  2324. query.
  2325. See U{RFC2535 section-6.1<https://tools.ietf.org/html/rfc2535#section-6.1>}.
  2326. @type authenticData: L{bool}
  2327. @param maxSize: The requestor's UDP payload size is the number of octets
  2328. of the largest UDP payload that can be reassembled and delivered in
  2329. the requestor's network stack.
  2330. @type maxSize: L{int}
  2331. @param queries: The L{list} of L{Query} associated with this message.
  2332. @type queries: L{list} of L{Query}
  2333. @param answers: The L{list} of answers associated with this message.
  2334. @type answers: L{list} of L{RRHeader}
  2335. @param authority: The L{list} of authority records associated with this
  2336. message.
  2337. @type authority: L{list} of L{RRHeader}
  2338. @param additional: The L{list} of additional records associated with
  2339. this message.
  2340. @type additional: L{list} of L{RRHeader}
  2341. """
  2342. self.id = id
  2343. self.answer = answer
  2344. self.opCode = opCode
  2345. self.auth = auth
  2346. self.trunc = trunc
  2347. self.recDes = recDes
  2348. self.recAv = recAv
  2349. self.rCode = rCode
  2350. self.ednsVersion = ednsVersion
  2351. self.dnssecOK = dnssecOK
  2352. self.authenticData = authenticData
  2353. self.checkingDisabled = checkingDisabled
  2354. self.maxSize = maxSize
  2355. if queries is None:
  2356. queries = []
  2357. self.queries = queries
  2358. if answers is None:
  2359. answers = []
  2360. self.answers = answers
  2361. if authority is None:
  2362. authority = []
  2363. self.authority = authority
  2364. if additional is None:
  2365. additional = []
  2366. self.additional = additional
  2367. def __repr__(self) -> str:
  2368. return _compactRepr(
  2369. self,
  2370. flagNames=(
  2371. "answer",
  2372. "auth",
  2373. "trunc",
  2374. "recDes",
  2375. "recAv",
  2376. "authenticData",
  2377. "checkingDisabled",
  2378. "dnssecOK",
  2379. ),
  2380. fieldNames=("id", "opCode", "rCode", "maxSize", "ednsVersion"),
  2381. sectionNames=("queries", "answers", "authority", "additional"),
  2382. alwaysShow=("id",),
  2383. )
  2384. def _toMessage(self):
  2385. """
  2386. Convert to a standard L{dns.Message}.
  2387. If C{ednsVersion} is not None, an L{_OPTHeader} instance containing all
  2388. the I{EDNS} specific attributes and options will be appended to the list
  2389. of C{additional} records.
  2390. @return: A L{dns.Message}
  2391. @rtype: L{dns.Message}
  2392. """
  2393. m = self._messageFactory(
  2394. id=self.id,
  2395. answer=self.answer,
  2396. opCode=self.opCode,
  2397. auth=self.auth,
  2398. trunc=self.trunc,
  2399. recDes=self.recDes,
  2400. recAv=self.recAv,
  2401. # Assign the lower 4 bits to the message
  2402. rCode=self.rCode & 0xF,
  2403. authenticData=self.authenticData,
  2404. checkingDisabled=self.checkingDisabled,
  2405. )
  2406. m.queries = self.queries[:]
  2407. m.answers = self.answers[:]
  2408. m.authority = self.authority[:]
  2409. m.additional = self.additional[:]
  2410. if self.ednsVersion is not None:
  2411. o = _OPTHeader(
  2412. version=self.ednsVersion,
  2413. dnssecOK=self.dnssecOK,
  2414. udpPayloadSize=self.maxSize,
  2415. # Assign the upper 8 bits to the OPT record
  2416. extendedRCODE=self.rCode >> 4,
  2417. )
  2418. m.additional.append(o)
  2419. return m
  2420. def toStr(self):
  2421. """
  2422. Encode to wire format by first converting to a standard L{dns.Message}.
  2423. @return: A L{bytes} string.
  2424. """
  2425. return self._toMessage().toStr()
  2426. @classmethod
  2427. def _fromMessage(cls, message):
  2428. """
  2429. Construct and return a new L{_EDNSMessage} whose attributes and records
  2430. are derived from the attributes and records of C{message} (a L{Message}
  2431. instance).
  2432. If present, an C{OPT} record will be extracted from the C{additional}
  2433. section and its attributes and options will be used to set the EDNS
  2434. specific attributes C{extendedRCODE}, C{ednsVersion}, C{dnssecOK},
  2435. C{ednsOptions}.
  2436. The C{extendedRCODE} will be combined with C{message.rCode} and assigned
  2437. to C{self.rCode}.
  2438. @param message: The source L{Message}.
  2439. @type message: L{Message}
  2440. @return: A new L{_EDNSMessage}
  2441. @rtype: L{_EDNSMessage}
  2442. """
  2443. additional = []
  2444. optRecords = []
  2445. for r in message.additional:
  2446. if r.type == OPT:
  2447. optRecords.append(_OPTHeader.fromRRHeader(r))
  2448. else:
  2449. additional.append(r)
  2450. newMessage = cls(
  2451. id=message.id,
  2452. answer=message.answer,
  2453. opCode=message.opCode,
  2454. auth=message.auth,
  2455. trunc=message.trunc,
  2456. recDes=message.recDes,
  2457. recAv=message.recAv,
  2458. rCode=message.rCode,
  2459. authenticData=message.authenticData,
  2460. checkingDisabled=message.checkingDisabled,
  2461. # Default to None, it will be updated later when the OPT records are
  2462. # parsed.
  2463. ednsVersion=None,
  2464. dnssecOK=False,
  2465. queries=message.queries[:],
  2466. answers=message.answers[:],
  2467. authority=message.authority[:],
  2468. additional=additional,
  2469. )
  2470. if len(optRecords) == 1:
  2471. # XXX: If multiple OPT records are received, an EDNS server should
  2472. # respond with FORMERR. See ticket:5669#comment:1.
  2473. opt = optRecords[0]
  2474. newMessage.ednsVersion = opt.version
  2475. newMessage.dnssecOK = opt.dnssecOK
  2476. newMessage.maxSize = opt.udpPayloadSize
  2477. newMessage.rCode = opt.extendedRCODE << 4 | message.rCode
  2478. return newMessage
  2479. def fromStr(self, bytes):
  2480. """
  2481. Decode from wire format, saving flags, values and records to this
  2482. L{_EDNSMessage} instance in place.
  2483. @param bytes: The full byte string to be decoded.
  2484. @type bytes: L{bytes}
  2485. """
  2486. m = self._messageFactory()
  2487. m.fromStr(bytes)
  2488. ednsMessage = self._fromMessage(m)
  2489. for attrName in self.compareAttributes:
  2490. setattr(self, attrName, getattr(ednsMessage, attrName))
  2491. class DNSMixin:
  2492. """
  2493. DNS protocol mixin shared by UDP and TCP implementations.
  2494. @ivar _reactor: A L{IReactorTime} and L{IReactorUDP} provider which will
  2495. be used to issue DNS queries and manage request timeouts.
  2496. """
  2497. id = None
  2498. liveMessages = None
  2499. def __init__(self, controller, reactor=None):
  2500. self.controller = controller
  2501. self.id = random.randrange(2 ** 10, 2 ** 15)
  2502. if reactor is None:
  2503. from twisted.internet import reactor
  2504. self._reactor = reactor
  2505. def pickID(self):
  2506. """
  2507. Return a unique ID for queries.
  2508. """
  2509. while True:
  2510. id = randomSource()
  2511. if id not in self.liveMessages:
  2512. return id
  2513. def callLater(self, period, func, *args):
  2514. """
  2515. Wrapper around reactor.callLater, mainly for test purpose.
  2516. """
  2517. return self._reactor.callLater(period, func, *args)
  2518. def _query(self, queries, timeout, id, writeMessage):
  2519. """
  2520. Send out a message with the given queries.
  2521. @type queries: L{list} of C{Query} instances
  2522. @param queries: The queries to transmit
  2523. @type timeout: L{int} or C{float}
  2524. @param timeout: How long to wait before giving up
  2525. @type id: L{int}
  2526. @param id: Unique key for this request
  2527. @type writeMessage: C{callable}
  2528. @param writeMessage: One-parameter callback which writes the message
  2529. @rtype: C{Deferred}
  2530. @return: a C{Deferred} which will be fired with the result of the
  2531. query, or errbacked with any errors that could happen (exceptions
  2532. during writing of the query, timeout errors, ...).
  2533. """
  2534. m = Message(id, recDes=1)
  2535. m.queries = queries
  2536. try:
  2537. writeMessage(m)
  2538. except BaseException:
  2539. return defer.fail()
  2540. resultDeferred = defer.Deferred()
  2541. cancelCall = self.callLater(timeout, self._clearFailed, resultDeferred, id)
  2542. self.liveMessages[id] = (resultDeferred, cancelCall)
  2543. return resultDeferred
  2544. def _clearFailed(self, deferred, id):
  2545. """
  2546. Clean the Deferred after a timeout.
  2547. """
  2548. try:
  2549. del self.liveMessages[id]
  2550. except KeyError:
  2551. pass
  2552. deferred.errback(failure.Failure(DNSQueryTimeoutError(id)))
  2553. class DNSDatagramProtocol(DNSMixin, protocol.DatagramProtocol):
  2554. """
  2555. DNS protocol over UDP.
  2556. """
  2557. resends = None
  2558. def stopProtocol(self):
  2559. """
  2560. Stop protocol: reset state variables.
  2561. """
  2562. self.liveMessages = {}
  2563. self.resends = {}
  2564. self.transport = None
  2565. def startProtocol(self):
  2566. """
  2567. Upon start, reset internal state.
  2568. """
  2569. self.liveMessages = {}
  2570. self.resends = {}
  2571. def writeMessage(self, message, address):
  2572. """
  2573. Send a message holding DNS queries.
  2574. @type message: L{Message}
  2575. """
  2576. self.transport.write(message.toStr(), address)
  2577. def startListening(self):
  2578. self._reactor.listenUDP(0, self, maxPacketSize=512)
  2579. def datagramReceived(self, data, addr):
  2580. """
  2581. Read a datagram, extract the message in it and trigger the associated
  2582. Deferred.
  2583. """
  2584. m = Message()
  2585. try:
  2586. m.fromStr(data)
  2587. except EOFError:
  2588. log.msg("Truncated packet (%d bytes) from %s" % (len(data), addr))
  2589. return
  2590. except ValueError as ex:
  2591. log.msg(f"Invalid packet ({ex}) from {addr}")
  2592. return
  2593. except BaseException:
  2594. # Nothing should trigger this, but since we're potentially
  2595. # invoking a lot of different decoding methods, we might as well
  2596. # be extra cautious. Anything that triggers this is itself
  2597. # buggy.
  2598. log.err(failure.Failure(), "Unexpected decoding error")
  2599. return
  2600. if m.id in self.liveMessages:
  2601. d, canceller = self.liveMessages[m.id]
  2602. del self.liveMessages[m.id]
  2603. canceller.cancel()
  2604. # XXX we shouldn't need this hack of catching exception on callback()
  2605. try:
  2606. d.callback(m)
  2607. except BaseException:
  2608. log.err()
  2609. else:
  2610. if m.id not in self.resends:
  2611. self.controller.messageReceived(m, self, addr)
  2612. def removeResend(self, id):
  2613. """
  2614. Mark message ID as no longer having duplication suppression.
  2615. """
  2616. try:
  2617. del self.resends[id]
  2618. except KeyError:
  2619. pass
  2620. def query(self, address, queries, timeout=10, id=None):
  2621. """
  2622. Send out a message with the given queries.
  2623. @type address: L{tuple} of L{str} and L{int}
  2624. @param address: The address to which to send the query
  2625. @type queries: L{list} of C{Query} instances
  2626. @param queries: The queries to transmit
  2627. @rtype: C{Deferred}
  2628. """
  2629. if not self.transport:
  2630. # XXX transport might not get created automatically, use callLater?
  2631. try:
  2632. self.startListening()
  2633. except CannotListenError:
  2634. return defer.fail()
  2635. if id is None:
  2636. id = self.pickID()
  2637. else:
  2638. self.resends[id] = 1
  2639. def writeMessage(m):
  2640. self.writeMessage(m, address)
  2641. return self._query(queries, timeout, id, writeMessage)
  2642. class DNSProtocol(DNSMixin, protocol.Protocol):
  2643. """
  2644. DNS protocol over TCP.
  2645. """
  2646. length = None
  2647. buffer = b""
  2648. def writeMessage(self, message):
  2649. """
  2650. Send a message holding DNS queries.
  2651. @type message: L{Message}
  2652. """
  2653. s = message.toStr()
  2654. self.transport.write(struct.pack("!H", len(s)) + s)
  2655. def connectionMade(self):
  2656. """
  2657. Connection is made: reset internal state, and notify the controller.
  2658. """
  2659. self.liveMessages = {}
  2660. self.controller.connectionMade(self)
  2661. def connectionLost(self, reason):
  2662. """
  2663. Notify the controller that this protocol is no longer
  2664. connected.
  2665. """
  2666. self.controller.connectionLost(self)
  2667. def dataReceived(self, data):
  2668. self.buffer += data
  2669. while self.buffer:
  2670. if self.length is None and len(self.buffer) >= 2:
  2671. self.length = struct.unpack("!H", self.buffer[:2])[0]
  2672. self.buffer = self.buffer[2:]
  2673. if len(self.buffer) >= self.length:
  2674. myChunk = self.buffer[: self.length]
  2675. m = Message()
  2676. m.fromStr(myChunk)
  2677. try:
  2678. d, canceller = self.liveMessages[m.id]
  2679. except KeyError:
  2680. self.controller.messageReceived(m, self)
  2681. else:
  2682. del self.liveMessages[m.id]
  2683. canceller.cancel()
  2684. # XXX we shouldn't need this hack
  2685. try:
  2686. d.callback(m)
  2687. except BaseException:
  2688. log.err()
  2689. self.buffer = self.buffer[self.length :]
  2690. self.length = None
  2691. else:
  2692. break
  2693. def query(self, queries, timeout=60):
  2694. """
  2695. Send out a message with the given queries.
  2696. @type queries: L{list} of C{Query} instances
  2697. @param queries: The queries to transmit
  2698. @rtype: C{Deferred}
  2699. """
  2700. id = self.pickID()
  2701. return self._query(queries, timeout, id, self.writeMessage)