name.py 29 KB

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