Debian Codegraph @

dns/rdtypes/euibase.py

raw
1 # Copyright (C) 2015 Red Hat, Inc.
2 # Author: Petr Spacek <[email protected]>
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 RED HAT 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
17 import binascii
18
19 import dns.exception
20 import dns.immutable
21 import dns.rdata
22
23
24 @dns.immutable.immutable
25 class EUIBase(dns.rdata.Rdata):
26 """EUIxx record"""
27
28 # see: rfc7043.txt
29
30 __slots__ = ["eui"]
31 # redefine these in subclasses
32 byte_len = 0
33 text_len = 0
34 # byte_len = 6 # 0123456789ab (in hex)
35 # text_len = byte_len * 3 - 1 # 01-23-45-67-89-ab
36
37 def __init__(self, rdclass, rdtype, eui):
38 super().__init__(rdclass, rdtype)
39 self.eui = self._as_bytes(eui)
40 if len(self.eui) != self.byte_len:
41 raise dns.exception.FormError(
42 f"EUI{self.byte_len * 8} rdata has to have {self.byte_len} bytes"
43 )
44
45 def to_text(self, origin=None, relativize=True, **kw):
46 return dns.rdata._hexify(self.eui, chunksize=2, separator=b"-", **kw)
47
48 @classmethod
49 def from_text(
50 cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None
51 ):
52 text = tok.get_string()
53 if len(text) != cls.text_len:
54 raise dns.exception.SyntaxError(
55 f"Input text must have {cls.text_len} characters"
56 )
57 for i in range(2, cls.byte_len * 3 - 1, 3):
58 if text[i] != "-":
59 raise dns.exception.SyntaxError(f"Dash expected at position {i}")
60 text = text.replace("-", "")
61 try:
62 data = binascii.unhexlify(text.encode())
63 except (ValueError, TypeError) as ex:
64 raise dns.exception.SyntaxError(f"Hex decoding error: {str(ex)}")
65 return cls(rdclass, rdtype, data)
66
67 def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
68 file.write(self.eui)
69
70 @classmethod
71 def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
72 eui = parser.get_bytes(cls.byte_len)
73 return cls(rdclass, rdtype, eui)