summaryrefslogtreecommitdiff
path: root/dns/wiredata.py
blob: a3fab7348514d1c98d323506d0923c9aba2b5569 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license

# Copyright (C) 2011,2017 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

"""DNS Wire Data Helper"""

import dns.exception


class WireData(bytes):
    # WireData is a binary type with stricter slicing

    def __getitem__(self, key):
        try:
            if isinstance(key, slice):
                # make sure we are not going outside of valid ranges,
                # do stricter control of boundaries than python does
                # by default

                for index in (key.start, key.stop):
                    if index is None:
                        continue
                    elif abs(index) > len(self):
                        raise dns.exception.FormError

                return WireData(super().__getitem__(key))
            return self.unwrap()[key]
        except IndexError:
            raise dns.exception.FormError

    def unwrap(self):
        return bytes(self)


def maybe_wrap(wire):
    if isinstance(wire, WireData):
        return wire
    elif isinstance(wire, bytes):
        return WireData(wire)
    elif isinstance(wire, str):
        return WireData(wire.encode())
    raise ValueError("unhandled type %s" % type(wire))