2 # Copyright (c) 2018 Cisco and/or its affiliates.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
21 if sys.version_info <= (3, 4):
22 from aenum import IntEnum # noqa: F401
24 from enum import IntEnum # noqa: F401
26 if sys.version_info <= (3, 6):
27 from aenum import IntFlag # noqa: F401
30 from enum import IntFlag # noqa: F401
32 from . import vpp_format # noqa: E402
35 # Set log-level in application by doing e.g.:
36 # logger = logging.getLogger('vpp_serializer')
37 # logger.setLevel(logging.DEBUG)
39 logger = logging.getLogger(__name__)
41 if sys.version[0] == '2':
42 def check(d): type(d) is dict
44 def check(d): type(d) is dict or type(d) is bytes
47 def conversion_required(data, field_type):
51 if type(data).__name__ in vpp_format.conversion_table[field_type]:
57 def conversion_packer(data, field_type):
58 t = type(data).__name__
59 return types[field_type].pack(vpp_format.
60 conversion_table[field_type][t](data))
63 def conversion_unpacker(data, field_type):
64 if field_type not in vpp_format.conversion_unpacker_table:
66 return vpp_format.conversion_unpacker_table[field_type](data)
69 class BaseTypes(object):
70 def __init__(self, type, elements=0, options=None):
71 base_types = {'u8': '>B',
84 if elements > 0 and (type == 'u8' or type == 'string'):
85 self.packer = struct.Struct('>%ss' % elements)
87 self.packer = struct.Struct(base_types[type])
88 self.size = self.packer.size
89 self.options = options
91 def __call__(self, args):
95 def pack(self, data, kwargs=None):
96 if not data: # Default to zero if not specified
97 if self.options and 'default' in self.options:
98 data = self.options['default']
101 return self.packer.pack(data)
103 def unpack(self, data, offset, result=None, ntc=False):
104 return self.packer.unpack_from(data, offset)[0], self.packer.size
107 class String(object):
108 def __init__(self, options):
111 self.length_field_packer = BaseTypes('u32')
112 self.limit = options['limit'] if 'limit' in options else None
114 def pack(self, list, kwargs=None):
116 return self.length_field_packer.pack(0) + b""
117 if self.limit and len(list) > self.limit:
118 raise VPPSerializerValueError(
119 "Invalid argument length for: {}, {} maximum {}".
120 format(list, len(list), self.limit))
122 return self.length_field_packer.pack(len(list)) + list.encode('utf8')
124 def unpack(self, data, offset=0, result=None, ntc=False):
125 length, length_field_size = self.length_field_packer.unpack(data,
129 p = BaseTypes('u8', length)
130 x, size = p.unpack(data, offset + length_field_size)
131 x2 = x.split(b'\0', 1)[0]
132 return (x2.decode('utf8'), size + length_field_size)
135 types = {'u8': BaseTypes('u8'), 'u16': BaseTypes('u16'),
136 'u32': BaseTypes('u32'), 'i32': BaseTypes('i32'),
137 'u64': BaseTypes('u64'), 'f64': BaseTypes('f64'),
138 'bool': BaseTypes('bool'), 'string': String}
141 def vpp_get_type(name):
148 class VPPSerializerValueError(ValueError):
152 class FixedList_u8(object):
153 def __init__(self, name, field_type, num):
156 self.packer = BaseTypes(field_type, num)
157 self.size = self.packer.size
158 self.field_type = field_type
160 def __call__(self, args):
164 def pack(self, data, kwargs=None):
165 """Packs a fixed length bytestring. Left-pads with zeros
166 if input data is too short."""
168 return b'\x00' * self.size
170 if len(data) > self.num:
171 raise VPPSerializerValueError(
172 'Fixed list length error for "{}", got: {}'
174 .format(self.name, len(data), self.num))
176 return self.packer.pack(data)
178 def unpack(self, data, offset=0, result=None, ntc=False):
179 if len(data[offset:]) < self.num:
180 raise VPPSerializerValueError(
181 'Invalid array length for "{}" got {}'
183 .format(self.name, len(data[offset:]), self.num))
184 if self.field_type == 'string':
185 s = self.packer.unpack(data, offset)
186 s2 = s[0].split(b'\0', 1)[0]
187 return (s2.decode('utf-8'), self.num)
188 return self.packer.unpack(data, offset)
191 class FixedList(object):
192 def __init__(self, name, field_type, num):
194 self.packer = types[field_type]
195 self.size = self.packer.size * num
197 self.field_type = field_type
199 def __call__(self, args):
203 def pack(self, list, kwargs):
204 if len(list) != self.num:
205 raise VPPSerializerValueError(
206 'Fixed list length error, got: {} expected: {}'
207 .format(len(list), self.num))
210 b += self.packer.pack(e)
213 def unpack(self, data, offset=0, result=None, ntc=False):
214 # Return a list of arguments
217 for e in range(self.num):
218 x, size = self.packer.unpack(data, offset, ntc=ntc)
225 class VLAList(object):
226 def __init__(self, name, field_type, len_field_name, index):
228 self.field_type = field_type
230 self.packer = types[field_type]
231 self.size = self.packer.size
232 self.length_field = len_field_name
234 def __call__(self, args):
238 def pack(self, list, kwargs=None):
241 if len(list) != kwargs[self.length_field]:
242 raise VPPSerializerValueError(
243 'Variable length error, got: {} expected: {}'
244 .format(len(list), kwargs[self.length_field]))
249 if self.packer.size == 1:
250 return bytearray(list)
253 b += self.packer.pack(e)
256 def unpack(self, data, offset=0, result=None, ntc=False):
257 # Return a list of arguments
261 if self.packer.size == 1:
262 if result[self.index] == 0:
264 p = BaseTypes('u8', result[self.index])
265 return p.unpack(data, offset, ntc=ntc)
268 for e in range(result[self.index]):
269 x, size = self.packer.unpack(data, offset, ntc=ntc)
276 class VLAList_legacy():
277 def __init__(self, name, field_type):
278 self.packer = types[field_type]
279 self.size = self.packer.size
281 def __call__(self, args):
285 def pack(self, list, kwargs=None):
286 if self.packer.size == 1:
291 b += self.packer.pack(e)
294 def unpack(self, data, offset=0, result=None, ntc=False):
296 # Return a list of arguments
297 if (len(data) - offset) % self.packer.size:
298 raise VPPSerializerValueError(
299 'Legacy Variable Length Array length mismatch.')
300 elements = int((len(data) - offset) / self.packer.size)
302 for e in range(elements):
303 x, size = self.packer.unpack(data, offset, ntc=ntc)
305 offset += self.packer.size
310 class VPPEnumType(object):
311 def __init__(self, name, msgdef):
312 self.size = types['u32'].size
313 self.enumtype = 'u32'
316 if type(f) is dict and 'enumtype' in f:
317 if f['enumtype'] != 'u32':
318 self.size = types[f['enumtype']].size
319 self.enumtype = f['enumtype']
322 e_hash[ename] = evalue
323 self.enum = IntFlag(name, e_hash)
326 def __call__(self, args):
330 def __getattr__(self, name):
331 return self.enum[name]
336 if sys.version[0] == '2':
337 __nonzero__ = __bool__
339 def pack(self, data, kwargs=None):
340 return types[self.enumtype].pack(data)
342 def unpack(self, data, offset=0, result=None, ntc=False):
343 x, size = types[self.enumtype].unpack(data, offset)
344 return self.enum(x), size
347 class VPPUnionType(object):
348 def __init__(self, name, msgdef):
353 self.packers = collections.OrderedDict()
354 for i, f in enumerate(msgdef):
355 if type(f) is dict and 'crc' in f:
359 if f_type not in types:
360 logger.debug('Unknown union type {}'.format(f_type))
361 raise VPPSerializerValueError(
362 'Unknown message type {}'.format(f_type))
363 fields.append(f_name)
364 size = types[f_type].size
365 self.packers[f_name] = types[f_type]
371 self.tuple = collections.namedtuple(name, fields, rename=True)
373 def __call__(self, args):
377 # Union of variable length?
378 def pack(self, data, kwargs=None):
380 return b'\x00' * self.size
382 for k, v in data.items():
383 logger.debug("Key: {} Value: {}".format(k, v))
384 b = self.packers[k].pack(v, kwargs)
386 r = bytearray(self.size)
390 def unpack(self, data, offset=0, result=None, ntc=False):
393 for k, p in self.packers.items():
394 x, size = p.unpack(data, offset, ntc=ntc)
398 return self.tuple._make(r), maxsize
401 class VPPTypeAlias(object):
402 def __init__(self, name, msgdef):
404 t = vpp_get_type(msgdef['type'])
407 if 'length' in msgdef:
408 if msgdef['length'] == 0:
410 if msgdef['type'] == 'u8':
411 self.packer = FixedList_u8(name, msgdef['type'],
413 self.size = self.packer.size
415 self.packer = FixedList(name, msgdef['type'], msgdef['length'])
422 def __call__(self, args):
426 def pack(self, data, kwargs=None):
427 if data and conversion_required(data, self.name):
429 return conversion_packer(data, self.name)
430 # Python 2 and 3 raises different exceptions from inet_pton
431 except(OSError, socket.error, TypeError):
434 return self.packer.pack(data, kwargs)
436 def unpack(self, data, offset=0, result=None, ntc=False):
437 t, size = self.packer.unpack(data, offset, result, ntc=ntc)
439 return conversion_unpacker(t, self.name), size
443 class VPPType(object):
444 # Set everything up to be able to pack / unpack
445 def __init__(self, name, msgdef):
451 self.field_by_name = {}
453 for i, f in enumerate(msgdef):
454 if type(f) is dict and 'crc' in f:
457 f_type, f_name = f[:2]
458 self.fields.append(f_name)
459 self.field_by_name[f_name] = None
460 self.fieldtypes.append(f_type)
461 if f_type not in types:
462 logger.debug('Unknown type {}'.format(f_type))
463 raise VPPSerializerValueError(
464 'Unknown message type {}'.format(f_type))
467 options = [x for x in f if type(x) is dict]
469 self.options = options[0]
473 if fieldlen == 3: # list
475 if list_elements == 0:
476 p = VLAList_legacy(f_name, f_type)
477 self.packers.append(p)
478 elif f_type == 'u8' or f_type == 'string':
479 p = FixedList_u8(f_name, f_type, list_elements)
480 self.packers.append(p)
483 p = FixedList(f_name, f_type, list_elements)
484 self.packers.append(p)
486 elif fieldlen == 4: # Variable length list
487 length_index = self.fields.index(f[3])
488 p = VLAList(f_name, f_type, f[3], length_index)
489 self.packers.append(p)
491 p = types[f_type](self.options)
492 self.packers.append(p)
496 self.tuple = collections.namedtuple(name, self.fields, rename=True)
499 def __call__(self, args):
503 def pack(self, data, kwargs=None):
508 # Try one of the format functions
509 if data and conversion_required(data, self.name):
510 return conversion_packer(data, self.name)
512 for i, a in enumerate(self.fields):
513 if data and type(data) is not dict and a not in data:
514 raise VPPSerializerValueError(
515 "Invalid argument: {} expected {}.{}".
516 format(data, self.name, a))
518 # Defaulting to zero.
519 if not data or a not in data: # Default to 0
521 kwarg = None # No default for VLA
524 kwarg = kwargs[a] if a in kwargs else None
525 if isinstance(self.packers[i], VPPType):
526 b += self.packers[i].pack(arg, kwarg)
528 b += self.packers[i].pack(arg, kwargs)
532 def unpack(self, data, offset=0, result=None, ntc=False):
533 # Return a list of arguments
536 for p in self.packers:
537 x, size = p.unpack(data, offset, result, ntc)
538 if type(x) is tuple and len(x) == 1:
543 t = self.tuple._make(result)
545 t = conversion_unpacker(t, self.name)
549 class VPPMessage(VPPType):