dns.py 98 KB

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