You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

994 lines
30 KiB

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