Debian Codegraph @

dns/rdtypes/txtbase.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2006-2017 Nominum, Inc.
4 #
5 # Permission to use, copy, modify, and distribute this software and its
6 # documentation for any purpose with or without fee is hereby granted,
7 # provided that the above copyright notice and this permission notice
8 # appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18 """TXT-like base class."""
19
20 from typing import Any, Dict, Iterable, Tuple
21
22 import dns.exception
23 import dns.immutable
24 import dns.name
25 import dns.rdata
26 import dns.rdataclass
27 import dns.rdatatype
28 import dns.renderer
29 import dns.tokenizer
30
31
32 @dns.immutable.immutable
33 class TXTBase(dns.rdata.Rdata):
34 """Base class for rdata that is like a TXT record (see RFC 1035)."""
35
36 __slots__ = ["strings"]
37
38 def __init__(
39 self,
40 rdclass: dns.rdataclass.RdataClass,
41 rdtype: dns.rdatatype.RdataType,
42 strings: Iterable[bytes | str],
43 ):
44 """Initialize a TXT-like rdata.
45
46 *rdclass*, an ``int`` is the rdataclass of the Rdata.
47
48 *rdtype*, an ``int`` is the rdatatype of the Rdata.
49
50 *strings*, a tuple of ``bytes``
51 """
52 super().__init__(rdclass, rdtype)
53 self.strings: Tuple[bytes] = self._as_tuple(
54 strings, lambda x: self._as_bytes(x, True, 255)
55 )
56 if len(self.strings) == 0:
57 raise ValueError("the list of strings must not be empty")
58
59 def to_text(
60 self,
61 origin: dns.name.Name | None = None,
62 relativize: bool = True,
63 **kw: Dict[str, Any],
64 ) -> str:
65 txt = ""
66 prefix = ""
67 for s in self.strings:
68 txt += f'{prefix}"{dns.rdata._escapify(s)}"'
69 prefix = " "
70 return txt
71
72 @classmethod
73 def from_text(
74 cls,
75 rdclass: dns.rdataclass.RdataClass,
76 rdtype: dns.rdatatype.RdataType,
77 tok: dns.tokenizer.Tokenizer,
78 origin: dns.name.Name | None = None,
79 relativize: bool = True,
80 relativize_to: dns.name.Name | None = None,
81 ) -> dns.rdata.Rdata:
82 strings = []
83 for token in tok.get_remaining():
84 token = token.unescape_to_bytes()
85 # The 'if' below is always true in the current code, but we
86 # are leaving this check in in case things change some day.
87 if not (
88 token.is_quoted_string() or token.is_identifier()
89 ): # pragma: no cover
90 raise dns.exception.SyntaxError("expected a string")
91 if len(token.value) > 255:
92 raise dns.exception.SyntaxError("string too long")
93 strings.append(token.value)
94 if len(strings) == 0:
95 raise dns.exception.UnexpectedEnd
96 return cls(rdclass, rdtype, strings)
97
98 def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
99 for s in self.strings:
100 with dns.renderer.prefixed_length(file, 1):
101 file.write(s)
102
103 @classmethod
104 def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
105 strings = []
106 while parser.remaining() > 0:
107 s = parser.get_counted_bytes()
108 strings.append(s)
109 return cls(rdclass, rdtype, strings)