dns.py 96 KB

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