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, name, num, options):
112 self.length_field_packer = BaseTypes('u32')
113 self.limit = options['limit'] if 'limit' in options else num
114 self.fixed = True if num else False
115 if self.fixed and not self.limit:
116 raise VPPSerializerValueError(
117 "Invalid argument length for: {}, {} maximum {}".
118 format(list, len(list), self.limit))
120 def pack(self, list, kwargs=None):
123 return b"\x00" * self.limit
124 return self.length_field_packer.pack(0) + b""
125 if self.limit and len(list) > self.limit - 1:
126 raise VPPSerializerValueError(
127 "Invalid argument length for: {}, {} maximum {}".
128 format(list, len(list), self.limit - 1))
130 return list.encode('ascii').ljust(self.limit, b'\x00')
131 return self.length_field_packer.pack(len(list)) + list.encode('ascii')
133 def unpack(self, data, offset=0, result=None, ntc=False):
135 p = BaseTypes('u8', self.num)
136 s = p.unpack(data, offset)
137 s2 = s[0].split(b'\0', 1)[0]
138 return (s2.decode('ascii'), self.num)
140 length, length_field_size = self.length_field_packer.unpack(data,
144 p = BaseTypes('u8', length)
145 x, size = p.unpack(data, offset + length_field_size)
146 #x2 = x.split(b'\0', 1)[0]
147 return (x.decode('ascii', errors='replace'), size + length_field_size)
150 types = {'u8': BaseTypes('u8'), 'u16': BaseTypes('u16'),
151 'u32': BaseTypes('u32'), 'i32': BaseTypes('i32'),
152 'u64': BaseTypes('u64'), 'f64': BaseTypes('f64'),
153 'bool': BaseTypes('bool'), 'string': String}
156 def vpp_get_type(name):
163 class VPPSerializerValueError(ValueError):
167 class FixedList_u8(object):
168 def __init__(self, name, field_type, num):
171 self.packer = BaseTypes(field_type, num)
172 self.size = self.packer.size
173 self.field_type = field_type
175 def __call__(self, args):
179 def pack(self, data, kwargs=None):
180 """Packs a fixed length bytestring. Left-pads with zeros
181 if input data is too short."""
183 return b'\x00' * self.size
185 if len(data) > self.num:
186 raise VPPSerializerValueError(
187 'Fixed list length error for "{}", got: {}'
189 .format(self.name, len(data), self.num))
191 return self.packer.pack(data)
193 def unpack(self, data, offset=0, result=None, ntc=False):
194 if len(data[offset:]) < self.num:
195 raise VPPSerializerValueError(
196 'Invalid array length for "{}" got {}'
198 .format(self.name, len(data[offset:]), self.num))
199 return self.packer.unpack(data, offset)
202 class FixedList(object):
203 def __init__(self, name, field_type, num):
205 self.packer = types[field_type]
206 self.size = self.packer.size * num
208 self.field_type = field_type
210 def __call__(self, args):
214 def pack(self, list, kwargs):
215 if len(list) != self.num:
216 raise VPPSerializerValueError(
217 'Fixed list length error, got: {} expected: {}'
218 .format(len(list), self.num))
221 b += self.packer.pack(e)
224 def unpack(self, data, offset=0, result=None, ntc=False):
225 # Return a list of arguments
228 for e in range(self.num):
229 x, size = self.packer.unpack(data, offset, ntc=ntc)
236 class VLAList(object):
237 def __init__(self, name, field_type, len_field_name, index):
239 self.field_type = field_type
241 self.packer = types[field_type]
242 self.size = self.packer.size
243 self.length_field = len_field_name
245 def __call__(self, args):
249 def pack(self, list, kwargs=None):
252 if len(list) != kwargs[self.length_field]:
253 raise VPPSerializerValueError(
254 'Variable length error, got: {} expected: {}'
255 .format(len(list), kwargs[self.length_field]))
260 if self.packer.size == 1:
261 return bytearray(list)
264 b += self.packer.pack(e)
267 def unpack(self, data, offset=0, result=None, ntc=False):
268 # Return a list of arguments
272 if self.packer.size == 1:
273 if result[self.index] == 0:
275 p = BaseTypes('u8', result[self.index])
276 return p.unpack(data, offset, ntc=ntc)
279 for e in range(result[self.index]):
280 x, size = self.packer.unpack(data, offset, ntc=ntc)
287 class VLAList_legacy():
288 def __init__(self, name, field_type):
289 self.packer = types[field_type]
290 self.size = self.packer.size
292 def __call__(self, args):
296 def pack(self, list, kwargs=None):
297 if self.packer.size == 1:
302 b += self.packer.pack(e)
305 def unpack(self, data, offset=0, result=None, ntc=False):
307 # Return a list of arguments
308 if (len(data) - offset) % self.packer.size:
309 raise VPPSerializerValueError(
310 'Legacy Variable Length Array length mismatch.')
311 elements = int((len(data) - offset) / self.packer.size)
313 for e in range(elements):
314 x, size = self.packer.unpack(data, offset, ntc=ntc)
316 offset += self.packer.size
321 class VPPEnumType(object):
322 def __init__(self, name, msgdef):
323 self.size = types['u32'].size
324 self.enumtype = 'u32'
327 if type(f) is dict and 'enumtype' in f:
328 if f['enumtype'] != 'u32':
329 self.size = types[f['enumtype']].size
330 self.enumtype = f['enumtype']
333 e_hash[ename] = evalue
334 self.enum = IntFlag(name, e_hash)
337 def __call__(self, args):
341 def __getattr__(self, name):
342 return self.enum[name]
347 if sys.version[0] == '2':
348 __nonzero__ = __bool__
350 def pack(self, data, kwargs=None):
351 return types[self.enumtype].pack(data)
353 def unpack(self, data, offset=0, result=None, ntc=False):
354 x, size = types[self.enumtype].unpack(data, offset)
355 return self.enum(x), size
358 class VPPUnionType(object):
359 def __init__(self, name, msgdef):
364 self.packers = collections.OrderedDict()
365 for i, f in enumerate(msgdef):
366 if type(f) is dict and 'crc' in f:
370 if f_type not in types:
371 logger.debug('Unknown union type {}'.format(f_type))
372 raise VPPSerializerValueError(
373 'Unknown message type {}'.format(f_type))
374 fields.append(f_name)
375 size = types[f_type].size
376 self.packers[f_name] = types[f_type]
382 self.tuple = collections.namedtuple(name, fields, rename=True)
384 def __call__(self, args):
388 # Union of variable length?
389 def pack(self, data, kwargs=None):
391 return b'\x00' * self.size
393 for k, v in data.items():
394 logger.debug("Key: {} Value: {}".format(k, v))
395 b = self.packers[k].pack(v, kwargs)
397 r = bytearray(self.size)
401 def unpack(self, data, offset=0, result=None, ntc=False):
404 for k, p in self.packers.items():
405 x, size = p.unpack(data, offset, ntc=ntc)
409 return self.tuple._make(r), maxsize
412 class VPPTypeAlias(object):
413 def __init__(self, name, msgdef):
415 t = vpp_get_type(msgdef['type'])
417 raise ValueError('No such type: {}'.format(msgdef['type']))
418 if 'length' in msgdef:
419 if msgdef['length'] == 0:
421 if msgdef['type'] == 'u8':
422 self.packer = FixedList_u8(name, msgdef['type'],
424 self.size = self.packer.size
426 self.packer = FixedList(name, msgdef['type'], msgdef['length'])
432 self.toplevelconversion = False
434 def __call__(self, args):
438 def pack(self, data, kwargs=None):
439 if data and conversion_required(data, self.name):
441 return conversion_packer(data, self.name)
442 # Python 2 and 3 raises different exceptions from inet_pton
443 except(OSError, socket.error, TypeError):
446 return self.packer.pack(data, kwargs)
448 def unpack(self, data, offset=0, result=None, ntc=False):
449 if ntc == False and self.name in vpp_format.conversion_unpacker_table:
450 # Disable type conversion for dependent types
452 self.toplevelconversion = True
453 t, size = self.packer.unpack(data, offset, result, ntc=ntc)
454 if self.toplevelconversion:
455 self.toplevelconversion = False
456 return conversion_unpacker(t, self.name), size
460 class VPPType(object):
461 # Set everything up to be able to pack / unpack
462 def __init__(self, name, msgdef):
468 self.field_by_name = {}
470 for i, f in enumerate(msgdef):
471 if type(f) is dict and 'crc' in f:
474 f_type, f_name = f[:2]
475 self.fields.append(f_name)
476 self.field_by_name[f_name] = None
477 self.fieldtypes.append(f_type)
478 if f_type not in types:
479 logger.debug('Unknown type {}'.format(f_type))
480 raise VPPSerializerValueError(
481 'Unknown message type {}'.format(f_type))
484 options = [x for x in f if type(x) is dict]
486 self.options = options[0]
490 if fieldlen == 3: # list
492 if list_elements == 0:
493 if f_type == 'string':
494 p = String(f_name, 0, self.options)
496 p = VLAList_legacy(f_name, f_type)
497 self.packers.append(p)
499 p = FixedList_u8(f_name, f_type, list_elements)
500 self.packers.append(p)
502 elif f_type == 'string':
503 p = String(f_name, list_elements, self.options)
504 self.packers.append(p)
507 p = FixedList(f_name, f_type, list_elements)
508 self.packers.append(p)
510 elif fieldlen == 4: # Variable length list
511 length_index = self.fields.index(f[3])
512 p = VLAList(f_name, f_type, f[3], length_index)
513 self.packers.append(p)
515 p = types[f_type](self.options)
516 self.packers.append(p)
520 self.tuple = collections.namedtuple(name, self.fields, rename=True)
522 self.toplevelconversion = False
524 def __call__(self, args):
528 def pack(self, data, kwargs=None):
533 # Try one of the format functions
534 if data and conversion_required(data, self.name):
535 return conversion_packer(data, self.name)
537 for i, a in enumerate(self.fields):
538 if data and type(data) is not dict and a not in data:
539 raise VPPSerializerValueError(
540 "Invalid argument: {} expected {}.{}".
541 format(data, self.name, a))
543 # Defaulting to zero.
544 if not data or a not in data: # Default to 0
546 kwarg = None # No default for VLA
549 kwarg = kwargs[a] if a in kwargs else None
550 if isinstance(self.packers[i], VPPType):
551 b += self.packers[i].pack(arg, kwarg)
553 b += self.packers[i].pack(arg, kwargs)
557 def unpack(self, data, offset=0, result=None, ntc=False):
558 # Return a list of arguments
561 if ntc == False and self.name in vpp_format.conversion_unpacker_table:
562 # Disable type conversion for dependent types
564 self.toplevelconversion = True
566 for p in self.packers:
567 x, size = p.unpack(data, offset, result, ntc)
568 if type(x) is tuple and len(x) == 1:
573 t = self.tuple._make(result)
575 if self.toplevelconversion:
576 self.toplevelconversion = False
577 t = conversion_unpacker(t, self.name)
581 class VPPMessage(VPPType):