1# Copyright (C) 2003-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
16import binascii
17
18import dns.exception
19import dns.rdata
20import dns.tokenizer
21
22
23class NSAP(dns.rdata.Rdata):
24
25    """NSAP record.
26
27    @ivar address: a NASP
28    @type address: string
29    @see: RFC 1706"""
30
31    __slots__ = ['address']
32
33    def __init__(self, rdclass, rdtype, address):
34        super(NSAP, self).__init__(rdclass, rdtype)
35        self.address = address
36
37    def to_text(self, origin=None, relativize=True, **kw):
38        return "0x%s" % binascii.hexlify(self.address).decode()
39
40    @classmethod
41    def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True):
42        address = tok.get_string()
43        tok.get_eol()
44        if address[0:2] != '0x':
45            raise dns.exception.SyntaxError('string does not start with 0x')
46        address = address[2:].replace('.', '')
47        if len(address) % 2 != 0:
48            raise dns.exception.SyntaxError('hexstring has odd length')
49        address = binascii.unhexlify(address.encode())
50        return cls(rdclass, rdtype, address)
51
52    def to_wire(self, file, compress=None, origin=None):
53        file.write(self.address)
54
55    @classmethod
56    def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin=None):
57        address = wire[current: current + rdlen].unwrap()
58        return cls(rdclass, rdtype, address)
59