name.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  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 Names."""
  17. import copy
  18. import encodings.idna # type: ignore
  19. import functools
  20. import struct
  21. from typing import Any, Callable, Dict, Iterable, Optional, Tuple
  22. import dns._features
  23. import dns.enum
  24. import dns.exception
  25. import dns.immutable
  26. import dns.wire
  27. # Dnspython will never access idna if the import fails, but pyright can't figure
  28. # that out, so...
  29. #
  30. # pyright: reportAttributeAccessIssue = false, reportPossiblyUnboundVariable = false
  31. if dns._features.have("idna"):
  32. import idna # type: ignore
  33. have_idna_2008 = True
  34. else: # pragma: no cover
  35. have_idna_2008 = False
  36. CompressType = Dict["Name", int]
  37. class NameRelation(dns.enum.IntEnum):
  38. """Name relation result from fullcompare()."""
  39. # This is an IntEnum for backwards compatibility in case anyone
  40. # has hardwired the constants.
  41. #: The compared names have no relationship to each other.
  42. NONE = 0
  43. #: the first name is a superdomain of the second.
  44. SUPERDOMAIN = 1
  45. #: The first name is a subdomain of the second.
  46. SUBDOMAIN = 2
  47. #: The compared names are equal.
  48. EQUAL = 3
  49. #: The compared names have a common ancestor.
  50. COMMONANCESTOR = 4
  51. @classmethod
  52. def _maximum(cls):
  53. return cls.COMMONANCESTOR # pragma: no cover
  54. @classmethod
  55. def _short_name(cls):
  56. return cls.__name__ # pragma: no cover
  57. # Backwards compatibility
  58. NAMERELN_NONE = NameRelation.NONE
  59. NAMERELN_SUPERDOMAIN = NameRelation.SUPERDOMAIN
  60. NAMERELN_SUBDOMAIN = NameRelation.SUBDOMAIN
  61. NAMERELN_EQUAL = NameRelation.EQUAL
  62. NAMERELN_COMMONANCESTOR = NameRelation.COMMONANCESTOR
  63. class EmptyLabel(dns.exception.SyntaxError):
  64. """A DNS label is empty."""
  65. class BadEscape(dns.exception.SyntaxError):
  66. """An escaped code in a text format of DNS name is invalid."""
  67. class BadPointer(dns.exception.FormError):
  68. """A DNS compression pointer points forward instead of backward."""
  69. class BadLabelType(dns.exception.FormError):
  70. """The label type in DNS name wire format is unknown."""
  71. class NeedAbsoluteNameOrOrigin(dns.exception.DNSException):
  72. """An attempt was made to convert a non-absolute name to
  73. wire when there was also a non-absolute (or missing) origin."""
  74. class NameTooLong(dns.exception.FormError):
  75. """A DNS name is > 255 octets long."""
  76. class LabelTooLong(dns.exception.SyntaxError):
  77. """A DNS label is > 63 octets long."""
  78. class AbsoluteConcatenation(dns.exception.DNSException):
  79. """An attempt was made to append anything other than the
  80. empty name to an absolute DNS name."""
  81. class NoParent(dns.exception.DNSException):
  82. """An attempt was made to get the parent of the root name
  83. or the empty name."""
  84. class NoIDNA2008(dns.exception.DNSException):
  85. """IDNA 2008 processing was requested but the idna module is not
  86. available."""
  87. class IDNAException(dns.exception.DNSException):
  88. """IDNA processing raised an exception."""
  89. supp_kwargs = {"idna_exception"}
  90. fmt = "IDNA processing exception: {idna_exception}"
  91. # We do this as otherwise mypy complains about unexpected keyword argument
  92. # idna_exception
  93. def __init__(self, *args, **kwargs):
  94. super().__init__(*args, **kwargs)
  95. class NeedSubdomainOfOrigin(dns.exception.DNSException):
  96. """An absolute name was provided that is not a subdomain of the specified origin."""
  97. _escaped = b'"().;\\@$'
  98. _escaped_text = '"().;\\@$'
  99. def _escapify(label: bytes | str) -> str:
  100. """Escape the characters in label which need it.
  101. @returns: the escaped string
  102. @rtype: string"""
  103. if isinstance(label, bytes):
  104. # Ordinary DNS label mode. Escape special characters and values
  105. # < 0x20 or > 0x7f.
  106. text = ""
  107. for c in label:
  108. if c in _escaped:
  109. text += "\\" + chr(c)
  110. elif c > 0x20 and c < 0x7F:
  111. text += chr(c)
  112. else:
  113. text += f"\\{c:03d}"
  114. return text
  115. # Unicode label mode. Escape only special characters and values < 0x20
  116. text = ""
  117. for uc in label:
  118. if uc in _escaped_text:
  119. text += "\\" + uc
  120. elif uc <= "\x20":
  121. text += f"\\{ord(uc):03d}"
  122. else:
  123. text += uc
  124. return text
  125. class IDNACodec:
  126. """Abstract base class for IDNA encoder/decoders."""
  127. def __init__(self):
  128. pass
  129. def is_idna(self, label: bytes) -> bool:
  130. return label.lower().startswith(b"xn--")
  131. def encode(self, label: str) -> bytes:
  132. raise NotImplementedError # pragma: no cover
  133. def decode(self, label: bytes) -> str:
  134. # We do not apply any IDNA policy on decode.
  135. if self.is_idna(label):
  136. try:
  137. slabel = label[4:].decode("punycode")
  138. return _escapify(slabel)
  139. except Exception as e:
  140. raise IDNAException(idna_exception=e)
  141. else:
  142. return _escapify(label)
  143. class IDNA2003Codec(IDNACodec):
  144. """IDNA 2003 encoder/decoder."""
  145. def __init__(self, strict_decode: bool = False):
  146. """Initialize the IDNA 2003 encoder/decoder.
  147. *strict_decode* is a ``bool``. If `True`, then IDNA2003 checking
  148. is done when decoding. This can cause failures if the name
  149. was encoded with IDNA2008. The default is `False`.
  150. """
  151. super().__init__()
  152. self.strict_decode = strict_decode
  153. def encode(self, label: str) -> bytes:
  154. """Encode *label*."""
  155. if label == "":
  156. return b""
  157. try:
  158. return encodings.idna.ToASCII(label)
  159. except UnicodeError:
  160. raise LabelTooLong
  161. def decode(self, label: bytes) -> str:
  162. """Decode *label*."""
  163. if not self.strict_decode:
  164. return super().decode(label)
  165. if label == b"":
  166. return ""
  167. try:
  168. return _escapify(encodings.idna.ToUnicode(label))
  169. except Exception as e:
  170. raise IDNAException(idna_exception=e)
  171. class IDNA2008Codec(IDNACodec):
  172. """IDNA 2008 encoder/decoder."""
  173. def __init__(
  174. self,
  175. uts_46: bool = False,
  176. transitional: bool = False,
  177. allow_pure_ascii: bool = False,
  178. strict_decode: bool = False,
  179. ):
  180. """Initialize the IDNA 2008 encoder/decoder.
  181. *uts_46* is a ``bool``. If True, apply Unicode IDNA
  182. compatibility processing as described in Unicode Technical
  183. Standard #46 (https://unicode.org/reports/tr46/).
  184. If False, do not apply the mapping. The default is False.
  185. *transitional* is a ``bool``: If True, use the
  186. "transitional" mode described in Unicode Technical Standard
  187. #46. The default is False.
  188. *allow_pure_ascii* is a ``bool``. If True, then a label which
  189. consists of only ASCII characters is allowed. This is less
  190. strict than regular IDNA 2008, but is also necessary for mixed
  191. names, e.g. a name with starting with "_sip._tcp." and ending
  192. in an IDN suffix which would otherwise be disallowed. The
  193. default is False.
  194. *strict_decode* is a ``bool``: If True, then IDNA2008 checking
  195. is done when decoding. This can cause failures if the name
  196. was encoded with IDNA2003. The default is False.
  197. """
  198. super().__init__()
  199. self.uts_46 = uts_46
  200. self.transitional = transitional
  201. self.allow_pure_ascii = allow_pure_ascii
  202. self.strict_decode = strict_decode
  203. def encode(self, label: str) -> bytes:
  204. if label == "":
  205. return b""
  206. if self.allow_pure_ascii and is_all_ascii(label):
  207. encoded = label.encode("ascii")
  208. if len(encoded) > 63:
  209. raise LabelTooLong
  210. return encoded
  211. if not have_idna_2008:
  212. raise NoIDNA2008
  213. try:
  214. if self.uts_46:
  215. # pylint: disable=possibly-used-before-assignment
  216. label = idna.uts46_remap(label, False, self.transitional)
  217. return idna.alabel(label)
  218. except idna.IDNAError as e:
  219. if e.args[0] == "Label too long":
  220. raise LabelTooLong
  221. else:
  222. raise IDNAException(idna_exception=e)
  223. def decode(self, label: bytes) -> str:
  224. if not self.strict_decode:
  225. return super().decode(label)
  226. if label == b"":
  227. return ""
  228. if not have_idna_2008:
  229. raise NoIDNA2008
  230. try:
  231. ulabel = idna.ulabel(label)
  232. if self.uts_46:
  233. ulabel = idna.uts46_remap(ulabel, False, self.transitional)
  234. return _escapify(ulabel)
  235. except (idna.IDNAError, UnicodeError) as e:
  236. raise IDNAException(idna_exception=e)
  237. IDNA_2003_Practical = IDNA2003Codec(False)
  238. IDNA_2003_Strict = IDNA2003Codec(True)
  239. IDNA_2003 = IDNA_2003_Practical
  240. IDNA_2008_Practical = IDNA2008Codec(True, False, True, False)
  241. IDNA_2008_UTS_46 = IDNA2008Codec(True, False, False, False)
  242. IDNA_2008_Strict = IDNA2008Codec(False, False, False, True)
  243. IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False)
  244. IDNA_2008 = IDNA_2008_Practical
  245. def _validate_labels(labels: Tuple[bytes, ...]) -> None:
  246. """Check for empty labels in the middle of a label sequence,
  247. labels that are too long, and for too many labels.
  248. Raises ``dns.name.NameTooLong`` if the name as a whole is too long.
  249. Raises ``dns.name.EmptyLabel`` if a label is empty (i.e. the root
  250. label) and appears in a position other than the end of the label
  251. sequence
  252. """
  253. l = len(labels)
  254. total = 0
  255. i = -1
  256. j = 0
  257. for label in labels:
  258. ll = len(label)
  259. total += ll + 1
  260. if ll > 63:
  261. raise LabelTooLong
  262. if i < 0 and label == b"":
  263. i = j
  264. j += 1
  265. if total > 255:
  266. raise NameTooLong
  267. if i >= 0 and i != l - 1:
  268. raise EmptyLabel
  269. def _maybe_convert_to_binary(label: bytes | str) -> bytes:
  270. """If label is ``str``, convert it to ``bytes``. If it is already
  271. ``bytes`` just return it.
  272. """
  273. if isinstance(label, bytes):
  274. return label
  275. if isinstance(label, str):
  276. return label.encode()
  277. raise ValueError # pragma: no cover
  278. @dns.immutable.immutable
  279. class Name:
  280. """A DNS name.
  281. The dns.name.Name class represents a DNS name as a tuple of
  282. labels. Each label is a ``bytes`` in DNS wire format. Instances
  283. of the class are immutable.
  284. """
  285. __slots__ = ["labels"]
  286. def __init__(self, labels: Iterable[bytes | str]):
  287. """*labels* is any iterable whose values are ``str`` or ``bytes``."""
  288. blabels = [_maybe_convert_to_binary(x) for x in labels]
  289. self.labels = tuple(blabels)
  290. _validate_labels(self.labels)
  291. def __copy__(self):
  292. return Name(self.labels)
  293. def __deepcopy__(self, memo):
  294. return Name(copy.deepcopy(self.labels, memo))
  295. def __getstate__(self):
  296. # Names can be pickled
  297. return {"labels": self.labels}
  298. def __setstate__(self, state):
  299. super().__setattr__("labels", state["labels"])
  300. _validate_labels(self.labels)
  301. def is_absolute(self) -> bool:
  302. """Is the most significant label of this name the root label?
  303. Returns a ``bool``.
  304. """
  305. return len(self.labels) > 0 and self.labels[-1] == b""
  306. def is_wild(self) -> bool:
  307. """Is this name wild? (I.e. Is the least significant label '*'?)
  308. Returns a ``bool``.
  309. """
  310. return len(self.labels) > 0 and self.labels[0] == b"*"
  311. def __hash__(self) -> int:
  312. """Return a case-insensitive hash of the name.
  313. Returns an ``int``.
  314. """
  315. h = 0
  316. for label in self.labels:
  317. for c in label.lower():
  318. h += (h << 3) + c
  319. return h
  320. def fullcompare(self, other: "Name") -> Tuple[NameRelation, int, int]:
  321. """Compare two names, returning a 3-tuple
  322. ``(relation, order, nlabels)``.
  323. *relation* describes the relation ship between the names,
  324. and is one of: ``dns.name.NameRelation.NONE``,
  325. ``dns.name.NameRelation.SUPERDOMAIN``, ``dns.name.NameRelation.SUBDOMAIN``,
  326. ``dns.name.NameRelation.EQUAL``, or ``dns.name.NameRelation.COMMONANCESTOR``.
  327. *order* is < 0 if *self* < *other*, > 0 if *self* > *other*, and ==
  328. 0 if *self* == *other*. A relative name is always less than an
  329. absolute name. If both names have the same relativity, then
  330. the DNSSEC order relation is used to order them.
  331. *nlabels* is the number of significant labels that the two names
  332. have in common.
  333. Here are some examples. Names ending in "." are absolute names,
  334. those not ending in "." are relative names.
  335. ============= ============= =========== ===== =======
  336. self other relation order nlabels
  337. ============= ============= =========== ===== =======
  338. www.example. www.example. equal 0 3
  339. www.example. example. subdomain > 0 2
  340. example. www.example. superdomain < 0 2
  341. example1.com. example2.com. common anc. < 0 2
  342. example1 example2. none < 0 0
  343. example1. example2 none > 0 0
  344. ============= ============= =========== ===== =======
  345. """
  346. sabs = self.is_absolute()
  347. oabs = other.is_absolute()
  348. if sabs != oabs:
  349. if sabs:
  350. return (NameRelation.NONE, 1, 0)
  351. else:
  352. return (NameRelation.NONE, -1, 0)
  353. l1 = len(self.labels)
  354. l2 = len(other.labels)
  355. ldiff = l1 - l2
  356. if ldiff < 0:
  357. l = l1
  358. else:
  359. l = l2
  360. order = 0
  361. nlabels = 0
  362. namereln = NameRelation.NONE
  363. while l > 0:
  364. l -= 1
  365. l1 -= 1
  366. l2 -= 1
  367. label1 = self.labels[l1].lower()
  368. label2 = other.labels[l2].lower()
  369. if label1 < label2:
  370. order = -1
  371. if nlabels > 0:
  372. namereln = NameRelation.COMMONANCESTOR
  373. return (namereln, order, nlabels)
  374. elif label1 > label2:
  375. order = 1
  376. if nlabels > 0:
  377. namereln = NameRelation.COMMONANCESTOR
  378. return (namereln, order, nlabels)
  379. nlabels += 1
  380. order = ldiff
  381. if ldiff < 0:
  382. namereln = NameRelation.SUPERDOMAIN
  383. elif ldiff > 0:
  384. namereln = NameRelation.SUBDOMAIN
  385. else:
  386. namereln = NameRelation.EQUAL
  387. return (namereln, order, nlabels)
  388. def is_subdomain(self, other: "Name") -> bool:
  389. """Is self a subdomain of other?
  390. Note that the notion of subdomain includes equality, e.g.
  391. "dnspython.org" is a subdomain of itself.
  392. Returns a ``bool``.
  393. """
  394. (nr, _, _) = self.fullcompare(other)
  395. if nr == NameRelation.SUBDOMAIN or nr == NameRelation.EQUAL:
  396. return True
  397. return False
  398. def is_superdomain(self, other: "Name") -> bool:
  399. """Is self a superdomain of other?
  400. Note that the notion of superdomain includes equality, e.g.
  401. "dnspython.org" is a superdomain of itself.
  402. Returns a ``bool``.
  403. """
  404. (nr, _, _) = self.fullcompare(other)
  405. if nr == NameRelation.SUPERDOMAIN or nr == NameRelation.EQUAL:
  406. return True
  407. return False
  408. def canonicalize(self) -> "Name":
  409. """Return a name which is equal to the current name, but is in
  410. DNSSEC canonical form.
  411. """
  412. return Name([x.lower() for x in self.labels])
  413. def __eq__(self, other):
  414. if isinstance(other, Name):
  415. return self.fullcompare(other)[1] == 0
  416. else:
  417. return False
  418. def __ne__(self, other):
  419. if isinstance(other, Name):
  420. return self.fullcompare(other)[1] != 0
  421. else:
  422. return True
  423. def __lt__(self, other):
  424. if isinstance(other, Name):
  425. return self.fullcompare(other)[1] < 0
  426. else:
  427. return NotImplemented
  428. def __le__(self, other):
  429. if isinstance(other, Name):
  430. return self.fullcompare(other)[1] <= 0
  431. else:
  432. return NotImplemented
  433. def __ge__(self, other):
  434. if isinstance(other, Name):
  435. return self.fullcompare(other)[1] >= 0
  436. else:
  437. return NotImplemented
  438. def __gt__(self, other):
  439. if isinstance(other, Name):
  440. return self.fullcompare(other)[1] > 0
  441. else:
  442. return NotImplemented
  443. def __repr__(self):
  444. return "<DNS name " + self.__str__() + ">"
  445. def __str__(self):
  446. return self.to_text(False)
  447. def to_text(self, omit_final_dot: bool = False) -> str:
  448. """Convert name to DNS text format.
  449. *omit_final_dot* is a ``bool``. If True, don't emit the final
  450. dot (denoting the root label) for absolute names. The default
  451. is False.
  452. Returns a ``str``.
  453. """
  454. if len(self.labels) == 0:
  455. return "@"
  456. if len(self.labels) == 1 and self.labels[0] == b"":
  457. return "."
  458. if omit_final_dot and self.is_absolute():
  459. l = self.labels[:-1]
  460. else:
  461. l = self.labels
  462. s = ".".join(map(_escapify, l))
  463. return s
  464. def to_unicode(
  465. self, omit_final_dot: bool = False, idna_codec: IDNACodec | None = None
  466. ) -> str:
  467. """Convert name to Unicode text format.
  468. IDN ACE labels are converted to Unicode.
  469. *omit_final_dot* is a ``bool``. If True, don't emit the final
  470. dot (denoting the root label) for absolute names. The default
  471. is False.
  472. *idna_codec* specifies the IDNA encoder/decoder. If None, the
  473. dns.name.IDNA_2003_Practical encoder/decoder is used.
  474. The IDNA_2003_Practical decoder does
  475. not impose any policy, it just decodes punycode, so if you
  476. don't want checking for compliance, you can use this decoder
  477. for IDNA2008 as well.
  478. Returns a ``str``.
  479. """
  480. if len(self.labels) == 0:
  481. return "@"
  482. if len(self.labels) == 1 and self.labels[0] == b"":
  483. return "."
  484. if omit_final_dot and self.is_absolute():
  485. l = self.labels[:-1]
  486. else:
  487. l = self.labels
  488. if idna_codec is None:
  489. idna_codec = IDNA_2003_Practical
  490. return ".".join([idna_codec.decode(x) for x in l])
  491. def to_digestable(self, origin: Optional["Name"] = None) -> bytes:
  492. """Convert name to a format suitable for digesting in hashes.
  493. The name is canonicalized and converted to uncompressed wire
  494. format. All names in wire format are absolute. If the name
  495. is a relative name, then an origin must be supplied.
  496. *origin* is a ``dns.name.Name`` or ``None``. If the name is
  497. relative and origin is not ``None``, then origin will be appended
  498. to the name.
  499. Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is
  500. relative and no origin was provided.
  501. Returns a ``bytes``.
  502. """
  503. digest = self.to_wire(origin=origin, canonicalize=True)
  504. assert digest is not None
  505. return digest
  506. def to_wire(
  507. self,
  508. file: Any | None = None,
  509. compress: CompressType | None = None,
  510. origin: Optional["Name"] = None,
  511. canonicalize: bool = False,
  512. ) -> bytes | None:
  513. """Convert name to wire format, possibly compressing it.
  514. *file* is the file where the name is emitted (typically an
  515. io.BytesIO file). If ``None`` (the default), a ``bytes``
  516. containing the wire name will be returned.
  517. *compress*, a ``dict``, is the compression table to use. If
  518. ``None`` (the default), names will not be compressed. Note that
  519. the compression code assumes that compression offset 0 is the
  520. start of *file*, and thus compression will not be correct
  521. if this is not the case.
  522. *origin* is a ``dns.name.Name`` or ``None``. If the name is
  523. relative and origin is not ``None``, then *origin* will be appended
  524. to it.
  525. *canonicalize*, a ``bool``, indicates whether the name should
  526. be canonicalized; that is, converted to a format suitable for
  527. digesting in hashes.
  528. Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is
  529. relative and no origin was provided.
  530. Returns a ``bytes`` or ``None``.
  531. """
  532. if file is None:
  533. out = bytearray()
  534. for label in self.labels:
  535. out.append(len(label))
  536. if canonicalize:
  537. out += label.lower()
  538. else:
  539. out += label
  540. if not self.is_absolute():
  541. if origin is None or not origin.is_absolute():
  542. raise NeedAbsoluteNameOrOrigin
  543. for label in origin.labels:
  544. out.append(len(label))
  545. if canonicalize:
  546. out += label.lower()
  547. else:
  548. out += label
  549. return bytes(out)
  550. labels: Iterable[bytes]
  551. if not self.is_absolute():
  552. if origin is None or not origin.is_absolute():
  553. raise NeedAbsoluteNameOrOrigin
  554. labels = list(self.labels)
  555. labels.extend(list(origin.labels))
  556. else:
  557. labels = self.labels
  558. i = 0
  559. for label in labels:
  560. n = Name(labels[i:])
  561. i += 1
  562. if compress is not None:
  563. pos = compress.get(n)
  564. else:
  565. pos = None
  566. if pos is not None:
  567. value = 0xC000 + pos
  568. s = struct.pack("!H", value)
  569. file.write(s)
  570. break
  571. else:
  572. if compress is not None and len(n) > 1:
  573. pos = file.tell()
  574. if pos <= 0x3FFF:
  575. compress[n] = pos
  576. l = len(label)
  577. file.write(struct.pack("!B", l))
  578. if l > 0:
  579. if canonicalize:
  580. file.write(label.lower())
  581. else:
  582. file.write(label)
  583. return None
  584. def __len__(self) -> int:
  585. """The length of the name (in labels).
  586. Returns an ``int``.
  587. """
  588. return len(self.labels)
  589. def __getitem__(self, index):
  590. return self.labels[index]
  591. def __add__(self, other):
  592. return self.concatenate(other)
  593. def __sub__(self, other):
  594. return self.relativize(other)
  595. def split(self, depth: int) -> Tuple["Name", "Name"]:
  596. """Split a name into a prefix and suffix names at the specified depth.
  597. *depth* is an ``int`` specifying the number of labels in the suffix
  598. Raises ``ValueError`` if *depth* was not >= 0 and <= the length of the
  599. name.
  600. Returns the tuple ``(prefix, suffix)``.
  601. """
  602. l = len(self.labels)
  603. if depth == 0:
  604. return (self, dns.name.empty)
  605. elif depth == l:
  606. return (dns.name.empty, self)
  607. elif depth < 0 or depth > l:
  608. raise ValueError("depth must be >= 0 and <= the length of the name")
  609. return (Name(self[:-depth]), Name(self[-depth:]))
  610. def concatenate(self, other: "Name") -> "Name":
  611. """Return a new name which is the concatenation of self and other.
  612. Raises ``dns.name.AbsoluteConcatenation`` if the name is
  613. absolute and *other* is not the empty name.
  614. Returns a ``dns.name.Name``.
  615. """
  616. if self.is_absolute() and len(other) > 0:
  617. raise AbsoluteConcatenation
  618. labels = list(self.labels)
  619. labels.extend(list(other.labels))
  620. return Name(labels)
  621. def relativize(self, origin: "Name") -> "Name":
  622. """If the name is a subdomain of *origin*, return a new name which is
  623. the name relative to origin. Otherwise return the name.
  624. For example, relativizing ``www.dnspython.org.`` to origin
  625. ``dnspython.org.`` returns the name ``www``. Relativizing ``example.``
  626. to origin ``dnspython.org.`` returns ``example.``.
  627. Returns a ``dns.name.Name``.
  628. """
  629. if origin is not None and self.is_subdomain(origin):
  630. return Name(self[: -len(origin)])
  631. else:
  632. return self
  633. def derelativize(self, origin: "Name") -> "Name":
  634. """If the name is a relative name, return a new name which is the
  635. concatenation of the name and origin. Otherwise return the name.
  636. For example, derelativizing ``www`` to origin ``dnspython.org.``
  637. returns the name ``www.dnspython.org.``. Derelativizing ``example.``
  638. to origin ``dnspython.org.`` returns ``example.``.
  639. Returns a ``dns.name.Name``.
  640. """
  641. if not self.is_absolute():
  642. return self.concatenate(origin)
  643. else:
  644. return self
  645. def choose_relativity(
  646. self, origin: Optional["Name"] = None, relativize: bool = True
  647. ) -> "Name":
  648. """Return a name with the relativity desired by the caller.
  649. If *origin* is ``None``, then the name is returned.
  650. Otherwise, if *relativize* is ``True`` the name is
  651. relativized, and if *relativize* is ``False`` the name is
  652. derelativized.
  653. Returns a ``dns.name.Name``.
  654. """
  655. if origin:
  656. if relativize:
  657. return self.relativize(origin)
  658. else:
  659. return self.derelativize(origin)
  660. else:
  661. return self
  662. def parent(self) -> "Name":
  663. """Return the parent of the name.
  664. For example, the parent of ``www.dnspython.org.`` is ``dnspython.org``.
  665. Raises ``dns.name.NoParent`` if the name is either the root name or the
  666. empty name, and thus has no parent.
  667. Returns a ``dns.name.Name``.
  668. """
  669. if self == root or self == empty:
  670. raise NoParent
  671. return Name(self.labels[1:])
  672. def predecessor(self, origin: "Name", prefix_ok: bool = True) -> "Name":
  673. """Return the maximal predecessor of *name* in the DNSSEC ordering in the zone
  674. whose origin is *origin*, or return the longest name under *origin* if the
  675. name is origin (i.e. wrap around to the longest name, which may still be
  676. *origin* due to length considerations.
  677. The relativity of the name is preserved, so if this name is relative
  678. then the method will return a relative name, and likewise if this name
  679. is absolute then the predecessor will be absolute.
  680. *prefix_ok* indicates if prefixing labels is allowed, and
  681. defaults to ``True``. Normally it is good to allow this, but if computing
  682. a maximal predecessor at a zone cut point then ``False`` must be specified.
  683. """
  684. return _handle_relativity_and_call(
  685. _absolute_predecessor, self, origin, prefix_ok
  686. )
  687. def successor(self, origin: "Name", prefix_ok: bool = True) -> "Name":
  688. """Return the minimal successor of *name* in the DNSSEC ordering in the zone
  689. whose origin is *origin*, or return *origin* if the successor cannot be
  690. computed due to name length limitations.
  691. Note that *origin* is returned in the "too long" cases because wrapping
  692. around to the origin is how NSEC records express "end of the zone".
  693. The relativity of the name is preserved, so if this name is relative
  694. then the method will return a relative name, and likewise if this name
  695. is absolute then the successor will be absolute.
  696. *prefix_ok* indicates if prefixing a new minimal label is allowed, and
  697. defaults to ``True``. Normally it is good to allow this, but if computing
  698. a minimal successor at a zone cut point then ``False`` must be specified.
  699. """
  700. return _handle_relativity_and_call(_absolute_successor, self, origin, prefix_ok)
  701. #: The root name, '.'
  702. root = Name([b""])
  703. #: The empty name.
  704. empty = Name([])
  705. def from_unicode(
  706. text: str, origin: Name | None = root, idna_codec: IDNACodec | None = None
  707. ) -> Name:
  708. """Convert unicode text into a Name object.
  709. Labels are encoded in IDN ACE form according to rules specified by
  710. the IDNA codec.
  711. *text*, a ``str``, is the text to convert into a name.
  712. *origin*, a ``dns.name.Name``, specifies the origin to
  713. append to non-absolute names. The default is the root name.
  714. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  715. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  716. is used.
  717. Returns a ``dns.name.Name``.
  718. """
  719. if not isinstance(text, str):
  720. raise ValueError("input to from_unicode() must be a unicode string")
  721. if not (origin is None or isinstance(origin, Name)):
  722. raise ValueError("origin must be a Name or None")
  723. labels = []
  724. label = ""
  725. escaping = False
  726. edigits = 0
  727. total = 0
  728. if idna_codec is None:
  729. idna_codec = IDNA_2003
  730. if text == "@":
  731. text = ""
  732. if text:
  733. if text in [".", "\u3002", "\uff0e", "\uff61"]:
  734. return Name([b""]) # no Unicode "u" on this constant!
  735. for c in text:
  736. if escaping:
  737. if edigits == 0:
  738. if c.isdigit():
  739. total = int(c)
  740. edigits += 1
  741. else:
  742. label += c
  743. escaping = False
  744. else:
  745. if not c.isdigit():
  746. raise BadEscape
  747. total *= 10
  748. total += int(c)
  749. edigits += 1
  750. if edigits == 3:
  751. escaping = False
  752. label += chr(total)
  753. elif c in [".", "\u3002", "\uff0e", "\uff61"]:
  754. if len(label) == 0:
  755. raise EmptyLabel
  756. labels.append(idna_codec.encode(label))
  757. label = ""
  758. elif c == "\\":
  759. escaping = True
  760. edigits = 0
  761. total = 0
  762. else:
  763. label += c
  764. if escaping:
  765. raise BadEscape
  766. if len(label) > 0:
  767. labels.append(idna_codec.encode(label))
  768. else:
  769. labels.append(b"")
  770. if (len(labels) == 0 or labels[-1] != b"") and origin is not None:
  771. labels.extend(list(origin.labels))
  772. return Name(labels)
  773. def is_all_ascii(text: str) -> bool:
  774. for c in text:
  775. if ord(c) > 0x7F:
  776. return False
  777. return True
  778. def from_text(
  779. text: bytes | str,
  780. origin: Name | None = root,
  781. idna_codec: IDNACodec | None = None,
  782. ) -> Name:
  783. """Convert text into a Name object.
  784. *text*, a ``bytes`` or ``str``, is the text to convert into a name.
  785. *origin*, a ``dns.name.Name``, specifies the origin to
  786. append to non-absolute names. The default is the root name.
  787. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  788. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  789. is used.
  790. Returns a ``dns.name.Name``.
  791. """
  792. if isinstance(text, str):
  793. if not is_all_ascii(text):
  794. # Some codepoint in the input text is > 127, so IDNA applies.
  795. return from_unicode(text, origin, idna_codec)
  796. # The input is all ASCII, so treat this like an ordinary non-IDNA
  797. # domain name. Note that "all ASCII" is about the input text,
  798. # not the codepoints in the domain name. E.g. if text has value
  799. #
  800. # r'\150\151\152\153\154\155\156\157\158\159'
  801. #
  802. # then it's still "all ASCII" even though the domain name has
  803. # codepoints > 127.
  804. text = text.encode("ascii")
  805. if not isinstance(text, bytes):
  806. raise ValueError("input to from_text() must be a string")
  807. if not (origin is None or isinstance(origin, Name)):
  808. raise ValueError("origin must be a Name or None")
  809. labels = []
  810. label = b""
  811. escaping = False
  812. edigits = 0
  813. total = 0
  814. if text == b"@":
  815. text = b""
  816. if text:
  817. if text == b".":
  818. return Name([b""])
  819. for c in text:
  820. byte_ = struct.pack("!B", c)
  821. if escaping:
  822. if edigits == 0:
  823. if byte_.isdigit():
  824. total = int(byte_)
  825. edigits += 1
  826. else:
  827. label += byte_
  828. escaping = False
  829. else:
  830. if not byte_.isdigit():
  831. raise BadEscape
  832. total *= 10
  833. total += int(byte_)
  834. edigits += 1
  835. if edigits == 3:
  836. escaping = False
  837. label += struct.pack("!B", total)
  838. elif byte_ == b".":
  839. if len(label) == 0:
  840. raise EmptyLabel
  841. labels.append(label)
  842. label = b""
  843. elif byte_ == b"\\":
  844. escaping = True
  845. edigits = 0
  846. total = 0
  847. else:
  848. label += byte_
  849. if escaping:
  850. raise BadEscape
  851. if len(label) > 0:
  852. labels.append(label)
  853. else:
  854. labels.append(b"")
  855. if (len(labels) == 0 or labels[-1] != b"") and origin is not None:
  856. labels.extend(list(origin.labels))
  857. return Name(labels)
  858. # we need 'dns.wire.Parser' quoted as dns.name and dns.wire depend on each other.
  859. def from_wire_parser(parser: "dns.wire.Parser") -> Name:
  860. """Convert possibly compressed wire format into a Name.
  861. *parser* is a dns.wire.Parser.
  862. Raises ``dns.name.BadPointer`` if a compression pointer did not
  863. point backwards in the message.
  864. Raises ``dns.name.BadLabelType`` if an invalid label type was encountered.
  865. Returns a ``dns.name.Name``
  866. """
  867. labels = []
  868. biggest_pointer = parser.current
  869. with parser.restore_furthest():
  870. count = parser.get_uint8()
  871. while count != 0:
  872. if count < 64:
  873. labels.append(parser.get_bytes(count))
  874. elif count >= 192:
  875. current = (count & 0x3F) * 256 + parser.get_uint8()
  876. if current >= biggest_pointer:
  877. raise BadPointer
  878. biggest_pointer = current
  879. parser.seek(current)
  880. else:
  881. raise BadLabelType
  882. count = parser.get_uint8()
  883. labels.append(b"")
  884. return Name(labels)
  885. def from_wire(message: bytes, current: int) -> Tuple[Name, int]:
  886. """Convert possibly compressed wire format into a Name.
  887. *message* is a ``bytes`` containing an entire DNS message in DNS
  888. wire form.
  889. *current*, an ``int``, is the offset of the beginning of the name
  890. from the start of the message
  891. Raises ``dns.name.BadPointer`` if a compression pointer did not
  892. point backwards in the message.
  893. Raises ``dns.name.BadLabelType`` if an invalid label type was encountered.
  894. Returns a ``(dns.name.Name, int)`` tuple consisting of the name
  895. that was read and the number of bytes of the wire format message
  896. which were consumed reading it.
  897. """
  898. if not isinstance(message, bytes):
  899. raise ValueError("input to from_wire() must be a byte string")
  900. parser = dns.wire.Parser(message, current)
  901. name = from_wire_parser(parser)
  902. return (name, parser.current - current)
  903. # RFC 4471 Support
  904. _MINIMAL_OCTET = b"\x00"
  905. _MINIMAL_OCTET_VALUE = ord(_MINIMAL_OCTET)
  906. _SUCCESSOR_PREFIX = Name([_MINIMAL_OCTET])
  907. _MAXIMAL_OCTET = b"\xff"
  908. _MAXIMAL_OCTET_VALUE = ord(_MAXIMAL_OCTET)
  909. _AT_SIGN_VALUE = ord("@")
  910. _LEFT_SQUARE_BRACKET_VALUE = ord("[")
  911. def _wire_length(labels):
  912. return functools.reduce(lambda v, x: v + len(x) + 1, labels, 0)
  913. def _pad_to_max_name(name):
  914. needed = 255 - _wire_length(name.labels)
  915. new_labels = []
  916. while needed > 64:
  917. new_labels.append(_MAXIMAL_OCTET * 63)
  918. needed -= 64
  919. if needed >= 2:
  920. new_labels.append(_MAXIMAL_OCTET * (needed - 1))
  921. # Note we're already maximal in the needed == 1 case as while we'd like
  922. # to add one more byte as a new label, we can't, as adding a new non-empty
  923. # label requires at least 2 bytes.
  924. new_labels = list(reversed(new_labels))
  925. new_labels.extend(name.labels)
  926. return Name(new_labels)
  927. def _pad_to_max_label(label, suffix_labels):
  928. length = len(label)
  929. # We have to subtract one here to account for the length byte of label.
  930. remaining = 255 - _wire_length(suffix_labels) - length - 1
  931. if remaining <= 0:
  932. # Shouldn't happen!
  933. return label
  934. needed = min(63 - length, remaining)
  935. return label + _MAXIMAL_OCTET * needed
  936. def _absolute_predecessor(name: Name, origin: Name, prefix_ok: bool) -> Name:
  937. # This is the RFC 4471 predecessor algorithm using the "absolute method" of section
  938. # 3.1.1.
  939. #
  940. # Our caller must ensure that the name and origin are absolute, and that name is a
  941. # subdomain of origin.
  942. if name == origin:
  943. return _pad_to_max_name(name)
  944. least_significant_label = name[0]
  945. if least_significant_label == _MINIMAL_OCTET:
  946. return name.parent()
  947. least_octet = least_significant_label[-1]
  948. suffix_labels = name.labels[1:]
  949. if least_octet == _MINIMAL_OCTET_VALUE:
  950. new_labels = [least_significant_label[:-1]]
  951. else:
  952. octets = bytearray(least_significant_label)
  953. octet = octets[-1]
  954. if octet == _LEFT_SQUARE_BRACKET_VALUE:
  955. octet = _AT_SIGN_VALUE
  956. else:
  957. octet -= 1
  958. octets[-1] = octet
  959. least_significant_label = bytes(octets)
  960. new_labels = [_pad_to_max_label(least_significant_label, suffix_labels)]
  961. new_labels.extend(suffix_labels)
  962. name = Name(new_labels)
  963. if prefix_ok:
  964. return _pad_to_max_name(name)
  965. else:
  966. return name
  967. def _absolute_successor(name: Name, origin: Name, prefix_ok: bool) -> Name:
  968. # This is the RFC 4471 successor algorithm using the "absolute method" of section
  969. # 3.1.2.
  970. #
  971. # Our caller must ensure that the name and origin are absolute, and that name is a
  972. # subdomain of origin.
  973. if prefix_ok:
  974. # Try prefixing \000 as new label
  975. try:
  976. return _SUCCESSOR_PREFIX.concatenate(name)
  977. except NameTooLong:
  978. pass
  979. while name != origin:
  980. # Try extending the least significant label.
  981. least_significant_label = name[0]
  982. if len(least_significant_label) < 63:
  983. # We may be able to extend the least label with a minimal additional byte.
  984. # This is only "may" because we could have a maximal length name even though
  985. # the least significant label isn't maximally long.
  986. new_labels = [least_significant_label + _MINIMAL_OCTET]
  987. new_labels.extend(name.labels[1:])
  988. try:
  989. return dns.name.Name(new_labels)
  990. except dns.name.NameTooLong:
  991. pass
  992. # We can't extend the label either, so we'll try to increment the least
  993. # signficant non-maximal byte in it.
  994. octets = bytearray(least_significant_label)
  995. # We do this reversed iteration with an explicit indexing variable because
  996. # if we find something to increment, we're going to want to truncate everything
  997. # to the right of it.
  998. for i in range(len(octets) - 1, -1, -1):
  999. octet = octets[i]
  1000. if octet == _MAXIMAL_OCTET_VALUE:
  1001. # We can't increment this, so keep looking.
  1002. continue
  1003. # Finally, something we can increment. We have to apply a special rule for
  1004. # incrementing "@", sending it to "[", because RFC 4034 6.1 says that when
  1005. # comparing names, uppercase letters compare as if they were their
  1006. # lower-case equivalents. If we increment "@" to "A", then it would compare
  1007. # as "a", which is after "[", "\", "]", "^", "_", and "`", so we would have
  1008. # skipped the most minimal successor, namely "[".
  1009. if octet == _AT_SIGN_VALUE:
  1010. octet = _LEFT_SQUARE_BRACKET_VALUE
  1011. else:
  1012. octet += 1
  1013. octets[i] = octet
  1014. # We can now truncate all of the maximal values we skipped (if any)
  1015. new_labels = [bytes(octets[: i + 1])]
  1016. new_labels.extend(name.labels[1:])
  1017. # We haven't changed the length of the name, so the Name constructor will
  1018. # always work.
  1019. return Name(new_labels)
  1020. # We couldn't increment, so chop off the least significant label and try
  1021. # again.
  1022. name = name.parent()
  1023. # We couldn't increment at all, so return the origin, as wrapping around is the
  1024. # DNSSEC way.
  1025. return origin
  1026. def _handle_relativity_and_call(
  1027. function: Callable[[Name, Name, bool], Name],
  1028. name: Name,
  1029. origin: Name,
  1030. prefix_ok: bool,
  1031. ) -> Name:
  1032. # Make "name" absolute if needed, ensure that the origin is absolute,
  1033. # call function(), and then relativize the result if needed.
  1034. if not origin.is_absolute():
  1035. raise NeedAbsoluteNameOrOrigin
  1036. relative = not name.is_absolute()
  1037. if relative:
  1038. name = name.derelativize(origin)
  1039. elif not name.is_subdomain(origin):
  1040. raise NeedSubdomainOfOrigin
  1041. result_name = function(name, origin, prefix_ok)
  1042. if relative:
  1043. result_name = result_name.relativize(origin)
  1044. return result_name