dns.py 89 KB

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