name.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. """
  18. import copy
  19. import struct
  20. import encodings.idna # type: ignore
  21. try:
  22. import idna # type: ignore
  23. have_idna_2008 = True
  24. except ImportError: # pragma: no cover
  25. have_idna_2008 = False
  26. import dns.wire
  27. import dns.exception
  28. import dns.immutable
  29. # fullcompare() result values
  30. #: The compared names have no relationship to each other.
  31. NAMERELN_NONE = 0
  32. #: the first name is a superdomain of the second.
  33. NAMERELN_SUPERDOMAIN = 1
  34. #: The first name is a subdomain of the second.
  35. NAMERELN_SUBDOMAIN = 2
  36. #: The compared names are equal.
  37. NAMERELN_EQUAL = 3
  38. #: The compared names have a common ancestor.
  39. NAMERELN_COMMONANCESTOR = 4
  40. class EmptyLabel(dns.exception.SyntaxError):
  41. """A DNS label is empty."""
  42. class BadEscape(dns.exception.SyntaxError):
  43. """An escaped code in a text format of DNS name is invalid."""
  44. class BadPointer(dns.exception.FormError):
  45. """A DNS compression pointer points forward instead of backward."""
  46. class BadLabelType(dns.exception.FormError):
  47. """The label type in DNS name wire format is unknown."""
  48. class NeedAbsoluteNameOrOrigin(dns.exception.DNSException):
  49. """An attempt was made to convert a non-absolute name to
  50. wire when there was also a non-absolute (or missing) origin."""
  51. class NameTooLong(dns.exception.FormError):
  52. """A DNS name is > 255 octets long."""
  53. class LabelTooLong(dns.exception.SyntaxError):
  54. """A DNS label is > 63 octets long."""
  55. class AbsoluteConcatenation(dns.exception.DNSException):
  56. """An attempt was made to append anything other than the
  57. empty name to an absolute DNS name."""
  58. class NoParent(dns.exception.DNSException):
  59. """An attempt was made to get the parent of the root name
  60. or the empty name."""
  61. class NoIDNA2008(dns.exception.DNSException):
  62. """IDNA 2008 processing was requested but the idna module is not
  63. available."""
  64. class IDNAException(dns.exception.DNSException):
  65. """IDNA processing raised an exception."""
  66. supp_kwargs = {'idna_exception'}
  67. fmt = "IDNA processing exception: {idna_exception}"
  68. class IDNACodec:
  69. """Abstract base class for IDNA encoder/decoders."""
  70. def __init__(self):
  71. pass
  72. def is_idna(self, label):
  73. return label.lower().startswith(b'xn--')
  74. def encode(self, label):
  75. raise NotImplementedError # pragma: no cover
  76. def decode(self, label):
  77. # We do not apply any IDNA policy on decode.
  78. if self.is_idna(label):
  79. try:
  80. label = label[4:].decode('punycode')
  81. except Exception as e:
  82. raise IDNAException(idna_exception=e)
  83. return _escapify(label)
  84. class IDNA2003Codec(IDNACodec):
  85. """IDNA 2003 encoder/decoder."""
  86. def __init__(self, strict_decode=False):
  87. """Initialize the IDNA 2003 encoder/decoder.
  88. *strict_decode* is a ``bool``. If `True`, then IDNA2003 checking
  89. is done when decoding. This can cause failures if the name
  90. was encoded with IDNA2008. The default is `False`.
  91. """
  92. super().__init__()
  93. self.strict_decode = strict_decode
  94. def encode(self, label):
  95. """Encode *label*."""
  96. if label == '':
  97. return b''
  98. try:
  99. return encodings.idna.ToASCII(label)
  100. except UnicodeError:
  101. raise LabelTooLong
  102. def decode(self, label):
  103. """Decode *label*."""
  104. if not self.strict_decode:
  105. return super().decode(label)
  106. if label == b'':
  107. return ''
  108. try:
  109. return _escapify(encodings.idna.ToUnicode(label))
  110. except Exception as e:
  111. raise IDNAException(idna_exception=e)
  112. class IDNA2008Codec(IDNACodec):
  113. """IDNA 2008 encoder/decoder.
  114. """
  115. def __init__(self, uts_46=False, transitional=False,
  116. allow_pure_ascii=False, strict_decode=False):
  117. """Initialize the IDNA 2008 encoder/decoder.
  118. *uts_46* is a ``bool``. If True, apply Unicode IDNA
  119. compatibility processing as described in Unicode Technical
  120. Standard #46 (http://unicode.org/reports/tr46/).
  121. If False, do not apply the mapping. The default is False.
  122. *transitional* is a ``bool``: If True, use the
  123. "transitional" mode described in Unicode Technical Standard
  124. #46. The default is False.
  125. *allow_pure_ascii* is a ``bool``. If True, then a label which
  126. consists of only ASCII characters is allowed. This is less
  127. strict than regular IDNA 2008, but is also necessary for mixed
  128. names, e.g. a name with starting with "_sip._tcp." and ending
  129. in an IDN suffix which would otherwise be disallowed. The
  130. default is False.
  131. *strict_decode* is a ``bool``: If True, then IDNA2008 checking
  132. is done when decoding. This can cause failures if the name
  133. was encoded with IDNA2003. The default is False.
  134. """
  135. super().__init__()
  136. self.uts_46 = uts_46
  137. self.transitional = transitional
  138. self.allow_pure_ascii = allow_pure_ascii
  139. self.strict_decode = strict_decode
  140. def encode(self, label):
  141. if label == '':
  142. return b''
  143. if self.allow_pure_ascii and is_all_ascii(label):
  144. encoded = label.encode('ascii')
  145. if len(encoded) > 63:
  146. raise LabelTooLong
  147. return encoded
  148. if not have_idna_2008:
  149. raise NoIDNA2008
  150. try:
  151. if self.uts_46:
  152. label = idna.uts46_remap(label, False, self.transitional)
  153. return idna.alabel(label)
  154. except idna.IDNAError as e:
  155. if e.args[0] == 'Label too long':
  156. raise LabelTooLong
  157. else:
  158. raise IDNAException(idna_exception=e)
  159. def decode(self, label):
  160. if not self.strict_decode:
  161. return super().decode(label)
  162. if label == b'':
  163. return ''
  164. if not have_idna_2008:
  165. raise NoIDNA2008
  166. try:
  167. ulabel = idna.ulabel(label)
  168. if self.uts_46:
  169. ulabel = idna.uts46_remap(ulabel, False, self.transitional)
  170. return _escapify(ulabel)
  171. except (idna.IDNAError, UnicodeError) as e:
  172. raise IDNAException(idna_exception=e)
  173. _escaped = b'"().;\\@$'
  174. _escaped_text = '"().;\\@$'
  175. IDNA_2003_Practical = IDNA2003Codec(False)
  176. IDNA_2003_Strict = IDNA2003Codec(True)
  177. IDNA_2003 = IDNA_2003_Practical
  178. IDNA_2008_Practical = IDNA2008Codec(True, False, True, False)
  179. IDNA_2008_UTS_46 = IDNA2008Codec(True, False, False, False)
  180. IDNA_2008_Strict = IDNA2008Codec(False, False, False, True)
  181. IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False)
  182. IDNA_2008 = IDNA_2008_Practical
  183. def _escapify(label):
  184. """Escape the characters in label which need it.
  185. @returns: the escaped string
  186. @rtype: string"""
  187. if isinstance(label, bytes):
  188. # Ordinary DNS label mode. Escape special characters and values
  189. # < 0x20 or > 0x7f.
  190. text = ''
  191. for c in label:
  192. if c in _escaped:
  193. text += '\\' + chr(c)
  194. elif c > 0x20 and c < 0x7F:
  195. text += chr(c)
  196. else:
  197. text += '\\%03d' % c
  198. return text
  199. # Unicode label mode. Escape only special characters and values < 0x20
  200. text = ''
  201. for c in label:
  202. if c in _escaped_text:
  203. text += '\\' + c
  204. elif c <= '\x20':
  205. text += '\\%03d' % ord(c)
  206. else:
  207. text += c
  208. return text
  209. def _validate_labels(labels):
  210. """Check for empty labels in the middle of a label sequence,
  211. labels that are too long, and for too many labels.
  212. Raises ``dns.name.NameTooLong`` if the name as a whole is too long.
  213. Raises ``dns.name.EmptyLabel`` if a label is empty (i.e. the root
  214. label) and appears in a position other than the end of the label
  215. sequence
  216. """
  217. l = len(labels)
  218. total = 0
  219. i = -1
  220. j = 0
  221. for label in labels:
  222. ll = len(label)
  223. total += ll + 1
  224. if ll > 63:
  225. raise LabelTooLong
  226. if i < 0 and label == b'':
  227. i = j
  228. j += 1
  229. if total > 255:
  230. raise NameTooLong
  231. if i >= 0 and i != l - 1:
  232. raise EmptyLabel
  233. def _maybe_convert_to_binary(label):
  234. """If label is ``str``, convert it to ``bytes``. If it is already
  235. ``bytes`` just return it.
  236. """
  237. if isinstance(label, bytes):
  238. return label
  239. if isinstance(label, str):
  240. return label.encode()
  241. raise ValueError # pragma: no cover
  242. @dns.immutable.immutable
  243. class Name:
  244. """A DNS name.
  245. The dns.name.Name class represents a DNS name as a tuple of
  246. labels. Each label is a ``bytes`` in DNS wire format. Instances
  247. of the class are immutable.
  248. """
  249. __slots__ = ['labels']
  250. def __init__(self, labels):
  251. """*labels* is any iterable whose values are ``str`` or ``bytes``.
  252. """
  253. labels = [_maybe_convert_to_binary(x) for x in labels]
  254. self.labels = tuple(labels)
  255. _validate_labels(self.labels)
  256. def __copy__(self):
  257. return Name(self.labels)
  258. def __deepcopy__(self, memo):
  259. return Name(copy.deepcopy(self.labels, memo))
  260. def __getstate__(self):
  261. # Names can be pickled
  262. return {'labels': self.labels}
  263. def __setstate__(self, state):
  264. super().__setattr__('labels', state['labels'])
  265. _validate_labels(self.labels)
  266. def is_absolute(self):
  267. """Is the most significant label of this name the root label?
  268. Returns a ``bool``.
  269. """
  270. return len(self.labels) > 0 and self.labels[-1] == b''
  271. def is_wild(self):
  272. """Is this name wild? (I.e. Is the least significant label '*'?)
  273. Returns a ``bool``.
  274. """
  275. return len(self.labels) > 0 and self.labels[0] == b'*'
  276. def __hash__(self):
  277. """Return a case-insensitive hash of the name.
  278. Returns an ``int``.
  279. """
  280. h = 0
  281. for label in self.labels:
  282. for c in label.lower():
  283. h += (h << 3) + c
  284. return h
  285. def fullcompare(self, other):
  286. """Compare two names, returning a 3-tuple
  287. ``(relation, order, nlabels)``.
  288. *relation* describes the relation ship between the names,
  289. and is one of: ``dns.name.NAMERELN_NONE``,
  290. ``dns.name.NAMERELN_SUPERDOMAIN``, ``dns.name.NAMERELN_SUBDOMAIN``,
  291. ``dns.name.NAMERELN_EQUAL``, or ``dns.name.NAMERELN_COMMONANCESTOR``.
  292. *order* is < 0 if *self* < *other*, > 0 if *self* > *other*, and ==
  293. 0 if *self* == *other*. A relative name is always less than an
  294. absolute name. If both names have the same relativity, then
  295. the DNSSEC order relation is used to order them.
  296. *nlabels* is the number of significant labels that the two names
  297. have in common.
  298. Here are some examples. Names ending in "." are absolute names,
  299. those not ending in "." are relative names.
  300. ============= ============= =========== ===== =======
  301. self other relation order nlabels
  302. ============= ============= =========== ===== =======
  303. www.example. www.example. equal 0 3
  304. www.example. example. subdomain > 0 2
  305. example. www.example. superdomain < 0 2
  306. example1.com. example2.com. common anc. < 0 2
  307. example1 example2. none < 0 0
  308. example1. example2 none > 0 0
  309. ============= ============= =========== ===== =======
  310. """
  311. sabs = self.is_absolute()
  312. oabs = other.is_absolute()
  313. if sabs != oabs:
  314. if sabs:
  315. return (NAMERELN_NONE, 1, 0)
  316. else:
  317. return (NAMERELN_NONE, -1, 0)
  318. l1 = len(self.labels)
  319. l2 = len(other.labels)
  320. ldiff = l1 - l2
  321. if ldiff < 0:
  322. l = l1
  323. else:
  324. l = l2
  325. order = 0
  326. nlabels = 0
  327. namereln = NAMERELN_NONE
  328. while l > 0:
  329. l -= 1
  330. l1 -= 1
  331. l2 -= 1
  332. label1 = self.labels[l1].lower()
  333. label2 = other.labels[l2].lower()
  334. if label1 < label2:
  335. order = -1
  336. if nlabels > 0:
  337. namereln = NAMERELN_COMMONANCESTOR
  338. return (namereln, order, nlabels)
  339. elif label1 > label2:
  340. order = 1
  341. if nlabels > 0:
  342. namereln = NAMERELN_COMMONANCESTOR
  343. return (namereln, order, nlabels)
  344. nlabels += 1
  345. order = ldiff
  346. if ldiff < 0:
  347. namereln = NAMERELN_SUPERDOMAIN
  348. elif ldiff > 0:
  349. namereln = NAMERELN_SUBDOMAIN
  350. else:
  351. namereln = NAMERELN_EQUAL
  352. return (namereln, order, nlabels)
  353. def is_subdomain(self, other):
  354. """Is self a subdomain of other?
  355. Note that the notion of subdomain includes equality, e.g.
  356. "dnpython.org" is a subdomain of itself.
  357. Returns a ``bool``.
  358. """
  359. (nr, _, _) = self.fullcompare(other)
  360. if nr == NAMERELN_SUBDOMAIN or nr == NAMERELN_EQUAL:
  361. return True
  362. return False
  363. def is_superdomain(self, other):
  364. """Is self a superdomain of other?
  365. Note that the notion of superdomain includes equality, e.g.
  366. "dnpython.org" is a superdomain of itself.
  367. Returns a ``bool``.
  368. """
  369. (nr, _, _) = self.fullcompare(other)
  370. if nr == NAMERELN_SUPERDOMAIN or nr == NAMERELN_EQUAL:
  371. return True
  372. return False
  373. def canonicalize(self):
  374. """Return a name which is equal to the current name, but is in
  375. DNSSEC canonical form.
  376. """
  377. return Name([x.lower() for x in self.labels])
  378. def __eq__(self, other):
  379. if isinstance(other, Name):
  380. return self.fullcompare(other)[1] == 0
  381. else:
  382. return False
  383. def __ne__(self, other):
  384. if isinstance(other, Name):
  385. return self.fullcompare(other)[1] != 0
  386. else:
  387. return True
  388. def __lt__(self, other):
  389. if isinstance(other, Name):
  390. return self.fullcompare(other)[1] < 0
  391. else:
  392. return NotImplemented
  393. def __le__(self, other):
  394. if isinstance(other, Name):
  395. return self.fullcompare(other)[1] <= 0
  396. else:
  397. return NotImplemented
  398. def __ge__(self, other):
  399. if isinstance(other, Name):
  400. return self.fullcompare(other)[1] >= 0
  401. else:
  402. return NotImplemented
  403. def __gt__(self, other):
  404. if isinstance(other, Name):
  405. return self.fullcompare(other)[1] > 0
  406. else:
  407. return NotImplemented
  408. def __repr__(self):
  409. return '<DNS name ' + self.__str__() + '>'
  410. def __str__(self):
  411. return self.to_text(False)
  412. def to_text(self, omit_final_dot=False):
  413. """Convert name to DNS text format.
  414. *omit_final_dot* is a ``bool``. If True, don't emit the final
  415. dot (denoting the root label) for absolute names. The default
  416. is False.
  417. Returns a ``str``.
  418. """
  419. if len(self.labels) == 0:
  420. return '@'
  421. if len(self.labels) == 1 and self.labels[0] == b'':
  422. return '.'
  423. if omit_final_dot and self.is_absolute():
  424. l = self.labels[:-1]
  425. else:
  426. l = self.labels
  427. s = '.'.join(map(_escapify, l))
  428. return s
  429. def to_unicode(self, omit_final_dot=False, idna_codec=None):
  430. """Convert name to Unicode text format.
  431. IDN ACE labels are converted to Unicode.
  432. *omit_final_dot* is a ``bool``. If True, don't emit the final
  433. dot (denoting the root label) for absolute names. The default
  434. is False.
  435. *idna_codec* specifies the IDNA encoder/decoder. If None, the
  436. dns.name.IDNA_2003_Practical encoder/decoder is used.
  437. The IDNA_2003_Practical decoder does
  438. not impose any policy, it just decodes punycode, so if you
  439. don't want checking for compliance, you can use this decoder
  440. for IDNA2008 as well.
  441. Returns a ``str``.
  442. """
  443. if len(self.labels) == 0:
  444. return '@'
  445. if len(self.labels) == 1 and self.labels[0] == b'':
  446. return '.'
  447. if omit_final_dot and self.is_absolute():
  448. l = self.labels[:-1]
  449. else:
  450. l = self.labels
  451. if idna_codec is None:
  452. idna_codec = IDNA_2003_Practical
  453. return '.'.join([idna_codec.decode(x) for x in l])
  454. def to_digestable(self, origin=None):
  455. """Convert name to a format suitable for digesting in hashes.
  456. The name is canonicalized and converted to uncompressed wire
  457. format. All names in wire format are absolute. If the name
  458. is a relative name, then an origin must be supplied.
  459. *origin* is a ``dns.name.Name`` or ``None``. If the name is
  460. relative and origin is not ``None``, then origin will be appended
  461. to the name.
  462. Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is
  463. relative and no origin was provided.
  464. Returns a ``bytes``.
  465. """
  466. return self.to_wire(origin=origin, canonicalize=True)
  467. def to_wire(self, file=None, compress=None, origin=None,
  468. canonicalize=False):
  469. """Convert name to wire format, possibly compressing it.
  470. *file* is the file where the name is emitted (typically an
  471. io.BytesIO file). If ``None`` (the default), a ``bytes``
  472. containing the wire name will be returned.
  473. *compress*, a ``dict``, is the compression table to use. If
  474. ``None`` (the default), names will not be compressed. Note that
  475. the compression code assumes that compression offset 0 is the
  476. start of *file*, and thus compression will not be correct
  477. if this is not the case.
  478. *origin* is a ``dns.name.Name`` or ``None``. If the name is
  479. relative and origin is not ``None``, then *origin* will be appended
  480. to it.
  481. *canonicalize*, a ``bool``, indicates whether the name should
  482. be canonicalized; that is, converted to a format suitable for
  483. digesting in hashes.
  484. Raises ``dns.name.NeedAbsoluteNameOrOrigin`` if the name is
  485. relative and no origin was provided.
  486. Returns a ``bytes`` or ``None``.
  487. """
  488. if file is None:
  489. out = bytearray()
  490. for label in self.labels:
  491. out.append(len(label))
  492. if canonicalize:
  493. out += label.lower()
  494. else:
  495. out += label
  496. if not self.is_absolute():
  497. if origin is None or not origin.is_absolute():
  498. raise NeedAbsoluteNameOrOrigin
  499. for label in origin.labels:
  500. out.append(len(label))
  501. if canonicalize:
  502. out += label.lower()
  503. else:
  504. out += label
  505. return bytes(out)
  506. if not self.is_absolute():
  507. if origin is None or not origin.is_absolute():
  508. raise NeedAbsoluteNameOrOrigin
  509. labels = list(self.labels)
  510. labels.extend(list(origin.labels))
  511. else:
  512. labels = self.labels
  513. i = 0
  514. for label in labels:
  515. n = Name(labels[i:])
  516. i += 1
  517. if compress is not None:
  518. pos = compress.get(n)
  519. else:
  520. pos = None
  521. if pos is not None:
  522. value = 0xc000 + pos
  523. s = struct.pack('!H', value)
  524. file.write(s)
  525. break
  526. else:
  527. if compress is not None and len(n) > 1:
  528. pos = file.tell()
  529. if pos <= 0x3fff:
  530. compress[n] = pos
  531. l = len(label)
  532. file.write(struct.pack('!B', l))
  533. if l > 0:
  534. if canonicalize:
  535. file.write(label.lower())
  536. else:
  537. file.write(label)
  538. def __len__(self):
  539. """The length of the name (in labels).
  540. Returns an ``int``.
  541. """
  542. return len(self.labels)
  543. def __getitem__(self, index):
  544. return self.labels[index]
  545. def __add__(self, other):
  546. return self.concatenate(other)
  547. def __sub__(self, other):
  548. return self.relativize(other)
  549. def split(self, depth):
  550. """Split a name into a prefix and suffix names at the specified depth.
  551. *depth* is an ``int`` specifying the number of labels in the suffix
  552. Raises ``ValueError`` if *depth* was not >= 0 and <= the length of the
  553. name.
  554. Returns the tuple ``(prefix, suffix)``.
  555. """
  556. l = len(self.labels)
  557. if depth == 0:
  558. return (self, dns.name.empty)
  559. elif depth == l:
  560. return (dns.name.empty, self)
  561. elif depth < 0 or depth > l:
  562. raise ValueError(
  563. 'depth must be >= 0 and <= the length of the name')
  564. return (Name(self[: -depth]), Name(self[-depth:]))
  565. def concatenate(self, other):
  566. """Return a new name which is the concatenation of self and other.
  567. Raises ``dns.name.AbsoluteConcatenation`` if the name is
  568. absolute and *other* is not the empty name.
  569. Returns a ``dns.name.Name``.
  570. """
  571. if self.is_absolute() and len(other) > 0:
  572. raise AbsoluteConcatenation
  573. labels = list(self.labels)
  574. labels.extend(list(other.labels))
  575. return Name(labels)
  576. def relativize(self, origin):
  577. """If the name is a subdomain of *origin*, return a new name which is
  578. the name relative to origin. Otherwise return the name.
  579. For example, relativizing ``www.dnspython.org.`` to origin
  580. ``dnspython.org.`` returns the name ``www``. Relativizing ``example.``
  581. to origin ``dnspython.org.`` returns ``example.``.
  582. Returns a ``dns.name.Name``.
  583. """
  584. if origin is not None and self.is_subdomain(origin):
  585. return Name(self[: -len(origin)])
  586. else:
  587. return self
  588. def derelativize(self, origin):
  589. """If the name is a relative name, return a new name which is the
  590. concatenation of the name and origin. Otherwise return the name.
  591. For example, derelativizing ``www`` to origin ``dnspython.org.``
  592. returns the name ``www.dnspython.org.``. Derelativizing ``example.``
  593. to origin ``dnspython.org.`` returns ``example.``.
  594. Returns a ``dns.name.Name``.
  595. """
  596. if not self.is_absolute():
  597. return self.concatenate(origin)
  598. else:
  599. return self
  600. def choose_relativity(self, origin=None, relativize=True):
  601. """Return a name with the relativity desired by the caller.
  602. If *origin* is ``None``, then the name is returned.
  603. Otherwise, if *relativize* is ``True`` the name is
  604. relativized, and if *relativize* is ``False`` the name is
  605. derelativized.
  606. Returns a ``dns.name.Name``.
  607. """
  608. if origin:
  609. if relativize:
  610. return self.relativize(origin)
  611. else:
  612. return self.derelativize(origin)
  613. else:
  614. return self
  615. def parent(self):
  616. """Return the parent of the name.
  617. For example, the parent of ``www.dnspython.org.`` is ``dnspython.org``.
  618. Raises ``dns.name.NoParent`` if the name is either the root name or the
  619. empty name, and thus has no parent.
  620. Returns a ``dns.name.Name``.
  621. """
  622. if self == root or self == empty:
  623. raise NoParent
  624. return Name(self.labels[1:])
  625. #: The root name, '.'
  626. root = Name([b''])
  627. #: The empty name.
  628. empty = Name([])
  629. def from_unicode(text, origin=root, idna_codec=None):
  630. """Convert unicode text into a Name object.
  631. Labels are encoded in IDN ACE form according to rules specified by
  632. the IDNA codec.
  633. *text*, a ``str``, is the text to convert into a name.
  634. *origin*, a ``dns.name.Name``, specifies the origin to
  635. append to non-absolute names. The default is the root name.
  636. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  637. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  638. is used.
  639. Returns a ``dns.name.Name``.
  640. """
  641. if not isinstance(text, str):
  642. raise ValueError("input to from_unicode() must be a unicode string")
  643. if not (origin is None or isinstance(origin, Name)):
  644. raise ValueError("origin must be a Name or None")
  645. labels = []
  646. label = ''
  647. escaping = False
  648. edigits = 0
  649. total = 0
  650. if idna_codec is None:
  651. idna_codec = IDNA_2003
  652. if text == '@':
  653. text = ''
  654. if text:
  655. if text in ['.', '\u3002', '\uff0e', '\uff61']:
  656. return Name([b'']) # no Unicode "u" on this constant!
  657. for c in text:
  658. if escaping:
  659. if edigits == 0:
  660. if c.isdigit():
  661. total = int(c)
  662. edigits += 1
  663. else:
  664. label += c
  665. escaping = False
  666. else:
  667. if not c.isdigit():
  668. raise BadEscape
  669. total *= 10
  670. total += int(c)
  671. edigits += 1
  672. if edigits == 3:
  673. escaping = False
  674. label += chr(total)
  675. elif c in ['.', '\u3002', '\uff0e', '\uff61']:
  676. if len(label) == 0:
  677. raise EmptyLabel
  678. labels.append(idna_codec.encode(label))
  679. label = ''
  680. elif c == '\\':
  681. escaping = True
  682. edigits = 0
  683. total = 0
  684. else:
  685. label += c
  686. if escaping:
  687. raise BadEscape
  688. if len(label) > 0:
  689. labels.append(idna_codec.encode(label))
  690. else:
  691. labels.append(b'')
  692. if (len(labels) == 0 or labels[-1] != b'') and origin is not None:
  693. labels.extend(list(origin.labels))
  694. return Name(labels)
  695. def is_all_ascii(text):
  696. for c in text:
  697. if ord(c) > 0x7f:
  698. return False
  699. return True
  700. def from_text(text, origin=root, idna_codec=None):
  701. """Convert text into a Name object.
  702. *text*, a ``str``, is the text to convert into a name.
  703. *origin*, a ``dns.name.Name``, specifies the origin to
  704. append to non-absolute names. The default is the root name.
  705. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  706. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  707. is used.
  708. Returns a ``dns.name.Name``.
  709. """
  710. if isinstance(text, str):
  711. if not is_all_ascii(text):
  712. # Some codepoint in the input text is > 127, so IDNA applies.
  713. return from_unicode(text, origin, idna_codec)
  714. # The input is all ASCII, so treat this like an ordinary non-IDNA
  715. # domain name. Note that "all ASCII" is about the input text,
  716. # not the codepoints in the domain name. E.g. if text has value
  717. #
  718. # r'\150\151\152\153\154\155\156\157\158\159'
  719. #
  720. # then it's still "all ASCII" even though the domain name has
  721. # codepoints > 127.
  722. text = text.encode('ascii')
  723. if not isinstance(text, bytes):
  724. raise ValueError("input to from_text() must be a string")
  725. if not (origin is None or isinstance(origin, Name)):
  726. raise ValueError("origin must be a Name or None")
  727. labels = []
  728. label = b''
  729. escaping = False
  730. edigits = 0
  731. total = 0
  732. if text == b'@':
  733. text = b''
  734. if text:
  735. if text == b'.':
  736. return Name([b''])
  737. for c in text:
  738. byte_ = struct.pack('!B', c)
  739. if escaping:
  740. if edigits == 0:
  741. if byte_.isdigit():
  742. total = int(byte_)
  743. edigits += 1
  744. else:
  745. label += byte_
  746. escaping = False
  747. else:
  748. if not byte_.isdigit():
  749. raise BadEscape
  750. total *= 10
  751. total += int(byte_)
  752. edigits += 1
  753. if edigits == 3:
  754. escaping = False
  755. label += struct.pack('!B', total)
  756. elif byte_ == b'.':
  757. if len(label) == 0:
  758. raise EmptyLabel
  759. labels.append(label)
  760. label = b''
  761. elif byte_ == b'\\':
  762. escaping = True
  763. edigits = 0
  764. total = 0
  765. else:
  766. label += byte_
  767. if escaping:
  768. raise BadEscape
  769. if len(label) > 0:
  770. labels.append(label)
  771. else:
  772. labels.append(b'')
  773. if (len(labels) == 0 or labels[-1] != b'') and origin is not None:
  774. labels.extend(list(origin.labels))
  775. return Name(labels)
  776. def from_wire_parser(parser):
  777. """Convert possibly compressed wire format into a Name.
  778. *parser* is a dns.wire.Parser.
  779. Raises ``dns.name.BadPointer`` if a compression pointer did not
  780. point backwards in the message.
  781. Raises ``dns.name.BadLabelType`` if an invalid label type was encountered.
  782. Returns a ``dns.name.Name``
  783. """
  784. labels = []
  785. biggest_pointer = parser.current
  786. with parser.restore_furthest():
  787. count = parser.get_uint8()
  788. while count != 0:
  789. if count < 64:
  790. labels.append(parser.get_bytes(count))
  791. elif count >= 192:
  792. current = (count & 0x3f) * 256 + parser.get_uint8()
  793. if current >= biggest_pointer:
  794. raise BadPointer
  795. biggest_pointer = current
  796. parser.seek(current)
  797. else:
  798. raise BadLabelType
  799. count = parser.get_uint8()
  800. labels.append(b'')
  801. return Name(labels)
  802. def from_wire(message, current):
  803. """Convert possibly compressed wire format into a Name.
  804. *message* is a ``bytes`` containing an entire DNS message in DNS
  805. wire form.
  806. *current*, an ``int``, is the offset of the beginning of the name
  807. from the start of the message
  808. Raises ``dns.name.BadPointer`` if a compression pointer did not
  809. point backwards in the message.
  810. Raises ``dns.name.BadLabelType`` if an invalid label type was encountered.
  811. Returns a ``(dns.name.Name, int)`` tuple consisting of the name
  812. that was read and the number of bytes of the wire format message
  813. which were consumed reading it.
  814. """
  815. if not isinstance(message, bytes):
  816. raise ValueError("input to from_wire() must be a byte string")
  817. parser = dns.wire.Parser(message, current)
  818. name = from_wire_parser(parser)
  819. return (name, parser.current - current)