Debian Codegraph @

Pyro5/serializers.py

raw
1 """
2 The various serializers.
3
4 Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
5 """
6
7 import array
8 import builtins
9 import uuid
10 import logging
11 import struct
12 import datetime
13 import decimal
14 import numbers
15 import inspect
16 import marshal
17 import json
18 import serpent
19 import contextlib
20 try:
21 import msgpack
22 except ImportError:
23 msgpack = None
24 from . import errors, config
25
26 __all__ = ["SerializerBase", "SerpentSerializer", "JsonSerializer", "MarshalSerializer", "MsgpackSerializer",
27 "serializers", "serializers_by_id"]
28
29 log = logging.getLogger("Pyro5.serializers")
30
31
32 all_exceptions = {}
33 for name, t in vars(builtins).items():
34 if type(t) is type and issubclass(t, BaseException):
35 all_exceptions[name] = t
36 for name, t in vars(errors).items():
37 if type(t) is type and issubclass(t, errors.PyroError):
38 all_exceptions[name] = t
39
40
41 def pyro_class_serpent_serializer(obj, serializer, stream, level):
42 # Override the default way that a Pyro URI/proxy/daemon is serialized.
43 # Because it defines a __getstate__ it would otherwise just become a tuple,
44 # and not be deserialized as a class.
45 d = SerializerBase.class_to_dict(obj)
46 serializer.ser_builtins_dict(d, stream, level)
47
48
49 def serialize_pyro_object_to_dict(obj):
50 return {
51 "__class__": "{:s}.{:s}".format(obj.__module__, obj.__class__.__name__),
52 "state": obj.__getstate__()
53 }
54
55
56 class SerializerBase(object):
57 """Base class for (de)serializer implementations (which must be thread safe)"""
58 serializer_id = 0 # define uniquely in subclass
59 __custom_class_to_dict_registry = {}
60 __custom_dict_to_class_registry = {}
61
62 def loads(self, data):
63 raise NotImplementedError("implement in subclass")
64
65 def loadsCall(self, data):
66 raise NotImplementedError("implement in subclass")
67
68 def dumps(self, data):
69 raise NotImplementedError("implement in subclass")
70
71 def dumpsCall(self, obj, method, vargs, kwargs):
72 raise NotImplementedError("implement in subclass")
73
74 @classmethod
75 def register_type_replacement(cls, object_type, replacement_function):
76 raise NotImplementedError("implement in subclass")
77
78 def _convertToBytes(self, data):
79 if type(data) is bytearray:
80 return bytes(data)
81 if type(data) is memoryview:
82 return data.tobytes()
83 return data
84
85 @classmethod
86 def register_class_to_dict(cls, clazz, converter, serpent_too=True):
87 """Registers a custom function that returns a dict representation of objects of the given class.
88 The function is called with a single parameter; the object to be converted to a dict."""
89 cls.__custom_class_to_dict_registry[clazz] = converter
90 if serpent_too:
91 with contextlib.suppress(errors.ProtocolError):
92 def serpent_converter(obj, serializer, stream, level):
93 d = converter(obj)
94 serializer.ser_builtins_dict(d, stream, level)
95
96 serpent.register_class(clazz, serpent_converter)
97
98 @classmethod
99 def unregister_class_to_dict(cls, clazz):
100 """Removes the to-dict conversion function registered for the given class. Objects of the class
101 will be serialized by the default mechanism again."""
102 if clazz in cls.__custom_class_to_dict_registry:
103 del cls.__custom_class_to_dict_registry[clazz]
104 with contextlib.suppress(errors.ProtocolError):
105 serpent.unregister_class(clazz)
106
107 @classmethod
108 def register_dict_to_class(cls, classname, converter):
109 """
110 Registers a custom converter function that creates objects from a dict with the given classname tag in it.
111 The function is called with two parameters: the classname and the dictionary to convert to an instance of the class.
112 """
113 cls.__custom_dict_to_class_registry[classname] = converter
114
115 @classmethod
116 def unregister_dict_to_class(cls, classname):
117 """
118 Removes the converter registered for the given classname. Dicts with that classname tag
119 will be deserialized by the default mechanism again.
120 """
121 if classname in cls.__custom_dict_to_class_registry:
122 del cls.__custom_dict_to_class_registry[classname]
123
124 @classmethod
125 def class_to_dict(cls, obj):
126 """
127 Convert a non-serializable object to a dict. Partly borrowed from serpent.
128 """
129 for clazz in cls.__custom_class_to_dict_registry:
130 if isinstance(obj, clazz):
131 return cls.__custom_class_to_dict_registry[clazz](obj)
132 if type(obj) in (set, dict, tuple, list):
133 # we use a ValueError to mirror the exception type returned by serpent and other serializers
134 raise ValueError("can't serialize type " + str(obj.__class__) + " into a dict")
135 if hasattr(obj, "_pyroDaemon"):
136 obj._pyroDaemon = None
137 if isinstance(obj, BaseException):
138 # special case for exceptions
139 return {
140 "__class__": obj.__class__.__module__ + "." + obj.__class__.__name__,
141 "__exception__": True,
142 "args": obj.args,
143 "attributes": vars(obj) # add custom exception attributes
144 }
145 # note: python 3.11+ object itself now has __getstate__
146 has_own_getstate = (
147 hasattr(type(obj), '__getstate__')
148 and type(obj).__getstate__ is not getattr(object, '__getstate__', None)
149 )
150 if has_own_getstate:
151 value = obj.__getstate__()
152 if isinstance(value, dict):
153 return value
154 try:
155 value = dict(vars(obj)) # make sure we can serialize anything that resembles a dict
156 value["__class__"] = obj.__class__.__module__ + "." + obj.__class__.__name__
157 return value
158 except TypeError:
159 if hasattr(obj, "__slots__"):
160 # use the __slots__ instead of the vars dict
161 value = {}
162 for slot in obj.__slots__:
163 value[slot] = getattr(obj, slot)
164 value["__class__"] = obj.__class__.__module__ + "." + obj.__class__.__name__
165 return value
166 else:
167 raise errors.SerializeError("don't know how to serialize class " + str(obj.__class__) +
168 " using serializer " + str(cls.__name__) +
169 ". Give it vars() or an appropriate __getstate__")
170
171 @classmethod
172 def dict_to_class(cls, data):
173 """
174 Recreate an object out of a dict containing the class name and the attributes.
175 Only a fixed set of classes are recognized.
176 """
177 from . import core, client, server # circular imports...
178 classname = data.get("__class__", "<unknown>")
179 if isinstance(classname, bytes):
180 classname = classname.decode("utf-8")
181 if classname in cls.__custom_dict_to_class_registry:
182 converter = cls.__custom_dict_to_class_registry[classname]
183 return converter(classname, data)
184 if "__" in classname:
185 raise errors.SecurityError("refused to deserialize types with double underscores in their name: " + classname)
186 # for performance reasons, the constructors below are hardcoded here
187 # instead of added on a per-class basis to the dict-to-class registry
188 if classname == "Pyro5.core.URI":
189 uri = core.URI.__new__(core.URI)
190 uri.__setstate__(data["state"])
191 return uri
192 elif classname == "Pyro5.client.Proxy":
193 proxy = client.Proxy.__new__(client.Proxy)
194 proxy.__setstate__(data["state"])
195 return proxy
196 elif classname == "Pyro5.server.Daemon":
197 daemon = server.Daemon.__new__(server.Daemon)
198 daemon.__setstate__(data["state"])
199 return daemon
200 elif classname.startswith("Pyro5.util."):
201 if classname == "Pyro5.util.SerpentSerializer":
202 return SerpentSerializer()
203 elif classname == "Pyro5.util.MarshalSerializer":
204 return MarshalSerializer()
205 elif classname == "Pyro5.util.JsonSerializer":
206 return JsonSerializer()
207 elif classname == "Pyro5.util.MsgpackSerializer":
208 return MsgpackSerializer()
209 elif classname.startswith("Pyro5.errors."):
210 errortype = getattr(errors, classname.split('.', 2)[2])
211 if issubclass(errortype, errors.PyroError):
212 return SerializerBase.make_exception(errortype, data)
213 elif classname == "struct.error":
214 return SerializerBase.make_exception(struct.error, data)
215 elif classname == "Pyro5.core._ExceptionWrapper":
216 ex = data["exception"]
217 if isinstance(ex, dict) and "__class__" in ex:
218 ex = SerializerBase.dict_to_class(ex)
219 return core._ExceptionWrapper(ex)
220 elif data.get("__exception__", False):
221 if classname in all_exceptions:
222 return SerializerBase.make_exception(all_exceptions[classname], data)
223 # translate to the appropriate namespace...
224 namespace, short_classname = classname.split('.', 1)
225 if namespace in ("builtins", "exceptions"):
226 exceptiontype = getattr(builtins, short_classname)
227 if issubclass(exceptiontype, BaseException):
228 return SerializerBase.make_exception(exceptiontype, data)
229 elif namespace == "sqlite3" and short_classname.endswith("Error"):
230 import sqlite3
231 exceptiontype = getattr(sqlite3, short_classname)
232 if issubclass(exceptiontype, BaseException):
233 return SerializerBase.make_exception(exceptiontype, data)
234 log.warning("unsupported serialized class: " + classname)
235 raise errors.SerializeError("unsupported serialized class: " + classname)
236
237 @staticmethod
238 def make_exception(exceptiontype, data):
239 ex = exceptiontype(*data["args"])
240 if "attributes" in data:
241 # restore custom attributes on the exception object
242 for attr, value in data["attributes"].items():
243 setattr(ex, attr, value)
244 return ex
245
246 def recreate_classes(self, literal):
247 t = type(literal)
248 if t is set:
249 return {self.recreate_classes(x) for x in literal}
250 if t is list:
251 return [self.recreate_classes(x) for x in literal]
252 if t is tuple:
253 return tuple(self.recreate_classes(x) for x in literal)
254 if t is dict:
255 if "__class__" in literal:
256 return self.dict_to_class(literal)
257 result = {}
258 for key, value in literal.items():
259 result[key] = self.recreate_classes(value)
260 return result
261 return literal
262
263 def __eq__(self, other):
264 """this equality method is only to support the unit tests of this class"""
265 return isinstance(other, SerializerBase) and vars(self) == vars(other)
266
267 def __ne__(self, other):
268 return not self.__eq__(other)
269
270 __hash__ = object.__hash__
271
272
273 class SerpentSerializer(SerializerBase):
274 """(de)serializer that wraps the serpent serialization protocol."""
275 serializer_id = 1 # never change this
276
277 def dumpsCall(self, obj, method, vargs, kwargs):
278 return serpent.dumps((obj, method, vargs, kwargs), module_in_classname=True, bytes_repr=config.SERPENT_BYTES_REPR)
279
280 def dumps(self, data):
281 return serpent.dumps(data, module_in_classname=True, bytes_repr=config.SERPENT_BYTES_REPR)
282
283 def loadsCall(self, data):
284 obj, method, vargs, kwargs = serpent.loads(data)
285 vargs = self.recreate_classes(vargs)
286 kwargs = self.recreate_classes(kwargs)
287 return obj, method, vargs, kwargs
288
289 def loads(self, data):
290 return self.recreate_classes(serpent.loads(data))
291
292 @classmethod
293 def register_type_replacement(cls, object_type, replacement_function):
294 def custom_serializer(obj, serpent_serializer, outputstream, indentlevel):
295 replaced = replacement_function(obj)
296 if replaced is obj:
297 serpent_serializer.ser_default_class(replaced, outputstream, indentlevel)
298 else:
299 serpent_serializer._serialize(replaced, outputstream, indentlevel)
300
301 if object_type is type or not inspect.isclass(object_type):
302 raise ValueError("refusing to register replacement for a non-type or the type 'type' itself")
303 serpent.register_class(object_type, custom_serializer)
304
305 @classmethod
306 def dict_to_class(cls, data):
307 if data.get("__class__") == "float":
308 return float(data["value"]) # serpent encodes a float nan as a special class dict like this
309 return super(SerpentSerializer, cls).dict_to_class(data)
310
311
312 class MarshalSerializer(SerializerBase):
313 """(de)serializer that wraps the marshal serialization protocol."""
314 serializer_id = 2 # never change this
315
316 def dumpsCall(self, obj, method, vargs, kwargs):
317 vargs = [self.convert_obj_into_marshallable(value) for value in vargs]
318 kwargs = {key: self.convert_obj_into_marshallable(value) for key, value in kwargs.items()}
319 return marshal.dumps((obj, method, vargs, kwargs))
320
321 def dumps(self, data):
322 return marshal.dumps(self.convert_obj_into_marshallable(data))
323
324 def loadsCall(self, data):
325 data = self._convertToBytes(data)
326 obj, method, vargs, kwargs = marshal.loads(data)
327 vargs = self.recreate_classes(vargs)
328 kwargs = self.recreate_classes(kwargs)
329 return obj, method, vargs, kwargs
330
331 def loads(self, data):
332 data = self._convertToBytes(data)
333 return self.recreate_classes(marshal.loads(data))
334
335 def convert_obj_into_marshallable(self, obj):
336 marshalable_types = (str, int, float, type(None), bool, complex, bytes, bytearray,
337 tuple, set, frozenset, list, dict)
338 if isinstance(obj, array.array):
339 if obj.typecode == 'c':
340 return obj.tostring()
341 if obj.typecode == 'u':
342 return obj.tounicode()
343 return obj.tolist()
344 if isinstance(obj, marshalable_types):
345 return obj
346 return self.class_to_dict(obj)
347
348 @classmethod
349 def class_to_dict(cls, obj):
350 if isinstance(obj, uuid.UUID):
351 return str(obj)
352 return super(MarshalSerializer, cls).class_to_dict(obj)
353
354 @classmethod
355 def register_type_replacement(cls, object_type, replacement_function):
356 pass # marshal serializer doesn't support per-type hooks
357
358
359 class JsonSerializer(SerializerBase):
360 """(de)serializer that wraps the json serialization protocol."""
361 serializer_id = 3 # never change this
362
363 __type_replacements = {}
364
365 def dumpsCall(self, obj, method, vargs, kwargs):
366 data = {"object": obj, "method": method, "params": vargs, "kwargs": kwargs}
367 data = json.dumps(data, ensure_ascii=False, default=self.default)
368 return data.encode("utf-8")
369
370 def dumps(self, data):
371 data = json.dumps(data, ensure_ascii=False, default=self.default)
372 return data.encode("utf-8")
373
374 def loadsCall(self, data):
375 data = self._convertToBytes(data).decode("utf-8")
376 data = json.loads(data)
377 vargs = self.recreate_classes(data["params"])
378 kwargs = self.recreate_classes(data["kwargs"])
379 return data["object"], data["method"], vargs, kwargs
380
381 def loads(self, data):
382 data = self._convertToBytes(data).decode("utf-8")
383 return self.recreate_classes(json.loads(data))
384
385 def default(self, obj):
386 replacer = self.__type_replacements.get(type(obj), None)
387 if replacer:
388 obj = replacer(obj)
389 if isinstance(obj, set):
390 return tuple(obj) # json module can't deal with sets so we make a tuple out of it
391 if isinstance(obj, uuid.UUID):
392 return str(obj)
393 if isinstance(obj, (datetime.datetime, datetime.date)):
394 return obj.isoformat()
395 if isinstance(obj, decimal.Decimal):
396 return str(obj)
397 if isinstance(obj, array.array):
398 if obj.typecode == 'c':
399 return obj.tostring()
400 if obj.typecode == 'u':
401 return obj.tounicode()
402 return obj.tolist()
403 return self.class_to_dict(obj)
404
405 @classmethod
406 def register_type_replacement(cls, object_type, replacement_function):
407 if object_type is type or not inspect.isclass(object_type):
408 raise ValueError("refusing to register replacement for a non-type or the type 'type' itself")
409 cls.__type_replacements[object_type] = replacement_function
410
411
412 class MsgpackSerializer(SerializerBase):
413 """(de)serializer that wraps the msgpack serialization protocol."""
414 serializer_id = 4 # never change this
415
416 __type_replacements = {}
417
418 def dumpsCall(self, obj, method, vargs, kwargs):
419 return msgpack.packb((obj, method, vargs, kwargs), use_bin_type=True, default=self.default)
420
421 def dumps(self, data):
422 return msgpack.packb(data, use_bin_type=True, default=self.default)
423
424 def loadsCall(self, data):
425 return msgpack.unpackb(self._convertToBytes(data), raw=False, object_hook=self.object_hook)
426
427 def loads(self, data):
428 return msgpack.unpackb(self._convertToBytes(data), raw=False, object_hook=self.object_hook, ext_hook=self.ext_hook)
429
430 def default(self, obj):
431 replacer = self.__type_replacements.get(type(obj), None)
432 if replacer:
433 obj = replacer(obj)
434 if isinstance(obj, set):
435 return tuple(obj) # msgpack module can't deal with sets so we make a tuple out of it
436 if isinstance(obj, uuid.UUID):
437 return str(obj)
438 if isinstance(obj, complex):
439 return msgpack.ExtType(0x30, struct.pack("dd", obj.real, obj.imag))
440 if isinstance(obj, datetime.datetime):
441 if obj.tzinfo:
442 raise errors.SerializeError("msgpack cannot serialize datetime with timezone info")
443 return msgpack.ExtType(0x32, struct.pack("d", obj.timestamp()))
444 if isinstance(obj, datetime.date):
445 return msgpack.ExtType(0x33, struct.pack("l", obj.toordinal()))
446 if isinstance(obj, decimal.Decimal):
447 return str(obj)
448 if isinstance(obj, numbers.Number):
449 return msgpack.ExtType(0x31, str(obj).encode("ascii")) # long
450 if isinstance(obj, array.array):
451 if obj.typecode == 'c':
452 return obj.tostring()
453 if obj.typecode == 'u':
454 return obj.tounicode()
455 return obj.tolist()
456 return self.class_to_dict(obj)
457
458 def object_hook(self, obj):
459 if "__class__" in obj:
460 return self.dict_to_class(obj)
461 return obj
462
463 def ext_hook(self, code, data):
464 if code == 0x30:
465 real, imag = struct.unpack("dd", data)
466 return complex(real, imag)
467 if code == 0x31:
468 return int(data)
469 if code == 0x32:
470 return datetime.datetime.fromtimestamp(struct.unpack("d", data)[0])
471 if code == 0x33:
472 return datetime.date.fromordinal(struct.unpack("l", data)[0])
473 raise errors.SerializeError("invalid ext code for msgpack: " + str(code))
474
475 @classmethod
476 def register_type_replacement(cls, object_type, replacement_function):
477 if object_type is type or not inspect.isclass(object_type):
478 raise ValueError("refusing to register replacement for a non-type or the type 'type' itself")
479 cls.__type_replacements[object_type] = replacement_function
480
481
482 """The various serializers that are supported"""
483 serializers = {
484 "serpent": SerpentSerializer(),
485 "marshal": MarshalSerializer(),
486 "json": JsonSerializer()
487 }
488
489 if msgpack:
490 serializers["msgpack"] = MsgpackSerializer()
491
492
493 """The available serializers by their internal id"""
494 serializers_by_id = {ser.serializer_id: ser for ser in serializers.values()}