update.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2007, 2009-2011 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 Dynamic Update Support"""
  17. from typing import Any, List
  18. import dns.enum
  19. import dns.exception
  20. import dns.message
  21. import dns.name
  22. import dns.opcode
  23. import dns.rdata
  24. import dns.rdataclass
  25. import dns.rdataset
  26. import dns.rdatatype
  27. import dns.rrset
  28. import dns.tsig
  29. class UpdateSection(dns.enum.IntEnum):
  30. """Update sections"""
  31. ZONE = 0
  32. PREREQ = 1
  33. UPDATE = 2
  34. ADDITIONAL = 3
  35. @classmethod
  36. def _maximum(cls):
  37. return 3
  38. class UpdateMessage(dns.message.Message): # lgtm[py/missing-equals]
  39. # ignore the mypy error here as we mean to use a different enum
  40. _section_enum = UpdateSection # type: ignore
  41. def __init__(
  42. self,
  43. zone: dns.name.Name | str | None = None,
  44. rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
  45. keyring: Any | None = None,
  46. keyname: dns.name.Name | None = None,
  47. keyalgorithm: dns.name.Name | str = dns.tsig.default_algorithm,
  48. id: int | None = None,
  49. ):
  50. """Initialize a new DNS Update object.
  51. See the documentation of the Message class for a complete
  52. description of the keyring dictionary.
  53. *zone*, a ``dns.name.Name``, ``str``, or ``None``, the zone
  54. which is being updated. ``None`` should only be used by dnspython's
  55. message constructors, as a zone is required for the convenience
  56. methods like ``add()``, ``replace()``, etc.
  57. *rdclass*, an ``int`` or ``str``, the class of the zone.
  58. The *keyring*, *keyname*, and *keyalgorithm* parameters are passed to
  59. ``use_tsig()``; see its documentation for details.
  60. """
  61. super().__init__(id=id)
  62. self.flags |= dns.opcode.to_flags(dns.opcode.UPDATE)
  63. if isinstance(zone, str):
  64. zone = dns.name.from_text(zone)
  65. self.origin = zone
  66. rdclass = dns.rdataclass.RdataClass.make(rdclass)
  67. self.zone_rdclass = rdclass
  68. if self.origin:
  69. self.find_rrset(
  70. self.zone,
  71. self.origin,
  72. rdclass,
  73. dns.rdatatype.SOA,
  74. create=True,
  75. force_unique=True,
  76. )
  77. if keyring is not None:
  78. self.use_tsig(keyring, keyname, algorithm=keyalgorithm)
  79. @property
  80. def zone(self) -> List[dns.rrset.RRset]:
  81. """The zone section."""
  82. return self.sections[0]
  83. @zone.setter
  84. def zone(self, v):
  85. self.sections[0] = v
  86. @property
  87. def prerequisite(self) -> List[dns.rrset.RRset]:
  88. """The prerequisite section."""
  89. return self.sections[1]
  90. @prerequisite.setter
  91. def prerequisite(self, v):
  92. self.sections[1] = v
  93. @property
  94. def update(self) -> List[dns.rrset.RRset]:
  95. """The update section."""
  96. return self.sections[2]
  97. @update.setter
  98. def update(self, v):
  99. self.sections[2] = v
  100. def _add_rr(self, name, ttl, rd, deleting=None, section=None):
  101. """Add a single RR to the update section."""
  102. if section is None:
  103. section = self.update
  104. covers = rd.covers()
  105. rrset = self.find_rrset(
  106. section, name, self.zone_rdclass, rd.rdtype, covers, deleting, True, True
  107. )
  108. rrset.add(rd, ttl)
  109. def _add(self, replace, section, name, *args):
  110. """Add records.
  111. *replace* is the replacement mode. If ``False``,
  112. RRs are added to an existing RRset; if ``True``, the RRset
  113. is replaced with the specified contents. The second
  114. argument is the section to add to. The third argument
  115. is always a name. The other arguments can be:
  116. - rdataset...
  117. - ttl, rdata...
  118. - ttl, rdtype, string...
  119. """
  120. if isinstance(name, str):
  121. name = dns.name.from_text(name, None)
  122. if isinstance(args[0], dns.rdataset.Rdataset):
  123. for rds in args:
  124. if replace:
  125. self.delete(name, rds.rdtype)
  126. for rd in rds:
  127. self._add_rr(name, rds.ttl, rd, section=section)
  128. else:
  129. args = list(args)
  130. ttl = int(args.pop(0))
  131. if isinstance(args[0], dns.rdata.Rdata):
  132. if replace:
  133. self.delete(name, args[0].rdtype)
  134. for rd in args:
  135. self._add_rr(name, ttl, rd, section=section)
  136. else:
  137. rdtype = dns.rdatatype.RdataType.make(args.pop(0))
  138. if replace:
  139. self.delete(name, rdtype)
  140. for s in args:
  141. rd = dns.rdata.from_text(self.zone_rdclass, rdtype, s, self.origin)
  142. self._add_rr(name, ttl, rd, section=section)
  143. def add(self, name: dns.name.Name | str, *args: Any) -> None:
  144. """Add records.
  145. The first argument is always a name. The other
  146. arguments can be:
  147. - rdataset...
  148. - ttl, rdata...
  149. - ttl, rdtype, string...
  150. """
  151. self._add(False, self.update, name, *args)
  152. def delete(self, name: dns.name.Name | str, *args: Any) -> None:
  153. """Delete records.
  154. The first argument is always a name. The other
  155. arguments can be:
  156. - *empty*
  157. - rdataset...
  158. - rdata...
  159. - rdtype, [string...]
  160. """
  161. if isinstance(name, str):
  162. name = dns.name.from_text(name, None)
  163. if len(args) == 0:
  164. self.find_rrset(
  165. self.update,
  166. name,
  167. dns.rdataclass.ANY,
  168. dns.rdatatype.ANY,
  169. dns.rdatatype.NONE,
  170. dns.rdataclass.ANY,
  171. True,
  172. True,
  173. )
  174. elif isinstance(args[0], dns.rdataset.Rdataset):
  175. for rds in args:
  176. for rd in rds:
  177. self._add_rr(name, 0, rd, dns.rdataclass.NONE)
  178. else:
  179. largs = list(args)
  180. if isinstance(largs[0], dns.rdata.Rdata):
  181. for rd in largs:
  182. self._add_rr(name, 0, rd, dns.rdataclass.NONE)
  183. else:
  184. rdtype = dns.rdatatype.RdataType.make(largs.pop(0))
  185. if len(largs) == 0:
  186. self.find_rrset(
  187. self.update,
  188. name,
  189. self.zone_rdclass,
  190. rdtype,
  191. dns.rdatatype.NONE,
  192. dns.rdataclass.ANY,
  193. True,
  194. True,
  195. )
  196. else:
  197. for s in largs:
  198. rd = dns.rdata.from_text(
  199. self.zone_rdclass,
  200. rdtype,
  201. s, # type: ignore[arg-type]
  202. self.origin,
  203. )
  204. self._add_rr(name, 0, rd, dns.rdataclass.NONE)
  205. def replace(self, name: dns.name.Name | str, *args: Any) -> None:
  206. """Replace records.
  207. The first argument is always a name. The other
  208. arguments can be:
  209. - rdataset...
  210. - ttl, rdata...
  211. - ttl, rdtype, string...
  212. Note that if you want to replace the entire node, you should do
  213. a delete of the name followed by one or more calls to add.
  214. """
  215. self._add(True, self.update, name, *args)
  216. def present(self, name: dns.name.Name | str, *args: Any) -> None:
  217. """Require that an owner name (and optionally an rdata type,
  218. or specific rdataset) exists as a prerequisite to the
  219. execution of the update.
  220. The first argument is always a name.
  221. The other arguments can be:
  222. - rdataset...
  223. - rdata...
  224. - rdtype, string...
  225. """
  226. if isinstance(name, str):
  227. name = dns.name.from_text(name, None)
  228. if len(args) == 0:
  229. self.find_rrset(
  230. self.prerequisite,
  231. name,
  232. dns.rdataclass.ANY,
  233. dns.rdatatype.ANY,
  234. dns.rdatatype.NONE,
  235. None,
  236. True,
  237. True,
  238. )
  239. elif (
  240. isinstance(args[0], dns.rdataset.Rdataset)
  241. or isinstance(args[0], dns.rdata.Rdata)
  242. or len(args) > 1
  243. ):
  244. if not isinstance(args[0], dns.rdataset.Rdataset):
  245. # Add a 0 TTL
  246. largs = list(args)
  247. largs.insert(0, 0) # type: ignore[arg-type]
  248. self._add(False, self.prerequisite, name, *largs)
  249. else:
  250. self._add(False, self.prerequisite, name, *args)
  251. else:
  252. rdtype = dns.rdatatype.RdataType.make(args[0])
  253. self.find_rrset(
  254. self.prerequisite,
  255. name,
  256. dns.rdataclass.ANY,
  257. rdtype,
  258. dns.rdatatype.NONE,
  259. None,
  260. True,
  261. True,
  262. )
  263. def absent(
  264. self,
  265. name: dns.name.Name | str,
  266. rdtype: dns.rdatatype.RdataType | str | None = None,
  267. ) -> None:
  268. """Require that an owner name (and optionally an rdata type) does
  269. not exist as a prerequisite to the execution of the update."""
  270. if isinstance(name, str):
  271. name = dns.name.from_text(name, None)
  272. if rdtype is None:
  273. self.find_rrset(
  274. self.prerequisite,
  275. name,
  276. dns.rdataclass.NONE,
  277. dns.rdatatype.ANY,
  278. dns.rdatatype.NONE,
  279. None,
  280. True,
  281. True,
  282. )
  283. else:
  284. rdtype = dns.rdatatype.RdataType.make(rdtype)
  285. self.find_rrset(
  286. self.prerequisite,
  287. name,
  288. dns.rdataclass.NONE,
  289. rdtype,
  290. dns.rdatatype.NONE,
  291. None,
  292. True,
  293. True,
  294. )
  295. def _get_one_rr_per_rrset(self, value):
  296. # Updates are always one_rr_per_rrset
  297. return True
  298. def _parse_rr_header(self, section, name, rdclass, rdtype): # pyright: ignore
  299. deleting = None
  300. empty = False
  301. if section == UpdateSection.ZONE:
  302. if (
  303. dns.rdataclass.is_metaclass(rdclass)
  304. or rdtype != dns.rdatatype.SOA
  305. or self.zone
  306. ):
  307. raise dns.exception.FormError
  308. else:
  309. if not self.zone:
  310. raise dns.exception.FormError
  311. if rdclass in (dns.rdataclass.ANY, dns.rdataclass.NONE):
  312. deleting = rdclass
  313. rdclass = self.zone[0].rdclass
  314. empty = (
  315. deleting == dns.rdataclass.ANY or section == UpdateSection.PREREQ
  316. )
  317. return (rdclass, rdtype, deleting, empty)
  318. # backwards compatibility
  319. Update = UpdateMessage
  320. ### BEGIN generated UpdateSection constants
  321. ZONE = UpdateSection.ZONE
  322. PREREQ = UpdateSection.PREREQ
  323. UPDATE = UpdateSection.UPDATE
  324. ADDITIONAL = UpdateSection.ADDITIONAL
  325. ### END generated UpdateSection constants