Debian Codegraph @

Pyro5/protocol.py

raw
1 """
2 The pyro wire protocol structures.
3
4 Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
5
6
7 Wire messages contains of a fixed size header, an optional set of annotation chunks,
8 and then the payload data. This class doesn't deal with the payload data:
9 (de)serialization and handling of that data is done elsewhere.
10 Annotation chunks are only parsed.
11
12 The header format is::
13
14 0x00 4s 4 'PYRO' (message identifier)
15 0x04 H 2 protocol version
16 0x06 B 1 message type
17 0x07 B 1 serializer id
18 0x08 H 2 message flags
19 0x0a H 2 sequence number (to identify proper request-reply sequencing)
20 0x0c I 4 data length (max 4 Gb)
21 0x10 I 4 annotations length (max 4 Gb, total of all chunks, 0 if no annotation chunks present)
22 0x14 16s 16 correlation uuid
23 0x24 H 2 (reserved)
24 0x26 H 2 magic number 0x4dc5
25 total size: 0x28 (40 bytes)
26
27 After the header, zero or more annotation chunks may follow, of the format::
28
29 4s 4 annotation id (4 ASCII letters)
30 I 4 chunk length (max 4 Gb)
31 B x annotation chunk databytes
32
33 After that, the actual payload data bytes follow.
34 """
35
36 import struct
37 import logging
38 import zlib
39 import uuid
40 from . import config, errors
41 from .callcontext import current_context
42
43
44 log = logging.getLogger("Pyro5.protocol")
45
46 MSG_CONNECT = 1
47 MSG_CONNECTOK = 2
48 MSG_CONNECTFAIL = 3
49 MSG_INVOKE = 4
50 MSG_RESULT = 5
51 MSG_PING = 6
52 FLAGS_EXCEPTION = 1 << 0
53 FLAGS_COMPRESSED = 1 << 1 # compress the data, but not the annotations (if you need that, do it yourself)
54 FLAGS_ONEWAY = 1 << 2
55 FLAGS_BATCH = 1 << 3
56 FLAGS_ITEMSTREAMRESULT = 1 << 4
57 FLAGS_KEEPSERIALIZED = 1 << 5
58 FLAGS_CORR_ID = 1 << 6
59
60 # wire protocol version. Note that if this gets updated, Pyrolite might need an update too.
61 PROTOCOL_VERSION = 502
62 _magic_number = 0x4dc5
63 _header_format = '!4sHBBHHII16sHH'
64 _header_size = struct.calcsize(_header_format)
65 _magic_number_bytes = _magic_number.to_bytes(2, "big")
66 _protocol_version_bytes = PROTOCOL_VERSION.to_bytes(2, "big")
67 _empty_correlation_id = b"\0" * 16
68
69
70 class SendingMessage:
71 """Wire protocol message that will be sent."""
72
73 def __init__(self, msgtype, flags, seq, serializer_id, payload, annotations=None):
74 self.type = msgtype
75 self.seq = seq
76 self.serializer_id = serializer_id
77 annotations = annotations or {}
78 annotations_size = sum([8 + len(v) for v in annotations.values()])
79 flags &= ~FLAGS_COMPRESSED
80 if config.COMPRESSION and len(payload) > 100:
81 payload = zlib.compress(payload, 4)
82 flags |= FLAGS_COMPRESSED
83 self.flags = flags
84 total_size = len(payload) + annotations_size
85 if total_size > config.MAX_MESSAGE_SIZE:
86 raise errors.ProtocolError("message too large ({:d}, max={:d})".format(total_size, config.MAX_MESSAGE_SIZE))
87 if current_context.correlation_id:
88 flags |= FLAGS_CORR_ID
89 self.corr_id = current_context.correlation_id.bytes
90 else:
91 self.corr_id = _empty_correlation_id
92 header_data = struct.pack(_header_format, b"PYRO", PROTOCOL_VERSION, msgtype, serializer_id, flags, seq,
93 len(payload), annotations_size, self.corr_id, 0, _magic_number)
94 annotation_data = []
95 for k, v in annotations.items():
96 if len(k) != 4:
97 raise errors.ProtocolError("annotation identifier must be 4 ascii characters")
98 annotation_data.append(struct.pack("!4sI", k.encode("ascii"), len(v)))
99 if not isinstance(v, (bytes, bytearray, memoryview)):
100 raise errors.ProtocolError("annotation data must be bytes, bytearray, or memoryview", type(v))
101 annotation_data.append(v) # note: annotations are not compressed by Pyro
102 self.data = header_data + b"".join(annotation_data) + payload
103
104 def __repr__(self):
105 return "<{:s}.{:s} at 0x{:x}; type={:d} flags={:d} seq={:d} size={:d}>" \
106 .format(self.__module__, self.__class__.__name__, id(self), self.type, self.flags, self.seq, len(self.data))
107
108 @staticmethod
109 def ping(pyroConnection):
110 """Convenience method to send a 'ping' message and wait for the 'pong' response"""
111 ping = SendingMessage(MSG_PING, 0, 0, 42, b"ping")
112 pyroConnection.send(ping.data)
113 recv_stub(pyroConnection, [MSG_PING])
114
115
116 class ReceivingMessage:
117 """Wire protocol message that was received."""
118 def __init__(self, header, payload=None):
119 """Parses a message from the given header."""
120 tag, ver, self.type, self.serializer_id, self.flags, self.seq, self.data_size, \
121 self.annotations_size, self.corr_id, _, magic = struct.unpack(_header_format, header)
122 if tag != b"PYRO" or ver != PROTOCOL_VERSION or magic != _magic_number:
123 raise errors.ProtocolError("invalid message or protocol version")
124 if self.data_size+self.annotations_size > config.MAX_MESSAGE_SIZE:
125 raise errors.ProtocolError("message too large ({:d}, max={:d})"
126 .format(self.data_size+self.annotations_size, config.MAX_MESSAGE_SIZE))
127 self.data = None
128 self.annotations = {}
129 if payload is not None:
130 self.add_payload(payload)
131
132 def __repr__(self):
133 return "<{:s}.{:s} at 0x{:x}; type={:d} flags={:d} seq={:d} size={:d}>" \
134 .format(self.__module__, self.__class__.__name__, id(self), self.type, self.flags, self.seq, len(self.data or ""))
135
136 @staticmethod
137 def validate(data):
138 """Checks if the message data looks like a valid Pyro message, if not, raise an error."""
139 ld = len(data)
140 if ld < 4:
141 raise ValueError("data must be at least 4 bytes to be able to identify")
142 if not data.startswith(b"PYRO"):
143 raise errors.ProtocolError("invalid data")
144 if ld >= 6 and data[4:6] != _protocol_version_bytes:
145 raise errors.ProtocolError("invalid protocol version: {:d}".format(int.from_bytes(data[4:6], "big")))
146 if ld >= _header_size and data[38:40] != _magic_number_bytes:
147 raise errors.ProtocolError("invalid magic number")
148
149 def add_payload(self, payload):
150 """Parses (annotations processing) and adds payload data to a received message."""
151 assert not self.data
152 if len(payload) != self.data_size + self.annotations_size:
153 raise errors.ProtocolError("payload length doesn't match message header")
154 if self.annotations_size:
155 payload = memoryview(payload) # avoid copying
156 self.annotations = {}
157 i = 0
158 while i < self.annotations_size:
159 annotation_id = bytes(payload[i:i+4]).decode("ascii")
160 length = int.from_bytes(payload[i+4:i+8], "big")
161 self.annotations[annotation_id] = payload[i+8:i+8+length] # note: it stores a memoryview!
162 i += 8 + length
163 assert i == self.annotations_size
164 self.data = payload[self.annotations_size:]
165 else:
166 self.data = payload
167 if self.flags & FLAGS_COMPRESSED:
168 self.data = zlib.decompress(self.data)
169 self.flags &= ~FLAGS_COMPRESSED
170 self.data_size = len(self.data)
171
172
173 def log_wiredata(logger, text, msg):
174 """logs all the given properties of the wire message in the given logger"""
175 num_anns = len(msg.annotations) if hasattr(msg, "annotations") else 0
176 corr_bytes = bytes(msg.corr_id) if hasattr(msg, "corr_id") else _empty_correlation_id
177 corr_id = uuid.UUID(bytes=corr_bytes)
178 logger.debug("%s: msgtype=%d flags=0x%x ser=%d seq=%d num_annotations=%s corr_id=%s\ndata=%r" %
179 (text, msg.type, msg.flags, msg.serializer_id, msg.seq, num_anns, corr_id, bytes(msg.data)))
180
181
182 def recv_stub(connection, accepted_msgtypes=None):
183 """
184 Receives a pyro message from a given connection.
185 Accepts the given message types (None=any, or pass a sequence).
186 Also reads annotation chunks and the actual payload data.
187 """
188 # TODO decouple i/o from actual protocol logic, so that the protocol can be easily unit tested
189 header = connection.recv(6) # 'PYRO' + 2 bytes protocol version
190 ReceivingMessage.validate(header)
191 header += connection.recv(_header_size - 6)
192 msg = ReceivingMessage(header)
193 if accepted_msgtypes and msg.type not in accepted_msgtypes:
194 err = "invalid msg type {:d} received (expected: {:s})".format(msg.type, ",".join(str(t) for t in accepted_msgtypes))
195 log.error(err)
196 exc = errors.ProtocolError(err)
197 exc.pyroMsg = msg
198 raise exc
199 payload = connection.recv(msg.annotations_size + msg.data_size)
200 msg.add_payload(payload)
201 return msg