xdrlib.py 5.77 KB
Newer Older
1 2 3 4 5 6 7
"""Implements (a subset of) Sun XDR -- eXternal Data Representation.

See: RFC 1014

"""

import struct
8
from io import BytesIO
9
from functools import wraps
10

11 12
__all__ = ["Error", "Packer", "Unpacker", "ConversionError"]

13
# exceptions
14
class Error(Exception):
15 16
    """Exception class for this module. Use:

17
    except xdrlib.Error as var:
18 19 20 21 22 23 24
        # var has the Error instance for the exception

    Public ivars:
        msg -- contains the message

    """
    def __init__(self, msg):
25
        self.msg = msg
26
    def __repr__(self):
27
        return repr(self.msg)
28
    def __str__(self):
29
        return str(self.msg)
30 31 32 33 34


class ConversionError(Error):
    pass

35 36 37 38 39 40 41 42 43 44
def raise_conversion_error(function):
    """ Wrap any raised struct.errors in a ConversionError. """

    @wraps(function)
    def result(self, value):
        try:
            return function(self, value)
        except struct.error as e:
            raise ConversionError(e.args[0]) from None
    return result
45

46

47 48 49 50
class Packer:
    """Pack various data representations into a buffer."""

    def __init__(self):
51
        self.reset()
52 53

    def reset(self):
54
        self.__buf = BytesIO()
55 56

    def get_buffer(self):
57
        return self.__buf.getvalue()
58 59 60
    # backwards compatibility
    get_buf = get_buffer

61
    @raise_conversion_error
62
    def pack_uint(self, x):
63
        self.__buf.write(struct.pack('>L', x))
64

65
    @raise_conversion_error
66 67 68
    def pack_int(self, x):
        self.__buf.write(struct.pack('>l', x))

69 70 71
    pack_enum = pack_int

    def pack_bool(self, x):
72 73
        if x: self.__buf.write(b'\0\0\0\1')
        else: self.__buf.write(b'\0\0\0\0')
74 75

    def pack_uhyper(self, x):
76 77 78 79 80 81 82 83
        try:
            self.pack_uint(x>>32 & 0xffffffff)
        except (TypeError, struct.error) as e:
            raise ConversionError(e.args[0]) from None
        try:
            self.pack_uint(x & 0xffffffff)
        except (TypeError, struct.error) as e:
            raise ConversionError(e.args[0]) from None
84 85 86

    pack_hyper = pack_uhyper

87
    @raise_conversion_error
88
    def pack_float(self, x):
89
        self.__buf.write(struct.pack('>f', x))
90

91
    @raise_conversion_error
92
    def pack_double(self, x):
93
        self.__buf.write(struct.pack('>d', x))
94 95

    def pack_fstring(self, n, s):
96
        if n < 0:
97
            raise ValueError('fstring size must be nonnegative')
98
        data = s[:n]
99
        n = ((n+3)//4)*4
100
        data = data + (n - len(data)) * b'\0'
101
        self.__buf.write(data)
102 103 104 105

    pack_fopaque = pack_fstring

    def pack_string(self, s):
106 107 108
        n = len(s)
        self.pack_uint(n)
        self.pack_fstring(n, s)
109 110 111 112 113

    pack_opaque = pack_string
    pack_bytes = pack_string

    def pack_list(self, list, pack_item):
114 115 116 117
        for item in list:
            self.pack_uint(1)
            pack_item(item)
        self.pack_uint(0)
118 119

    def pack_farray(self, n, list, pack_item):
120
        if len(list) != n:
121
            raise ValueError('wrong array size')
122 123
        for item in list:
            pack_item(item)
124 125

    def pack_array(self, list, pack_item):
126 127 128
        n = len(list)
        self.pack_uint(n)
        self.pack_farray(n, list, pack_item)
129 130


131

132 133 134 135
class Unpacker:
    """Unpacks various data representations from the given buffer."""

    def __init__(self, data):
136
        self.reset(data)
137 138

    def reset(self, data):
139 140
        self.__buf = data
        self.__pos = 0
141 142

    def get_position(self):
143
        return self.__pos
144 145

    def set_position(self, position):
146
        self.__pos = position
147

148
    def get_buffer(self):
149
        return self.__buf
150

151
    def done(self):
152 153
        if self.__pos < len(self.__buf):
            raise Error('unextracted data remains')
154 155

    def unpack_uint(self):
156 157 158 159 160
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
161
        return struct.unpack('>L', data)[0]
162 163

    def unpack_int(self):
164 165 166 167 168 169
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
        return struct.unpack('>l', data)[0]
170 171

    unpack_enum = unpack_int
172 173 174

    def unpack_bool(self):
        return bool(self.unpack_int())
175 176

    def unpack_uhyper(self):
177 178
        hi = self.unpack_uint()
        lo = self.unpack_uint()
179
        return int(hi)<<32 | lo
180 181

    def unpack_hyper(self):
182
        x = self.unpack_uhyper()
183 184
        if x >= 0x8000000000000000:
            x = x - 0x10000000000000000
185
        return x
186 187

    def unpack_float(self):
188 189 190 191 192 193
        i = self.__pos
        self.__pos = j = i+4
        data = self.__buf[i:j]
        if len(data) < 4:
            raise EOFError
        return struct.unpack('>f', data)[0]
194

195
    def unpack_double(self):
196 197 198 199 200 201
        i = self.__pos
        self.__pos = j = i+8
        data = self.__buf[i:j]
        if len(data) < 8:
            raise EOFError
        return struct.unpack('>d', data)[0]
202 203

    def unpack_fstring(self, n):
204
        if n < 0:
205
            raise ValueError('fstring size must be nonnegative')
206
        i = self.__pos
207
        j = i + (n+3)//4*4
208 209 210 211
        if j > len(self.__buf):
            raise EOFError
        self.__pos = j
        return self.__buf[i:i+n]
212 213 214 215

    unpack_fopaque = unpack_fstring

    def unpack_string(self):
216 217
        n = self.unpack_uint()
        return self.unpack_fstring(n)
218 219 220 221 222

    unpack_opaque = unpack_string
    unpack_bytes = unpack_string

    def unpack_list(self, unpack_item):
223 224 225 226
        list = []
        while 1:
            x = self.unpack_uint()
            if x == 0: break
227
            if x != 1:
228
                raise ConversionError('0 or 1 expected, got %r' % (x,))
229 230 231
            item = unpack_item()
            list.append(item)
        return list
232 233

    def unpack_farray(self, n, unpack_item):
234 235 236 237
        list = []
        for i in range(n):
            list.append(unpack_item())
        return list
238 239

    def unpack_array(self, unpack_item):
240 241
        n = self.unpack_uint()
        return self.unpack_farray(n, unpack_item)