message.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2001-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """DNS Messages"""
  17. import contextlib
  18. import io
  19. import time
  20. import dns.wire
  21. import dns.edns
  22. import dns.enum
  23. import dns.exception
  24. import dns.flags
  25. import dns.name
  26. import dns.opcode
  27. import dns.entropy
  28. import dns.rcode
  29. import dns.rdata
  30. import dns.rdataclass
  31. import dns.rdatatype
  32. import dns.rrset
  33. import dns.renderer
  34. import dns.ttl
  35. import dns.tsig
  36. import dns.rdtypes.ANY.OPT
  37. import dns.rdtypes.ANY.TSIG
  38. class ShortHeader(dns.exception.FormError):
  39. """The DNS packet passed to from_wire() is too short."""
  40. class TrailingJunk(dns.exception.FormError):
  41. """The DNS packet passed to from_wire() has extra junk at the end of it."""
  42. class UnknownHeaderField(dns.exception.DNSException):
  43. """The header field name was not recognized when converting from text
  44. into a message."""
  45. class BadEDNS(dns.exception.FormError):
  46. """An OPT record occurred somewhere other than
  47. the additional data section."""
  48. class BadTSIG(dns.exception.FormError):
  49. """A TSIG record occurred somewhere other than the end of
  50. the additional data section."""
  51. class UnknownTSIGKey(dns.exception.DNSException):
  52. """A TSIG with an unknown key was received."""
  53. class Truncated(dns.exception.DNSException):
  54. """The truncated flag is set."""
  55. supp_kwargs = {'message'}
  56. def message(self):
  57. """As much of the message as could be processed.
  58. Returns a ``dns.message.Message``.
  59. """
  60. return self.kwargs['message']
  61. class NotQueryResponse(dns.exception.DNSException):
  62. """Message is not a response to a query."""
  63. class ChainTooLong(dns.exception.DNSException):
  64. """The CNAME chain is too long."""
  65. class AnswerForNXDOMAIN(dns.exception.DNSException):
  66. """The rcode is NXDOMAIN but an answer was found."""
  67. class NoPreviousName(dns.exception.SyntaxError):
  68. """No previous name was known."""
  69. class MessageSection(dns.enum.IntEnum):
  70. """Message sections"""
  71. QUESTION = 0
  72. ANSWER = 1
  73. AUTHORITY = 2
  74. ADDITIONAL = 3
  75. @classmethod
  76. def _maximum(cls):
  77. return 3
  78. class MessageError:
  79. def __init__(self, exception, offset):
  80. self.exception = exception
  81. self.offset = offset
  82. DEFAULT_EDNS_PAYLOAD = 1232
  83. MAX_CHAIN = 16
  84. class Message:
  85. """A DNS message."""
  86. _section_enum = MessageSection
  87. def __init__(self, id=None):
  88. if id is None:
  89. self.id = dns.entropy.random_16()
  90. else:
  91. self.id = id
  92. self.flags = 0
  93. self.sections = [[], [], [], []]
  94. self.opt = None
  95. self.request_payload = 0
  96. self.keyring = None
  97. self.tsig = None
  98. self.request_mac = b''
  99. self.xfr = False
  100. self.origin = None
  101. self.tsig_ctx = None
  102. self.index = {}
  103. self.errors = []
  104. @property
  105. def question(self):
  106. """ The question section."""
  107. return self.sections[0]
  108. @question.setter
  109. def question(self, v):
  110. self.sections[0] = v
  111. @property
  112. def answer(self):
  113. """ The answer section."""
  114. return self.sections[1]
  115. @answer.setter
  116. def answer(self, v):
  117. self.sections[1] = v
  118. @property
  119. def authority(self):
  120. """ The authority section."""
  121. return self.sections[2]
  122. @authority.setter
  123. def authority(self, v):
  124. self.sections[2] = v
  125. @property
  126. def additional(self):
  127. """ The additional data section."""
  128. return self.sections[3]
  129. @additional.setter
  130. def additional(self, v):
  131. self.sections[3] = v
  132. def __repr__(self):
  133. return '<DNS message, ID ' + repr(self.id) + '>'
  134. def __str__(self):
  135. return self.to_text()
  136. def to_text(self, origin=None, relativize=True, **kw):
  137. """Convert the message to text.
  138. The *origin*, *relativize*, and any other keyword
  139. arguments are passed to the RRset ``to_wire()`` method.
  140. Returns a ``str``.
  141. """
  142. s = io.StringIO()
  143. s.write('id %d\n' % self.id)
  144. s.write('opcode %s\n' % dns.opcode.to_text(self.opcode()))
  145. s.write('rcode %s\n' % dns.rcode.to_text(self.rcode()))
  146. s.write('flags %s\n' % dns.flags.to_text(self.flags))
  147. if self.edns >= 0:
  148. s.write('edns %s\n' % self.edns)
  149. if self.ednsflags != 0:
  150. s.write('eflags %s\n' %
  151. dns.flags.edns_to_text(self.ednsflags))
  152. s.write('payload %d\n' % self.payload)
  153. for opt in self.options:
  154. s.write('option %s\n' % opt.to_text())
  155. for (name, which) in self._section_enum.__members__.items():
  156. s.write(f';{name}\n')
  157. for rrset in self.section_from_number(which):
  158. s.write(rrset.to_text(origin, relativize, **kw))
  159. s.write('\n')
  160. #
  161. # We strip off the final \n so the caller can print the result without
  162. # doing weird things to get around eccentricities in Python print
  163. # formatting
  164. #
  165. return s.getvalue()[:-1]
  166. def __eq__(self, other):
  167. """Two messages are equal if they have the same content in the
  168. header, question, answer, and authority sections.
  169. Returns a ``bool``.
  170. """
  171. if not isinstance(other, Message):
  172. return False
  173. if self.id != other.id:
  174. return False
  175. if self.flags != other.flags:
  176. return False
  177. for i, section in enumerate(self.sections):
  178. other_section = other.sections[i]
  179. for n in section:
  180. if n not in other_section:
  181. return False
  182. for n in other_section:
  183. if n not in section:
  184. return False
  185. return True
  186. def __ne__(self, other):
  187. return not self.__eq__(other)
  188. def is_response(self, other):
  189. """Is *other*, also a ``dns.message.Message``, a response to this
  190. message?
  191. Returns a ``bool``.
  192. """
  193. if other.flags & dns.flags.QR == 0 or \
  194. self.id != other.id or \
  195. dns.opcode.from_flags(self.flags) != \
  196. dns.opcode.from_flags(other.flags):
  197. return False
  198. if other.rcode() in {dns.rcode.FORMERR, dns.rcode.SERVFAIL,
  199. dns.rcode.NOTIMP, dns.rcode.REFUSED}:
  200. # We don't check the question section in these cases if
  201. # the other question section is empty, even though they
  202. # still really ought to have a question section.
  203. if len(other.question) == 0:
  204. return True
  205. if dns.opcode.is_update(self.flags):
  206. # This is assuming the "sender doesn't include anything
  207. # from the update", but we don't care to check the other
  208. # case, which is that all the sections are returned and
  209. # identical.
  210. return True
  211. for n in self.question:
  212. if n not in other.question:
  213. return False
  214. for n in other.question:
  215. if n not in self.question:
  216. return False
  217. return True
  218. def section_number(self, section):
  219. """Return the "section number" of the specified section for use
  220. in indexing.
  221. *section* is one of the section attributes of this message.
  222. Raises ``ValueError`` if the section isn't known.
  223. Returns an ``int``.
  224. """
  225. for i, our_section in enumerate(self.sections):
  226. if section is our_section:
  227. return self._section_enum(i)
  228. raise ValueError('unknown section')
  229. def section_from_number(self, number):
  230. """Return the section list associated with the specified section
  231. number.
  232. *number* is a section number `int` or the text form of a section
  233. name.
  234. Raises ``ValueError`` if the section isn't known.
  235. Returns a ``list``.
  236. """
  237. section = self._section_enum.make(number)
  238. return self.sections[section]
  239. def find_rrset(self, section, name, rdclass, rdtype,
  240. covers=dns.rdatatype.NONE, deleting=None, create=False,
  241. force_unique=False):
  242. """Find the RRset with the given attributes in the specified section.
  243. *section*, an ``int`` section number, or one of the section
  244. attributes of this message. This specifies the
  245. the section of the message to search. For example::
  246. my_message.find_rrset(my_message.answer, name, rdclass, rdtype)
  247. my_message.find_rrset(dns.message.ANSWER, name, rdclass, rdtype)
  248. *name*, a ``dns.name.Name``, the name of the RRset.
  249. *rdclass*, an ``int``, the class of the RRset.
  250. *rdtype*, an ``int``, the type of the RRset.
  251. *covers*, an ``int`` or ``None``, the covers value of the RRset.
  252. The default is ``None``.
  253. *deleting*, an ``int`` or ``None``, the deleting value of the RRset.
  254. The default is ``None``.
  255. *create*, a ``bool``. If ``True``, create the RRset if it is not found.
  256. The created RRset is appended to *section*.
  257. *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``,
  258. create a new RRset regardless of whether a matching RRset exists
  259. already. The default is ``False``. This is useful when creating
  260. DDNS Update messages, as order matters for them.
  261. Raises ``KeyError`` if the RRset was not found and create was
  262. ``False``.
  263. Returns a ``dns.rrset.RRset object``.
  264. """
  265. if isinstance(section, int):
  266. section_number = section
  267. section = self.section_from_number(section_number)
  268. else:
  269. section_number = self.section_number(section)
  270. key = (section_number, name, rdclass, rdtype, covers, deleting)
  271. if not force_unique:
  272. if self.index is not None:
  273. rrset = self.index.get(key)
  274. if rrset is not None:
  275. return rrset
  276. else:
  277. for rrset in section:
  278. if rrset.full_match(name, rdclass, rdtype, covers,
  279. deleting):
  280. return rrset
  281. if not create:
  282. raise KeyError
  283. rrset = dns.rrset.RRset(name, rdclass, rdtype, covers, deleting)
  284. section.append(rrset)
  285. if self.index is not None:
  286. self.index[key] = rrset
  287. return rrset
  288. def get_rrset(self, section, name, rdclass, rdtype,
  289. covers=dns.rdatatype.NONE, deleting=None, create=False,
  290. force_unique=False):
  291. """Get the RRset with the given attributes in the specified section.
  292. If the RRset is not found, None is returned.
  293. *section*, an ``int`` section number, or one of the section
  294. attributes of this message. This specifies the
  295. the section of the message to search. For example::
  296. my_message.get_rrset(my_message.answer, name, rdclass, rdtype)
  297. my_message.get_rrset(dns.message.ANSWER, name, rdclass, rdtype)
  298. *name*, a ``dns.name.Name``, the name of the RRset.
  299. *rdclass*, an ``int``, the class of the RRset.
  300. *rdtype*, an ``int``, the type of the RRset.
  301. *covers*, an ``int`` or ``None``, the covers value of the RRset.
  302. The default is ``None``.
  303. *deleting*, an ``int`` or ``None``, the deleting value of the RRset.
  304. The default is ``None``.
  305. *create*, a ``bool``. If ``True``, create the RRset if it is not found.
  306. The created RRset is appended to *section*.
  307. *force_unique*, a ``bool``. If ``True`` and *create* is also ``True``,
  308. create a new RRset regardless of whether a matching RRset exists
  309. already. The default is ``False``. This is useful when creating
  310. DDNS Update messages, as order matters for them.
  311. Returns a ``dns.rrset.RRset object`` or ``None``.
  312. """
  313. try:
  314. rrset = self.find_rrset(section, name, rdclass, rdtype, covers,
  315. deleting, create, force_unique)
  316. except KeyError:
  317. rrset = None
  318. return rrset
  319. def to_wire(self, origin=None, max_size=0, multi=False, tsig_ctx=None,
  320. **kw):
  321. """Return a string containing the message in DNS compressed wire
  322. format.
  323. Additional keyword arguments are passed to the RRset ``to_wire()``
  324. method.
  325. *origin*, a ``dns.name.Name`` or ``None``, the origin to be appended
  326. to any relative names. If ``None``, and the message has an origin
  327. attribute that is not ``None``, then it will be used.
  328. *max_size*, an ``int``, the maximum size of the wire format
  329. output; default is 0, which means "the message's request
  330. payload, if nonzero, or 65535".
  331. *multi*, a ``bool``, should be set to ``True`` if this message is
  332. part of a multiple message sequence.
  333. *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the
  334. ongoing TSIG context, used when signing zone transfers.
  335. Raises ``dns.exception.TooBig`` if *max_size* was exceeded.
  336. Returns a ``bytes``.
  337. """
  338. if origin is None and self.origin is not None:
  339. origin = self.origin
  340. if max_size == 0:
  341. if self.request_payload != 0:
  342. max_size = self.request_payload
  343. else:
  344. max_size = 65535
  345. if max_size < 512:
  346. max_size = 512
  347. elif max_size > 65535:
  348. max_size = 65535
  349. r = dns.renderer.Renderer(self.id, self.flags, max_size, origin)
  350. for rrset in self.question:
  351. r.add_question(rrset.name, rrset.rdtype, rrset.rdclass)
  352. for rrset in self.answer:
  353. r.add_rrset(dns.renderer.ANSWER, rrset, **kw)
  354. for rrset in self.authority:
  355. r.add_rrset(dns.renderer.AUTHORITY, rrset, **kw)
  356. if self.opt is not None:
  357. r.add_rrset(dns.renderer.ADDITIONAL, self.opt)
  358. for rrset in self.additional:
  359. r.add_rrset(dns.renderer.ADDITIONAL, rrset, **kw)
  360. r.write_header()
  361. if self.tsig is not None:
  362. (new_tsig, ctx) = dns.tsig.sign(r.get_wire(),
  363. self.keyring,
  364. self.tsig[0],
  365. int(time.time()),
  366. self.request_mac,
  367. tsig_ctx,
  368. multi)
  369. self.tsig.clear()
  370. self.tsig.add(new_tsig)
  371. r.add_rrset(dns.renderer.ADDITIONAL, self.tsig)
  372. r.write_header()
  373. if multi:
  374. self.tsig_ctx = ctx
  375. return r.get_wire()
  376. @staticmethod
  377. def _make_tsig(keyname, algorithm, time_signed, fudge, mac, original_id,
  378. error, other):
  379. tsig = dns.rdtypes.ANY.TSIG.TSIG(dns.rdataclass.ANY, dns.rdatatype.TSIG,
  380. algorithm, time_signed, fudge, mac,
  381. original_id, error, other)
  382. return dns.rrset.from_rdata(keyname, 0, tsig)
  383. def use_tsig(self, keyring, keyname=None, fudge=300,
  384. original_id=None, tsig_error=0, other_data=b'',
  385. algorithm=dns.tsig.default_algorithm):
  386. """When sending, a TSIG signature using the specified key
  387. should be added.
  388. *key*, a ``dns.tsig.Key`` is the key to use. If a key is specified,
  389. the *keyring* and *algorithm* fields are not used.
  390. *keyring*, a ``dict``, ``callable`` or ``dns.tsig.Key``, is either
  391. the TSIG keyring or key to use.
  392. The format of a keyring dict is a mapping from TSIG key name, as
  393. ``dns.name.Name`` to ``dns.tsig.Key`` or a TSIG secret, a ``bytes``.
  394. If a ``dict`` *keyring* is specified but a *keyname* is not, the key
  395. used will be the first key in the *keyring*. Note that the order of
  396. keys in a dictionary is not defined, so applications should supply a
  397. keyname when a ``dict`` keyring is used, unless they know the keyring
  398. contains only one key. If a ``callable`` keyring is specified, the
  399. callable will be called with the message and the keyname, and is
  400. expected to return a key.
  401. *keyname*, a ``dns.name.Name``, ``str`` or ``None``, the name of
  402. this TSIG key to use; defaults to ``None``. If *keyring* is a
  403. ``dict``, the key must be defined in it. If *keyring* is a
  404. ``dns.tsig.Key``, this is ignored.
  405. *fudge*, an ``int``, the TSIG time fudge.
  406. *original_id*, an ``int``, the TSIG original id. If ``None``,
  407. the message's id is used.
  408. *tsig_error*, an ``int``, the TSIG error code.
  409. *other_data*, a ``bytes``, the TSIG other data.
  410. *algorithm*, a ``dns.name.Name``, the TSIG algorithm to use. This is
  411. only used if *keyring* is a ``dict``, and the key entry is a ``bytes``.
  412. """
  413. if isinstance(keyring, dns.tsig.Key):
  414. key = keyring
  415. keyname = key.name
  416. elif callable(keyring):
  417. key = keyring(self, keyname)
  418. else:
  419. if isinstance(keyname, str):
  420. keyname = dns.name.from_text(keyname)
  421. if keyname is None:
  422. keyname = next(iter(keyring))
  423. key = keyring[keyname]
  424. if isinstance(key, bytes):
  425. key = dns.tsig.Key(keyname, key, algorithm)
  426. self.keyring = key
  427. if original_id is None:
  428. original_id = self.id
  429. self.tsig = self._make_tsig(keyname, self.keyring.algorithm, 0, fudge,
  430. b'', original_id, tsig_error, other_data)
  431. @property
  432. def keyname(self):
  433. if self.tsig:
  434. return self.tsig.name
  435. else:
  436. return None
  437. @property
  438. def keyalgorithm(self):
  439. if self.tsig:
  440. return self.tsig[0].algorithm
  441. else:
  442. return None
  443. @property
  444. def mac(self):
  445. if self.tsig:
  446. return self.tsig[0].mac
  447. else:
  448. return None
  449. @property
  450. def tsig_error(self):
  451. if self.tsig:
  452. return self.tsig[0].error
  453. else:
  454. return None
  455. @property
  456. def had_tsig(self):
  457. return bool(self.tsig)
  458. @staticmethod
  459. def _make_opt(flags=0, payload=DEFAULT_EDNS_PAYLOAD, options=None):
  460. opt = dns.rdtypes.ANY.OPT.OPT(payload, dns.rdatatype.OPT,
  461. options or ())
  462. return dns.rrset.from_rdata(dns.name.root, int(flags), opt)
  463. def use_edns(self, edns=0, ednsflags=0, payload=DEFAULT_EDNS_PAYLOAD,
  464. request_payload=None, options=None):
  465. """Configure EDNS behavior.
  466. *edns*, an ``int``, is the EDNS level to use. Specifying
  467. ``None``, ``False``, or ``-1`` means "do not use EDNS", and in this case
  468. the other parameters are ignored. Specifying ``True`` is
  469. equivalent to specifying 0, i.e. "use EDNS0".
  470. *ednsflags*, an ``int``, the EDNS flag values.
  471. *payload*, an ``int``, is the EDNS sender's payload field, which is the
  472. maximum size of UDP datagram the sender can handle. I.e. how big
  473. a response to this message can be.
  474. *request_payload*, an ``int``, is the EDNS payload size to use when
  475. sending this message. If not specified, defaults to the value of
  476. *payload*.
  477. *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS
  478. options.
  479. """
  480. if edns is None or edns is False:
  481. edns = -1
  482. elif edns is True:
  483. edns = 0
  484. if edns < 0:
  485. self.opt = None
  486. self.request_payload = 0
  487. else:
  488. # make sure the EDNS version in ednsflags agrees with edns
  489. ednsflags &= 0xFF00FFFF
  490. ednsflags |= (edns << 16)
  491. if options is None:
  492. options = []
  493. self.opt = self._make_opt(ednsflags, payload, options)
  494. if request_payload is None:
  495. request_payload = payload
  496. self.request_payload = request_payload
  497. @property
  498. def edns(self):
  499. if self.opt:
  500. return (self.ednsflags & 0xff0000) >> 16
  501. else:
  502. return -1
  503. @property
  504. def ednsflags(self):
  505. if self.opt:
  506. return self.opt.ttl
  507. else:
  508. return 0
  509. @ednsflags.setter
  510. def ednsflags(self, v):
  511. if self.opt:
  512. self.opt.ttl = v
  513. elif v:
  514. self.opt = self._make_opt(v)
  515. @property
  516. def payload(self):
  517. if self.opt:
  518. return self.opt[0].payload
  519. else:
  520. return 0
  521. @property
  522. def options(self):
  523. if self.opt:
  524. return self.opt[0].options
  525. else:
  526. return ()
  527. def want_dnssec(self, wanted=True):
  528. """Enable or disable 'DNSSEC desired' flag in requests.
  529. *wanted*, a ``bool``. If ``True``, then DNSSEC data is
  530. desired in the response, EDNS is enabled if required, and then
  531. the DO bit is set. If ``False``, the DO bit is cleared if
  532. EDNS is enabled.
  533. """
  534. if wanted:
  535. self.ednsflags |= dns.flags.DO
  536. elif self.opt:
  537. self.ednsflags &= ~dns.flags.DO
  538. def rcode(self):
  539. """Return the rcode.
  540. Returns an ``int``.
  541. """
  542. return dns.rcode.from_flags(int(self.flags), int(self.ednsflags))
  543. def set_rcode(self, rcode):
  544. """Set the rcode.
  545. *rcode*, an ``int``, is the rcode to set.
  546. """
  547. (value, evalue) = dns.rcode.to_flags(rcode)
  548. self.flags &= 0xFFF0
  549. self.flags |= value
  550. self.ednsflags &= 0x00FFFFFF
  551. self.ednsflags |= evalue
  552. def opcode(self):
  553. """Return the opcode.
  554. Returns an ``int``.
  555. """
  556. return dns.opcode.from_flags(int(self.flags))
  557. def set_opcode(self, opcode):
  558. """Set the opcode.
  559. *opcode*, an ``int``, is the opcode to set.
  560. """
  561. self.flags &= 0x87FF
  562. self.flags |= dns.opcode.to_flags(opcode)
  563. def _get_one_rr_per_rrset(self, value):
  564. # What the caller picked is fine.
  565. return value
  566. # pylint: disable=unused-argument
  567. def _parse_rr_header(self, section, name, rdclass, rdtype):
  568. return (rdclass, rdtype, None, False)
  569. # pylint: enable=unused-argument
  570. def _parse_special_rr_header(self, section, count, position,
  571. name, rdclass, rdtype):
  572. if rdtype == dns.rdatatype.OPT:
  573. if section != MessageSection.ADDITIONAL or self.opt or \
  574. name != dns.name.root:
  575. raise BadEDNS
  576. elif rdtype == dns.rdatatype.TSIG:
  577. if section != MessageSection.ADDITIONAL or \
  578. rdclass != dns.rdatatype.ANY or \
  579. position != count - 1:
  580. raise BadTSIG
  581. return (rdclass, rdtype, None, False)
  582. class ChainingResult:
  583. """The result of a call to dns.message.QueryMessage.resolve_chaining().
  584. The ``answer`` attribute is the answer RRSet, or ``None`` if it doesn't
  585. exist.
  586. The ``canonical_name`` attribute is the canonical name after all
  587. chaining has been applied (this is the name as ``rrset.name`` in cases
  588. where rrset is not ``None``).
  589. The ``minimum_ttl`` attribute is the minimum TTL, i.e. the TTL to
  590. use if caching the data. It is the smallest of all the CNAME TTLs
  591. and either the answer TTL if it exists or the SOA TTL and SOA
  592. minimum values for negative answers.
  593. The ``cnames`` attribute is a list of all the CNAME RRSets followed to
  594. get to the canonical name.
  595. """
  596. def __init__(self, canonical_name, answer, minimum_ttl, cnames):
  597. self.canonical_name = canonical_name
  598. self.answer = answer
  599. self.minimum_ttl = minimum_ttl
  600. self.cnames = cnames
  601. class QueryMessage(Message):
  602. def resolve_chaining(self):
  603. """Follow the CNAME chain in the response to determine the answer
  604. RRset.
  605. Raises ``dns.message.NotQueryResponse`` if the message is not
  606. a response.
  607. Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long.
  608. Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN
  609. but an answer was found.
  610. Raises ``dns.exception.FormError`` if the question count is not 1.
  611. Returns a ChainingResult object.
  612. """
  613. if self.flags & dns.flags.QR == 0:
  614. raise NotQueryResponse
  615. if len(self.question) != 1:
  616. raise dns.exception.FormError
  617. question = self.question[0]
  618. qname = question.name
  619. min_ttl = dns.ttl.MAX_TTL
  620. answer = None
  621. count = 0
  622. cnames = []
  623. while count < MAX_CHAIN:
  624. try:
  625. answer = self.find_rrset(self.answer, qname, question.rdclass,
  626. question.rdtype)
  627. min_ttl = min(min_ttl, answer.ttl)
  628. break
  629. except KeyError:
  630. if question.rdtype != dns.rdatatype.CNAME:
  631. try:
  632. crrset = self.find_rrset(self.answer, qname,
  633. question.rdclass,
  634. dns.rdatatype.CNAME)
  635. cnames.append(crrset)
  636. min_ttl = min(min_ttl, crrset.ttl)
  637. for rd in crrset:
  638. qname = rd.target
  639. break
  640. count += 1
  641. continue
  642. except KeyError:
  643. # Exit the chaining loop
  644. break
  645. else:
  646. # Exit the chaining loop
  647. break
  648. if count >= MAX_CHAIN:
  649. raise ChainTooLong
  650. if self.rcode() == dns.rcode.NXDOMAIN and answer is not None:
  651. raise AnswerForNXDOMAIN
  652. if answer is None:
  653. # Further minimize the TTL with NCACHE.
  654. auname = qname
  655. while True:
  656. # Look for an SOA RR whose owner name is a superdomain
  657. # of qname.
  658. try:
  659. srrset = self.find_rrset(self.authority, auname,
  660. question.rdclass,
  661. dns.rdatatype.SOA)
  662. min_ttl = min(min_ttl, srrset.ttl, srrset[0].minimum)
  663. break
  664. except KeyError:
  665. try:
  666. auname = auname.parent()
  667. except dns.name.NoParent:
  668. break
  669. return ChainingResult(qname, answer, min_ttl, cnames)
  670. def canonical_name(self):
  671. """Return the canonical name of the first name in the question
  672. section.
  673. Raises ``dns.message.NotQueryResponse`` if the message is not
  674. a response.
  675. Raises ``dns.message.ChainTooLong`` if the CNAME chain is too long.
  676. Raises ``dns.message.AnswerForNXDOMAIN`` if the rcode is NXDOMAIN
  677. but an answer was found.
  678. Raises ``dns.exception.FormError`` if the question count is not 1.
  679. """
  680. return self.resolve_chaining().canonical_name
  681. def _maybe_import_update():
  682. # We avoid circular imports by doing this here. We do it in another
  683. # function as doing it in _message_factory_from_opcode() makes "dns"
  684. # a local symbol, and the first line fails :)
  685. # pylint: disable=redefined-outer-name,import-outside-toplevel,unused-import
  686. import dns.update # noqa: F401
  687. def _message_factory_from_opcode(opcode):
  688. if opcode == dns.opcode.QUERY:
  689. return QueryMessage
  690. elif opcode == dns.opcode.UPDATE:
  691. _maybe_import_update()
  692. return dns.update.UpdateMessage
  693. else:
  694. return Message
  695. class _WireReader:
  696. """Wire format reader.
  697. parser: the binary parser
  698. message: The message object being built
  699. initialize_message: Callback to set message parsing options
  700. question_only: Are we only reading the question?
  701. one_rr_per_rrset: Put each RR into its own RRset?
  702. keyring: TSIG keyring
  703. ignore_trailing: Ignore trailing junk at end of request?
  704. multi: Is this message part of a multi-message sequence?
  705. DNS dynamic updates.
  706. continue_on_error: try to extract as much information as possible from
  707. the message, accumulating MessageErrors in the *errors* attribute instead of
  708. raising them.
  709. """
  710. def __init__(self, wire, initialize_message, question_only=False,
  711. one_rr_per_rrset=False, ignore_trailing=False,
  712. keyring=None, multi=False, continue_on_error=False):
  713. self.parser = dns.wire.Parser(wire)
  714. self.message = None
  715. self.initialize_message = initialize_message
  716. self.question_only = question_only
  717. self.one_rr_per_rrset = one_rr_per_rrset
  718. self.ignore_trailing = ignore_trailing
  719. self.keyring = keyring
  720. self.multi = multi
  721. self.continue_on_error = continue_on_error
  722. self.errors = []
  723. def _get_question(self, section_number, qcount):
  724. """Read the next *qcount* records from the wire data and add them to
  725. the question section.
  726. """
  727. section = self.message.sections[section_number]
  728. for _ in range(qcount):
  729. qname = self.parser.get_name(self.message.origin)
  730. (rdtype, rdclass) = self.parser.get_struct('!HH')
  731. (rdclass, rdtype, _, _) = \
  732. self.message._parse_rr_header(section_number, qname, rdclass,
  733. rdtype)
  734. self.message.find_rrset(section, qname, rdclass, rdtype,
  735. create=True, force_unique=True)
  736. def _add_error(self, e):
  737. self.errors.append(MessageError(e, self.parser.current))
  738. def _get_section(self, section_number, count):
  739. """Read the next I{count} records from the wire data and add them to
  740. the specified section.
  741. section_number: the section of the message to which to add records
  742. count: the number of records to read
  743. """
  744. section = self.message.sections[section_number]
  745. force_unique = self.one_rr_per_rrset
  746. for i in range(count):
  747. rr_start = self.parser.current
  748. absolute_name = self.parser.get_name()
  749. if self.message.origin is not None:
  750. name = absolute_name.relativize(self.message.origin)
  751. else:
  752. name = absolute_name
  753. (rdtype, rdclass, ttl, rdlen) = self.parser.get_struct('!HHIH')
  754. if rdtype in (dns.rdatatype.OPT, dns.rdatatype.TSIG):
  755. (rdclass, rdtype, deleting, empty) = \
  756. self.message._parse_special_rr_header(section_number,
  757. count, i, name,
  758. rdclass, rdtype)
  759. else:
  760. (rdclass, rdtype, deleting, empty) = \
  761. self.message._parse_rr_header(section_number,
  762. name, rdclass, rdtype)
  763. try:
  764. rdata_start = self.parser.current
  765. if empty:
  766. if rdlen > 0:
  767. raise dns.exception.FormError
  768. rd = None
  769. covers = dns.rdatatype.NONE
  770. else:
  771. with self.parser.restrict_to(rdlen):
  772. rd = dns.rdata.from_wire_parser(rdclass, rdtype,
  773. self.parser,
  774. self.message.origin)
  775. covers = rd.covers()
  776. if self.message.xfr and rdtype == dns.rdatatype.SOA:
  777. force_unique = True
  778. if rdtype == dns.rdatatype.OPT:
  779. self.message.opt = dns.rrset.from_rdata(name, ttl, rd)
  780. elif rdtype == dns.rdatatype.TSIG:
  781. if self.keyring is None:
  782. raise UnknownTSIGKey('got signed message without '
  783. 'keyring')
  784. if isinstance(self.keyring, dict):
  785. key = self.keyring.get(absolute_name)
  786. if isinstance(key, bytes):
  787. key = dns.tsig.Key(absolute_name, key, rd.algorithm)
  788. elif callable(self.keyring):
  789. key = self.keyring(self.message, absolute_name)
  790. else:
  791. key = self.keyring
  792. if key is None:
  793. raise UnknownTSIGKey("key '%s' unknown" % name)
  794. self.message.keyring = key
  795. self.message.tsig_ctx = \
  796. dns.tsig.validate(self.parser.wire,
  797. key,
  798. absolute_name,
  799. rd,
  800. int(time.time()),
  801. self.message.request_mac,
  802. rr_start,
  803. self.message.tsig_ctx,
  804. self.multi)
  805. self.message.tsig = dns.rrset.from_rdata(absolute_name, 0,
  806. rd)
  807. else:
  808. rrset = self.message.find_rrset(section, name,
  809. rdclass, rdtype, covers,
  810. deleting, True,
  811. force_unique)
  812. if rd is not None:
  813. if ttl > 0x7fffffff:
  814. ttl = 0
  815. rrset.add(rd, ttl)
  816. except Exception as e:
  817. if self.continue_on_error:
  818. self._add_error(e)
  819. self.parser.seek(rdata_start + rdlen)
  820. else:
  821. raise
  822. def read(self):
  823. """Read a wire format DNS message and build a dns.message.Message
  824. object."""
  825. if self.parser.remaining() < 12:
  826. raise ShortHeader
  827. (id, flags, qcount, ancount, aucount, adcount) = \
  828. self.parser.get_struct('!HHHHHH')
  829. factory = _message_factory_from_opcode(dns.opcode.from_flags(flags))
  830. self.message = factory(id=id)
  831. self.message.flags = dns.flags.Flag(flags)
  832. self.initialize_message(self.message)
  833. self.one_rr_per_rrset = \
  834. self.message._get_one_rr_per_rrset(self.one_rr_per_rrset)
  835. try:
  836. self._get_question(MessageSection.QUESTION, qcount)
  837. if self.question_only:
  838. return self.message
  839. self._get_section(MessageSection.ANSWER, ancount)
  840. self._get_section(MessageSection.AUTHORITY, aucount)
  841. self._get_section(MessageSection.ADDITIONAL, adcount)
  842. if not self.ignore_trailing and self.parser.remaining() != 0:
  843. raise TrailingJunk
  844. if self.multi and self.message.tsig_ctx and \
  845. not self.message.had_tsig:
  846. self.message.tsig_ctx.update(self.parser.wire)
  847. except Exception as e:
  848. if self.continue_on_error:
  849. self._add_error(e)
  850. else:
  851. raise
  852. return self.message
  853. def from_wire(wire, keyring=None, request_mac=b'', xfr=False, origin=None,
  854. tsig_ctx=None, multi=False,
  855. question_only=False, one_rr_per_rrset=False,
  856. ignore_trailing=False, raise_on_truncation=False,
  857. continue_on_error=False):
  858. """Convert a DNS wire format message into a message object.
  859. *keyring*, a ``dns.tsig.Key`` or ``dict``, the key or keyring to use if the
  860. message is signed.
  861. *request_mac*, a ``bytes``. If the message is a response to a TSIG-signed
  862. request, *request_mac* should be set to the MAC of that request.
  863. *xfr*, a ``bool``, should be set to ``True`` if this message is part of a
  864. zone transfer.
  865. *origin*, a ``dns.name.Name`` or ``None``. If the message is part of a zone
  866. transfer, *origin* should be the origin name of the zone. If not ``None``,
  867. names will be relativized to the origin.
  868. *tsig_ctx*, a ``dns.tsig.HMACTSig`` or ``dns.tsig.GSSTSig`` object, the
  869. ongoing TSIG context, used when validating zone transfers.
  870. *multi*, a ``bool``, should be set to ``True`` if this message is part of a
  871. multiple message sequence.
  872. *question_only*, a ``bool``. If ``True``, read only up to the end of the
  873. question section.
  874. *one_rr_per_rrset*, a ``bool``. If ``True``, put each RR into its own
  875. RRset.
  876. *ignore_trailing*, a ``bool``. If ``True``, ignore trailing junk at end of
  877. the message.
  878. *raise_on_truncation*, a ``bool``. If ``True``, raise an exception if the
  879. TC bit is set.
  880. *continue_on_error*, a ``bool``. If ``True``, try to continue parsing even
  881. if errors occur. Erroneous rdata will be ignored. Errors will be
  882. accumulated as a list of MessageError objects in the message's ``errors``
  883. attribute. This option is recommended only for DNS analysis tools, or for
  884. use in a server as part of an error handling path. The default is
  885. ``False``.
  886. Raises ``dns.message.ShortHeader`` if the message is less than 12 octets
  887. long.
  888. Raises ``dns.message.TrailingJunk`` if there were octets in the message past
  889. the end of the proper DNS message, and *ignore_trailing* is ``False``.
  890. Raises ``dns.message.BadEDNS`` if an OPT record was in the wrong section, or
  891. occurred more than once.
  892. Raises ``dns.message.BadTSIG`` if a TSIG record was not the last record of
  893. the additional data section.
  894. Raises ``dns.message.Truncated`` if the TC flag is set and
  895. *raise_on_truncation* is ``True``.
  896. Returns a ``dns.message.Message``.
  897. """
  898. def initialize_message(message):
  899. message.request_mac = request_mac
  900. message.xfr = xfr
  901. message.origin = origin
  902. message.tsig_ctx = tsig_ctx
  903. reader = _WireReader(wire, initialize_message, question_only,
  904. one_rr_per_rrset, ignore_trailing, keyring, multi,
  905. continue_on_error)
  906. try:
  907. m = reader.read()
  908. except dns.exception.FormError:
  909. if reader.message and (reader.message.flags & dns.flags.TC) and \
  910. raise_on_truncation:
  911. raise Truncated(message=reader.message)
  912. else:
  913. raise
  914. # Reading a truncated message might not have any errors, so we
  915. # have to do this check here too.
  916. if m.flags & dns.flags.TC and raise_on_truncation:
  917. raise Truncated(message=m)
  918. if continue_on_error:
  919. m.errors = reader.errors
  920. return m
  921. class _TextReader:
  922. """Text format reader.
  923. tok: the tokenizer.
  924. message: The message object being built.
  925. DNS dynamic updates.
  926. last_name: The most recently read name when building a message object.
  927. one_rr_per_rrset: Put each RR into its own RRset?
  928. origin: The origin for relative names
  929. relativize: relativize names?
  930. relativize_to: the origin to relativize to.
  931. """
  932. def __init__(self, text, idna_codec, one_rr_per_rrset=False,
  933. origin=None, relativize=True, relativize_to=None):
  934. self.message = None
  935. self.tok = dns.tokenizer.Tokenizer(text, idna_codec=idna_codec)
  936. self.last_name = None
  937. self.one_rr_per_rrset = one_rr_per_rrset
  938. self.origin = origin
  939. self.relativize = relativize
  940. self.relativize_to = relativize_to
  941. self.id = None
  942. self.edns = -1
  943. self.ednsflags = 0
  944. self.payload = DEFAULT_EDNS_PAYLOAD
  945. self.rcode = None
  946. self.opcode = dns.opcode.QUERY
  947. self.flags = 0
  948. def _header_line(self, _):
  949. """Process one line from the text format header section."""
  950. token = self.tok.get()
  951. what = token.value
  952. if what == 'id':
  953. self.id = self.tok.get_int()
  954. elif what == 'flags':
  955. while True:
  956. token = self.tok.get()
  957. if not token.is_identifier():
  958. self.tok.unget(token)
  959. break
  960. self.flags = self.flags | dns.flags.from_text(token.value)
  961. elif what == 'edns':
  962. self.edns = self.tok.get_int()
  963. self.ednsflags = self.ednsflags | (self.edns << 16)
  964. elif what == 'eflags':
  965. if self.edns < 0:
  966. self.edns = 0
  967. while True:
  968. token = self.tok.get()
  969. if not token.is_identifier():
  970. self.tok.unget(token)
  971. break
  972. self.ednsflags = self.ednsflags | \
  973. dns.flags.edns_from_text(token.value)
  974. elif what == 'payload':
  975. self.payload = self.tok.get_int()
  976. if self.edns < 0:
  977. self.edns = 0
  978. elif what == 'opcode':
  979. text = self.tok.get_string()
  980. self.opcode = dns.opcode.from_text(text)
  981. self.flags = self.flags | dns.opcode.to_flags(self.opcode)
  982. elif what == 'rcode':
  983. text = self.tok.get_string()
  984. self.rcode = dns.rcode.from_text(text)
  985. else:
  986. raise UnknownHeaderField
  987. self.tok.get_eol()
  988. def _question_line(self, section_number):
  989. """Process one line from the text format question section."""
  990. section = self.message.sections[section_number]
  991. token = self.tok.get(want_leading=True)
  992. if not token.is_whitespace():
  993. self.last_name = self.tok.as_name(token, self.message.origin,
  994. self.relativize,
  995. self.relativize_to)
  996. name = self.last_name
  997. if name is None:
  998. raise NoPreviousName
  999. token = self.tok.get()
  1000. if not token.is_identifier():
  1001. raise dns.exception.SyntaxError
  1002. # Class
  1003. try:
  1004. rdclass = dns.rdataclass.from_text(token.value)
  1005. token = self.tok.get()
  1006. if not token.is_identifier():
  1007. raise dns.exception.SyntaxError
  1008. except dns.exception.SyntaxError:
  1009. raise dns.exception.SyntaxError
  1010. except Exception:
  1011. rdclass = dns.rdataclass.IN
  1012. # Type
  1013. rdtype = dns.rdatatype.from_text(token.value)
  1014. (rdclass, rdtype, _, _) = \
  1015. self.message._parse_rr_header(section_number, name, rdclass, rdtype)
  1016. self.message.find_rrset(section, name, rdclass, rdtype, create=True,
  1017. force_unique=True)
  1018. self.tok.get_eol()
  1019. def _rr_line(self, section_number):
  1020. """Process one line from the text format answer, authority, or
  1021. additional data sections.
  1022. """
  1023. section = self.message.sections[section_number]
  1024. # Name
  1025. token = self.tok.get(want_leading=True)
  1026. if not token.is_whitespace():
  1027. self.last_name = self.tok.as_name(token, self.message.origin,
  1028. self.relativize,
  1029. self.relativize_to)
  1030. name = self.last_name
  1031. if name is None:
  1032. raise NoPreviousName
  1033. token = self.tok.get()
  1034. if not token.is_identifier():
  1035. raise dns.exception.SyntaxError
  1036. # TTL
  1037. try:
  1038. ttl = int(token.value, 0)
  1039. token = self.tok.get()
  1040. if not token.is_identifier():
  1041. raise dns.exception.SyntaxError
  1042. except dns.exception.SyntaxError:
  1043. raise dns.exception.SyntaxError
  1044. except Exception:
  1045. ttl = 0
  1046. # Class
  1047. try:
  1048. rdclass = dns.rdataclass.from_text(token.value)
  1049. token = self.tok.get()
  1050. if not token.is_identifier():
  1051. raise dns.exception.SyntaxError
  1052. except dns.exception.SyntaxError:
  1053. raise dns.exception.SyntaxError
  1054. except Exception:
  1055. rdclass = dns.rdataclass.IN
  1056. # Type
  1057. rdtype = dns.rdatatype.from_text(token.value)
  1058. (rdclass, rdtype, deleting, empty) = \
  1059. self.message._parse_rr_header(section_number, name, rdclass, rdtype)
  1060. token = self.tok.get()
  1061. if empty and not token.is_eol_or_eof():
  1062. raise dns.exception.SyntaxError
  1063. if not empty and token.is_eol_or_eof():
  1064. raise dns.exception.UnexpectedEnd
  1065. if not token.is_eol_or_eof():
  1066. self.tok.unget(token)
  1067. rd = dns.rdata.from_text(rdclass, rdtype, self.tok,
  1068. self.message.origin, self.relativize,
  1069. self.relativize_to)
  1070. covers = rd.covers()
  1071. else:
  1072. rd = None
  1073. covers = dns.rdatatype.NONE
  1074. rrset = self.message.find_rrset(section, name,
  1075. rdclass, rdtype, covers,
  1076. deleting, True, self.one_rr_per_rrset)
  1077. if rd is not None:
  1078. rrset.add(rd, ttl)
  1079. def _make_message(self):
  1080. factory = _message_factory_from_opcode(self.opcode)
  1081. message = factory(id=self.id)
  1082. message.flags = self.flags
  1083. if self.edns >= 0:
  1084. message.use_edns(self.edns, self.ednsflags, self.payload)
  1085. if self.rcode:
  1086. message.set_rcode(self.rcode)
  1087. if self.origin:
  1088. message.origin = self.origin
  1089. return message
  1090. def read(self):
  1091. """Read a text format DNS message and build a dns.message.Message
  1092. object."""
  1093. line_method = self._header_line
  1094. section_number = None
  1095. while 1:
  1096. token = self.tok.get(True, True)
  1097. if token.is_eol_or_eof():
  1098. break
  1099. if token.is_comment():
  1100. u = token.value.upper()
  1101. if u == 'HEADER':
  1102. line_method = self._header_line
  1103. if self.message:
  1104. message = self.message
  1105. else:
  1106. # If we don't have a message, create one with the current
  1107. # opcode, so that we know which section names to parse.
  1108. message = self._make_message()
  1109. try:
  1110. section_number = message._section_enum.from_text(u)
  1111. # We found a section name. If we don't have a message,
  1112. # use the one we just created.
  1113. if not self.message:
  1114. self.message = message
  1115. self.one_rr_per_rrset = \
  1116. message._get_one_rr_per_rrset(self.one_rr_per_rrset)
  1117. if section_number == MessageSection.QUESTION:
  1118. line_method = self._question_line
  1119. else:
  1120. line_method = self._rr_line
  1121. except Exception:
  1122. # It's just a comment.
  1123. pass
  1124. self.tok.get_eol()
  1125. continue
  1126. self.tok.unget(token)
  1127. line_method(section_number)
  1128. if not self.message:
  1129. self.message = self._make_message()
  1130. return self.message
  1131. def from_text(text, idna_codec=None, one_rr_per_rrset=False,
  1132. origin=None, relativize=True, relativize_to=None):
  1133. """Convert the text format message into a message object.
  1134. The reader stops after reading the first blank line in the input to
  1135. facilitate reading multiple messages from a single file with
  1136. ``dns.message.from_file()``.
  1137. *text*, a ``str``, the text format message.
  1138. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  1139. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  1140. is used.
  1141. *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put
  1142. into its own rrset. The default is ``False``.
  1143. *origin*, a ``dns.name.Name`` (or ``None``), the
  1144. origin to use for relative names.
  1145. *relativize*, a ``bool``. If true, name will be relativized.
  1146. *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
  1147. when relativizing names. If not set, the *origin* value will be used.
  1148. Raises ``dns.message.UnknownHeaderField`` if a header is unknown.
  1149. Raises ``dns.exception.SyntaxError`` if the text is badly formed.
  1150. Returns a ``dns.message.Message object``
  1151. """
  1152. # 'text' can also be a file, but we don't publish that fact
  1153. # since it's an implementation detail. The official file
  1154. # interface is from_file().
  1155. reader = _TextReader(text, idna_codec, one_rr_per_rrset, origin,
  1156. relativize, relativize_to)
  1157. return reader.read()
  1158. def from_file(f, idna_codec=None, one_rr_per_rrset=False):
  1159. """Read the next text format message from the specified file.
  1160. Message blocks are separated by a single blank line.
  1161. *f*, a ``file`` or ``str``. If *f* is text, it is treated as the
  1162. pathname of a file to open.
  1163. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  1164. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  1165. is used.
  1166. *one_rr_per_rrset*, a ``bool``. If ``True``, then each RR is put
  1167. into its own rrset. The default is ``False``.
  1168. Raises ``dns.message.UnknownHeaderField`` if a header is unknown.
  1169. Raises ``dns.exception.SyntaxError`` if the text is badly formed.
  1170. Returns a ``dns.message.Message object``
  1171. """
  1172. with contextlib.ExitStack() as stack:
  1173. if isinstance(f, str):
  1174. f = stack.enter_context(open(f))
  1175. return from_text(f, idna_codec, one_rr_per_rrset)
  1176. def make_query(qname, rdtype, rdclass=dns.rdataclass.IN, use_edns=None,
  1177. want_dnssec=False, ednsflags=None, payload=None,
  1178. request_payload=None, options=None, idna_codec=None,
  1179. id=None, flags=dns.flags.RD):
  1180. """Make a query message.
  1181. The query name, type, and class may all be specified either
  1182. as objects of the appropriate type, or as strings.
  1183. The query will have a randomly chosen query id, and its DNS flags
  1184. will be set to dns.flags.RD.
  1185. qname, a ``dns.name.Name`` or ``str``, the query name.
  1186. *rdtype*, an ``int`` or ``str``, the desired rdata type.
  1187. *rdclass*, an ``int`` or ``str``, the desired rdata class; the default
  1188. is class IN.
  1189. *use_edns*, an ``int``, ``bool`` or ``None``. The EDNS level to use; the
  1190. default is ``None``. If ``None``, EDNS will be enabled only if other
  1191. parameters (*ednsflags*, *payload*, *request_payload*, or *options*) are
  1192. set.
  1193. See the description of dns.message.Message.use_edns() for the possible
  1194. values for use_edns and their meanings.
  1195. *want_dnssec*, a ``bool``. If ``True``, DNSSEC data is desired.
  1196. *ednsflags*, an ``int``, the EDNS flag values.
  1197. *payload*, an ``int``, is the EDNS sender's payload field, which is the
  1198. maximum size of UDP datagram the sender can handle. I.e. how big
  1199. a response to this message can be.
  1200. *request_payload*, an ``int``, is the EDNS payload size to use when
  1201. sending this message. If not specified, defaults to the value of
  1202. *payload*.
  1203. *options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS
  1204. options.
  1205. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  1206. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  1207. is used.
  1208. *id*, an ``int`` or ``None``, the desired query id. The default is
  1209. ``None``, which generates a random query id.
  1210. *flags*, an ``int``, the desired query flags. The default is
  1211. ``dns.flags.RD``.
  1212. Returns a ``dns.message.QueryMessage``
  1213. """
  1214. if isinstance(qname, str):
  1215. qname = dns.name.from_text(qname, idna_codec=idna_codec)
  1216. rdtype = dns.rdatatype.RdataType.make(rdtype)
  1217. rdclass = dns.rdataclass.RdataClass.make(rdclass)
  1218. m = QueryMessage(id=id)
  1219. m.flags = dns.flags.Flag(flags)
  1220. m.find_rrset(m.question, qname, rdclass, rdtype, create=True,
  1221. force_unique=True)
  1222. # only pass keywords on to use_edns if they have been set to a
  1223. # non-None value. Setting a field will turn EDNS on if it hasn't
  1224. # been configured.
  1225. kwargs = {}
  1226. if ednsflags is not None:
  1227. kwargs['ednsflags'] = ednsflags
  1228. if payload is not None:
  1229. kwargs['payload'] = payload
  1230. if request_payload is not None:
  1231. kwargs['request_payload'] = request_payload
  1232. if options is not None:
  1233. kwargs['options'] = options
  1234. if kwargs and use_edns is None:
  1235. use_edns = 0
  1236. kwargs['edns'] = use_edns
  1237. m.use_edns(**kwargs)
  1238. m.want_dnssec(want_dnssec)
  1239. return m
  1240. def make_response(query, recursion_available=False, our_payload=8192,
  1241. fudge=300, tsig_error=0):
  1242. """Make a message which is a response for the specified query.
  1243. The message returned is really a response skeleton; it has all
  1244. of the infrastructure required of a response, but none of the
  1245. content.
  1246. The response's question section is a shallow copy of the query's
  1247. question section, so the query's question RRsets should not be
  1248. changed.
  1249. *query*, a ``dns.message.Message``, the query to respond to.
  1250. *recursion_available*, a ``bool``, should RA be set in the response?
  1251. *our_payload*, an ``int``, the payload size to advertise in EDNS
  1252. responses.
  1253. *fudge*, an ``int``, the TSIG time fudge.
  1254. *tsig_error*, an ``int``, the TSIG error.
  1255. Returns a ``dns.message.Message`` object whose specific class is
  1256. appropriate for the query. For example, if query is a
  1257. ``dns.update.UpdateMessage``, response will be too.
  1258. """
  1259. if query.flags & dns.flags.QR:
  1260. raise dns.exception.FormError('specified query message is not a query')
  1261. factory = _message_factory_from_opcode(query.opcode())
  1262. response = factory(id=query.id)
  1263. response.flags = dns.flags.QR | (query.flags & dns.flags.RD)
  1264. if recursion_available:
  1265. response.flags |= dns.flags.RA
  1266. response.set_opcode(query.opcode())
  1267. response.question = list(query.question)
  1268. if query.edns >= 0:
  1269. response.use_edns(0, 0, our_payload, query.payload)
  1270. if query.had_tsig:
  1271. response.use_tsig(query.keyring, query.keyname, fudge, None,
  1272. tsig_error, b'', query.keyalgorithm)
  1273. response.request_mac = query.mac
  1274. return response
  1275. ### BEGIN generated MessageSection constants
  1276. QUESTION = MessageSection.QUESTION
  1277. ANSWER = MessageSection.ANSWER
  1278. AUTHORITY = MessageSection.AUTHORITY
  1279. ADDITIONAL = MessageSection.ADDITIONAL
  1280. ### END generated MessageSection constants