blob: b04530cd8a926a31ec3925a015471e61dff3491e [file] [log] [blame]
Ole Troana7564e82018-06-12 21:06:44 +02001#
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:
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
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.
14#
Ole Troana7564e82018-06-12 21:06:44 +020015import collections
Ole Troan85465582019-04-30 10:04:36 +020016import logging
Ole Troan85465582019-04-30 10:04:36 +020017import socket
Paul Vinciguerraae8819f2019-06-07 13:35:37 -040018import struct
19import sys
Paul Vinciguerra42bdba82019-03-07 11:26:23 -080020
21if sys.version_info <= (3, 4):
Paul Vinciguerraae8819f2019-06-07 13:35:37 -040022 from aenum import IntEnum # noqa: F401
Ole Troan48ae19e2019-03-07 11:28:32 +010023else:
Paul Vinciguerraae8819f2019-06-07 13:35:37 -040024 from enum import IntEnum # noqa: F401
Paul Vinciguerra42bdba82019-03-07 11:26:23 -080025
26if sys.version_info <= (3, 6):
Paul Vinciguerraae8819f2019-06-07 13:35:37 -040027 from aenum import IntFlag # noqa: F401
Paul Vinciguerra42bdba82019-03-07 11:26:23 -080028else:
Paul Vinciguerra42bdba82019-03-07 11:26:23 -080029
Paul Vinciguerraae8819f2019-06-07 13:35:37 -040030 from enum import IntFlag # noqa: F401
31
32from . import vpp_format # noqa: E402
Ole Troana7564e82018-06-12 21:06:44 +020033
34#
35# Set log-level in application by doing e.g.:
36# logger = logging.getLogger('vpp_serializer')
37# logger.setLevel(logging.DEBUG)
38#
39logger = logging.getLogger(__name__)
40
Ole Troan0bcad322018-12-11 13:04:01 +010041if sys.version[0] == '2':
Ole Troan8006c6a2018-12-17 12:02:26 +010042 def check(d): type(d) is dict
Ole Troan0bcad322018-12-11 13:04:01 +010043else:
Ole Troan8006c6a2018-12-17 12:02:26 +010044 def check(d): type(d) is dict or type(d) is bytes
45
Ole Troan0bcad322018-12-11 13:04:01 +010046
47def conversion_required(data, field_type):
48 if check(data):
49 return False
50 try:
51 if type(data).__name__ in vpp_format.conversion_table[field_type]:
52 return True
53 except KeyError:
54 return False
55
56
57def 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))
61
62
63def conversion_unpacker(data, field_type):
64 if field_type not in vpp_format.conversion_unpacker_table:
65 return data
66 return vpp_format.conversion_unpacker_table[field_type](data)
67
Ole Troana7564e82018-06-12 21:06:44 +020068
Paul Vinciguerra7e713f12018-11-26 12:04:48 -080069class BaseTypes(object):
Ole Troan85465582019-04-30 10:04:36 +020070 def __init__(self, type, elements=0, options=None):
Ole Troana7564e82018-06-12 21:06:44 +020071 base_types = {'u8': '>B',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040072 'i8': '>b',
Ole Troan413f4a52018-11-28 11:36:05 +010073 'string': '>s',
Ole Troana7564e82018-06-12 21:06:44 +020074 'u16': '>H',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040075 'i16': '>h',
Ole Troana7564e82018-06-12 21:06:44 +020076 'u32': '>I',
77 'i32': '>i',
78 'u64': '>Q',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040079 'i64': '>q',
Paul Vinciguerra888640a2019-05-14 21:01:28 -040080 'f64': '=d',
Ole Troanf47e9b62018-10-16 15:14:03 +020081 'bool': '>?',
Ole Troana7564e82018-06-12 21:06:44 +020082 'header': '>HI'}
83
Ole Troan413f4a52018-11-28 11:36:05 +010084 if elements > 0 and (type == 'u8' or type == 'string'):
Ole Troana7564e82018-06-12 21:06:44 +020085 self.packer = struct.Struct('>%ss' % elements)
86 else:
87 self.packer = struct.Struct(base_types[type])
88 self.size = self.packer.size
Ole Troan85465582019-04-30 10:04:36 +020089 self.options = options
90
Ole Troana7564e82018-06-12 21:06:44 +020091 def pack(self, data, kwargs=None):
Ole Troan40dc4b32019-10-22 14:01:53 +020092 if data is None: # Default to zero if not specified
Ole Troan85465582019-04-30 10:04:36 +020093 if self.options and 'default' in self.options:
94 data = self.options['default']
95 else:
96 data = 0
Ole Troana7564e82018-06-12 21:06:44 +020097 return self.packer.pack(data)
98
Ole Troan0bcad322018-12-11 13:04:01 +010099 def unpack(self, data, offset, result=None, ntc=False):
Ole Troanc84cbad2018-09-06 22:58:05 +0200100 return self.packer.unpack_from(data, offset)[0], self.packer.size
Ole Troana7564e82018-06-12 21:06:44 +0200101
102
Ole Troan413f4a52018-11-28 11:36:05 +0100103class String(object):
Ole Troane5ff5a32019-08-23 22:55:18 +0200104 def __init__(self, name, num, options):
105 self.name = name
106 self.num = num
Ole Troan413f4a52018-11-28 11:36:05 +0100107 self.size = 1
108 self.length_field_packer = BaseTypes('u32')
Ole Troane5ff5a32019-08-23 22:55:18 +0200109 self.limit = options['limit'] if 'limit' in options else num
110 self.fixed = True if num else False
111 if self.fixed and not self.limit:
Ole Troan9ac11382019-04-23 17:11:01 +0200112 raise VPPSerializerValueError(
113 "Invalid argument length for: {}, {} maximum {}".
114 format(list, len(list), self.limit))
115
Ole Troane5ff5a32019-08-23 22:55:18 +0200116 def pack(self, list, kwargs=None):
117 if not list:
118 if self.fixed:
119 return b"\x00" * self.limit
120 return self.length_field_packer.pack(0) + b""
121 if self.limit and len(list) > self.limit - 1:
122 raise VPPSerializerValueError(
123 "Invalid argument length for: {}, {} maximum {}".
124 format(list, len(list), self.limit - 1))
125 if self.fixed:
126 return list.encode('ascii').ljust(self.limit, b'\x00')
127 return self.length_field_packer.pack(len(list)) + list.encode('ascii')
Ole Troan413f4a52018-11-28 11:36:05 +0100128
129 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troane5ff5a32019-08-23 22:55:18 +0200130 if self.fixed:
131 p = BaseTypes('u8', self.num)
132 s = p.unpack(data, offset)
133 s2 = s[0].split(b'\0', 1)[0]
134 return (s2.decode('ascii'), self.num)
135
Ole Troan413f4a52018-11-28 11:36:05 +0100136 length, length_field_size = self.length_field_packer.unpack(data,
137 offset)
138 if length == 0:
Ole Troane5ff5a32019-08-23 22:55:18 +0200139 return '', 0
Ole Troan413f4a52018-11-28 11:36:05 +0100140 p = BaseTypes('u8', length)
141 x, size = p.unpack(data, offset + length_field_size)
Ole Troan33a58172019-09-04 09:12:29 +0200142 #x2 = x.split(b'\0', 1)[0]
143 return (x.decode('ascii', errors='replace'), size + length_field_size)
Ole Troan413f4a52018-11-28 11:36:05 +0100144
145
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800146types = {'u8': BaseTypes('u8'), 'u16': BaseTypes('u16'),
147 'u32': BaseTypes('u32'), 'i32': BaseTypes('i32'),
148 'u64': BaseTypes('u64'), 'f64': BaseTypes('f64'),
Ole Troan9ac11382019-04-23 17:11:01 +0200149 'bool': BaseTypes('bool'), 'string': String}
Ole Troana7564e82018-06-12 21:06:44 +0200150
Ole Troan40dc4b32019-10-22 14:01:53 +0200151class_types = {}
Ole Troana7564e82018-06-12 21:06:44 +0200152
Ole Troan0685da42018-10-16 14:42:50 +0200153def vpp_get_type(name):
154 try:
155 return types[name]
156 except KeyError:
157 return None
158
159
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800160class VPPSerializerValueError(ValueError):
161 pass
162
163
Paul Vinciguerra7e713f12018-11-26 12:04:48 -0800164class FixedList_u8(object):
Ole Troana7564e82018-06-12 21:06:44 +0200165 def __init__(self, name, field_type, num):
166 self.name = name
167 self.num = num
168 self.packer = BaseTypes(field_type, num)
169 self.size = self.packer.size
Ole Troan413f4a52018-11-28 11:36:05 +0100170 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200171
Ole Troan0bcad322018-12-11 13:04:01 +0100172 def pack(self, data, kwargs=None):
Ole Troana7564e82018-06-12 21:06:44 +0200173 """Packs a fixed length bytestring. Left-pads with zeros
174 if input data is too short."""
Ole Troan0bcad322018-12-11 13:04:01 +0100175 if not data:
Ole Troan31555a32018-10-22 09:30:26 +0200176 return b'\x00' * self.size
Ole Troan0bcad322018-12-11 13:04:01 +0100177
178 if len(data) > self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800179 raise VPPSerializerValueError(
180 'Fixed list length error for "{}", got: {}'
181 ' expected: {}'
Ole Troan0bcad322018-12-11 13:04:01 +0100182 .format(self.name, len(data), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200183
Ole Troan64e978b2019-10-17 21:40:36 +0200184 try:
185 return self.packer.pack(data)
186 except struct.error:
187 raise VPPSerializerValueError(
188 'Packing failed for "{}" {}'
189 .format(self.name, kwargs))
Ole Troan0bcad322018-12-11 13:04:01 +0100190 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200191 if len(data[offset:]) < self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800192 raise VPPSerializerValueError(
193 'Invalid array length for "{}" got {}'
194 ' expected {}'
195 .format(self.name, len(data[offset:]), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200196 return self.packer.unpack(data, offset)
197
198
Paul Vinciguerra7e713f12018-11-26 12:04:48 -0800199class FixedList(object):
Ole Troana7564e82018-06-12 21:06:44 +0200200 def __init__(self, name, field_type, num):
201 self.num = num
202 self.packer = types[field_type]
203 self.size = self.packer.size * num
Ole Troan0bcad322018-12-11 13:04:01 +0100204 self.name = name
205 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200206
207 def pack(self, list, kwargs):
Ole Troana7564e82018-06-12 21:06:44 +0200208 if len(list) != self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800209 raise VPPSerializerValueError(
210 'Fixed list length error, got: {} expected: {}'
211 .format(len(list), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200212 b = bytes()
213 for e in list:
214 b += self.packer.pack(e)
215 return b
216
Ole Troan0bcad322018-12-11 13:04:01 +0100217 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200218 # Return a list of arguments
219 result = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200220 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200221 for e in range(self.num):
Ole Troan0bcad322018-12-11 13:04:01 +0100222 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200223 result.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200224 offset += size
225 total += size
226 return result, total
Ole Troana7564e82018-06-12 21:06:44 +0200227
228
Paul Vinciguerra7e713f12018-11-26 12:04:48 -0800229class VLAList(object):
Ole Troana7564e82018-06-12 21:06:44 +0200230 def __init__(self, name, field_type, len_field_name, index):
Ole Troanc84cbad2018-09-06 22:58:05 +0200231 self.name = name
Ole Troan413f4a52018-11-28 11:36:05 +0100232 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200233 self.index = index
234 self.packer = types[field_type]
235 self.size = self.packer.size
236 self.length_field = len_field_name
237
Ole Troan22674292019-10-21 18:59:11 +0200238 def pack(self, lst, kwargs=None):
239 if not lst:
Ole Troan31555a32018-10-22 09:30:26 +0200240 return b""
Ole Troan22674292019-10-21 18:59:11 +0200241 if len(lst) != kwargs[self.length_field]:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800242 raise VPPSerializerValueError(
243 'Variable length error, got: {} expected: {}'
Ole Troan22674292019-10-21 18:59:11 +0200244 .format(len(lst), kwargs[self.length_field]))
Ole Troana7564e82018-06-12 21:06:44 +0200245
246 # u8 array
247 if self.packer.size == 1:
Ole Troan22674292019-10-21 18:59:11 +0200248 if isinstance(lst, list):
249 return b''.join(lst)
250 return bytes(lst)
Ole Troana7564e82018-06-12 21:06:44 +0200251
Ole Troan22674292019-10-21 18:59:11 +0200252 b = bytes()
253 for e in lst:
Ole Troana7564e82018-06-12 21:06:44 +0200254 b += self.packer.pack(e)
255 return b
256
Ole Troan0bcad322018-12-11 13:04:01 +0100257 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200258 # Return a list of arguments
Ole Troanc84cbad2018-09-06 22:58:05 +0200259 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200260
261 # u8 array
262 if self.packer.size == 1:
263 if result[self.index] == 0:
Ole Troanc84cbad2018-09-06 22:58:05 +0200264 return b'', 0
Ole Troana7564e82018-06-12 21:06:44 +0200265 p = BaseTypes('u8', result[self.index])
Ole Troan0bcad322018-12-11 13:04:01 +0100266 return p.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200267
268 r = []
269 for e in range(result[self.index]):
Ole Troan0bcad322018-12-11 13:04:01 +0100270 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200271 r.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200272 offset += size
273 total += size
274 return r, total
Ole Troana7564e82018-06-12 21:06:44 +0200275
276
277class VLAList_legacy():
278 def __init__(self, name, field_type):
279 self.packer = types[field_type]
280 self.size = self.packer.size
281
282 def pack(self, list, kwargs=None):
Ole Troana7564e82018-06-12 21:06:44 +0200283 if self.packer.size == 1:
284 return bytes(list)
285
286 b = bytes()
287 for e in list:
288 b += self.packer.pack(e)
289 return b
290
Ole Troan0bcad322018-12-11 13:04:01 +0100291 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troanc84cbad2018-09-06 22:58:05 +0200292 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200293 # Return a list of arguments
294 if (len(data) - offset) % self.packer.size:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800295 raise VPPSerializerValueError(
296 'Legacy Variable Length Array length mismatch.')
Ole Troana7564e82018-06-12 21:06:44 +0200297 elements = int((len(data) - offset) / self.packer.size)
298 r = []
Ole Troana7564e82018-06-12 21:06:44 +0200299 for e in range(elements):
Ole Troan0bcad322018-12-11 13:04:01 +0100300 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200301 r.append(x)
302 offset += self.packer.size
Ole Troanc84cbad2018-09-06 22:58:05 +0200303 total += size
304 return r, total
Ole Troana7564e82018-06-12 21:06:44 +0200305
306
Paul Vinciguerra7e713f12018-11-26 12:04:48 -0800307class VPPEnumType(object):
Ole Troan40dc4b32019-10-22 14:01:53 +0200308 def __init__(self, name, msgdef, options=None):
Ole Troana7564e82018-06-12 21:06:44 +0200309 self.size = types['u32'].size
Ole Troan40dc4b32019-10-22 14:01:53 +0200310 self.name = name
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100311 self.enumtype = 'u32'
Ole Troan40dc4b32019-10-22 14:01:53 +0200312 self.msgdef = msgdef
Ole Troana7564e82018-06-12 21:06:44 +0200313 e_hash = {}
314 for f in msgdef:
315 if type(f) is dict and 'enumtype' in f:
316 if f['enumtype'] != 'u32':
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100317 self.size = types[f['enumtype']].size
318 self.enumtype = f['enumtype']
Ole Troana7564e82018-06-12 21:06:44 +0200319 continue
320 ename, evalue = f
321 e_hash[ename] = evalue
Ole Troan48ae19e2019-03-07 11:28:32 +0100322 self.enum = IntFlag(name, e_hash)
Ole Troana7564e82018-06-12 21:06:44 +0200323 types[name] = self
Ole Troan40dc4b32019-10-22 14:01:53 +0200324 class_types[name] = VPPEnumType
325 self.options = options
Ole Troan85465582019-04-30 10:04:36 +0200326
Ole Troana7564e82018-06-12 21:06:44 +0200327 def __getattr__(self, name):
328 return self.enum[name]
329
Paul Vinciguerraa089ae12019-07-08 15:41:07 -0400330 def __bool__(self):
Ole Troan0685da42018-10-16 14:42:50 +0200331 return True
332
Paul Vinciguerraa089ae12019-07-08 15:41:07 -0400333 if sys.version[0] == '2':
334 __nonzero__ = __bool__
335
Ole Troana7564e82018-06-12 21:06:44 +0200336 def pack(self, data, kwargs=None):
Ole Troan40dc4b32019-10-22 14:01:53 +0200337 if data is None: # Default to zero if not specified
338 if self.options and 'default' in self.options:
339 data = self.options['default']
340 else:
341 data = 0
342
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100343 return types[self.enumtype].pack(data)
Ole Troana7564e82018-06-12 21:06:44 +0200344
Ole Troan0bcad322018-12-11 13:04:01 +0100345 def unpack(self, data, offset=0, result=None, ntc=False):
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100346 x, size = types[self.enumtype].unpack(data, offset)
Ole Troanc84cbad2018-09-06 22:58:05 +0200347 return self.enum(x), size
Ole Troana7564e82018-06-12 21:06:44 +0200348
349
Paul Vinciguerra7e713f12018-11-26 12:04:48 -0800350class VPPUnionType(object):
Ole Troana7564e82018-06-12 21:06:44 +0200351 def __init__(self, name, msgdef):
352 self.name = name
353 self.size = 0
354 self.maxindex = 0
355 fields = []
356 self.packers = collections.OrderedDict()
357 for i, f in enumerate(msgdef):
358 if type(f) is dict and 'crc' in f:
359 self.crc = f['crc']
360 continue
361 f_type, f_name = f
362 if f_type not in types:
363 logger.debug('Unknown union type {}'.format(f_type))
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800364 raise VPPSerializerValueError(
365 'Unknown message type {}'.format(f_type))
Ole Troana7564e82018-06-12 21:06:44 +0200366 fields.append(f_name)
367 size = types[f_type].size
368 self.packers[f_name] = types[f_type]
369 if size > self.size:
370 self.size = size
371 self.maxindex = i
372
373 types[name] = self
374 self.tuple = collections.namedtuple(name, fields, rename=True)
Ole Troana7564e82018-06-12 21:06:44 +0200375
Ole Troan31555a32018-10-22 09:30:26 +0200376 # Union of variable length?
Ole Troana7564e82018-06-12 21:06:44 +0200377 def pack(self, data, kwargs=None):
Ole Troan31555a32018-10-22 09:30:26 +0200378 if not data:
379 return b'\x00' * self.size
380
Ole Troana7564e82018-06-12 21:06:44 +0200381 for k, v in data.items():
382 logger.debug("Key: {} Value: {}".format(k, v))
383 b = self.packers[k].pack(v, kwargs)
Ole Troana7564e82018-06-12 21:06:44 +0200384 break
385 r = bytearray(self.size)
Ole Troanb199e982018-08-02 19:19:21 +0200386 r[:len(b)] = b
Ole Troana7564e82018-06-12 21:06:44 +0200387 return r
388
Ole Troan0bcad322018-12-11 13:04:01 +0100389 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200390 r = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200391 maxsize = 0
Ole Troana7564e82018-06-12 21:06:44 +0200392 for k, p in self.packers.items():
Ole Troan0bcad322018-12-11 13:04:01 +0100393 x, size = p.unpack(data, offset, ntc=ntc)
Ole Troanc84cbad2018-09-06 22:58:05 +0200394 if size > maxsize:
395 maxsize = size
396 r.append(x)
397 return self.tuple._make(r), maxsize
Ole Troana7564e82018-06-12 21:06:44 +0200398
399
Ole Troan0bcad322018-12-11 13:04:01 +0100400class VPPTypeAlias(object):
401 def __init__(self, name, msgdef):
402 self.name = name
403 t = vpp_get_type(msgdef['type'])
404 if not t:
Ole Troan75761b92019-09-11 17:49:08 +0200405 raise ValueError('No such type: {}'.format(msgdef['type']))
Ole Troan0bcad322018-12-11 13:04:01 +0100406 if 'length' in msgdef:
407 if msgdef['length'] == 0:
408 raise ValueError()
409 if msgdef['type'] == 'u8':
410 self.packer = FixedList_u8(name, msgdef['type'],
411 msgdef['length'])
412 self.size = self.packer.size
413 else:
414 self.packer = FixedList(name, msgdef['type'], msgdef['length'])
Ole Troan8c8acc02018-11-27 10:05:23 +0100415 else:
Ole Troan0bcad322018-12-11 13:04:01 +0100416 self.packer = t
417 self.size = t.size
418
419 types[name] = self
Ole Troan75761b92019-09-11 17:49:08 +0200420 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100421
422 def pack(self, data, kwargs=None):
423 if data and conversion_required(data, self.name):
424 try:
425 return conversion_packer(data, self.name)
426 # Python 2 and 3 raises different exceptions from inet_pton
427 except(OSError, socket.error, TypeError):
428 pass
429
430 return self.packer.pack(data, kwargs)
431
432 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troan75761b92019-09-11 17:49:08 +0200433 if ntc == False and self.name in vpp_format.conversion_unpacker_table:
434 # Disable type conversion for dependent types
435 ntc = True
436 self.toplevelconversion = True
Ole Troan0bcad322018-12-11 13:04:01 +0100437 t, size = self.packer.unpack(data, offset, result, ntc=ntc)
Ole Troan75761b92019-09-11 17:49:08 +0200438 if self.toplevelconversion:
439 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100440 return conversion_unpacker(t, self.name), size
441 return t, size
Ole Troan53fffa12018-11-13 12:36:56 +0100442
443
Paul Vinciguerra7e713f12018-11-26 12:04:48 -0800444class VPPType(object):
Ole Troana7564e82018-06-12 21:06:44 +0200445 # Set everything up to be able to pack / unpack
446 def __init__(self, name, msgdef):
447 self.name = name
448 self.msgdef = msgdef
449 self.packers = []
450 self.fields = []
451 self.fieldtypes = []
452 self.field_by_name = {}
453 size = 0
454 for i, f in enumerate(msgdef):
455 if type(f) is dict and 'crc' in f:
456 self.crc = f['crc']
457 continue
458 f_type, f_name = f[:2]
459 self.fields.append(f_name)
460 self.field_by_name[f_name] = None
461 self.fieldtypes.append(f_type)
462 if f_type not in types:
463 logger.debug('Unknown type {}'.format(f_type))
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800464 raise VPPSerializerValueError(
465 'Unknown message type {}'.format(f_type))
Ole Troan9ac11382019-04-23 17:11:01 +0200466
Ole Troan85465582019-04-30 10:04:36 +0200467 fieldlen = len(f)
Ole Troan9ac11382019-04-23 17:11:01 +0200468 options = [x for x in f if type(x) is dict]
469 if len(options):
470 self.options = options[0]
Ole Troan85465582019-04-30 10:04:36 +0200471 fieldlen -= 1
Ole Troan9ac11382019-04-23 17:11:01 +0200472 else:
473 self.options = {}
Ole Troan85465582019-04-30 10:04:36 +0200474 if fieldlen == 3: # list
Ole Troana7564e82018-06-12 21:06:44 +0200475 list_elements = f[2]
476 if list_elements == 0:
Ole Troane5ff5a32019-08-23 22:55:18 +0200477 if f_type == 'string':
478 p = String(f_name, 0, self.options)
479 else:
480 p = VLAList_legacy(f_name, f_type)
Ole Troana7564e82018-06-12 21:06:44 +0200481 self.packers.append(p)
Ole Troane5ff5a32019-08-23 22:55:18 +0200482 elif f_type == 'u8':
Ole Troana7564e82018-06-12 21:06:44 +0200483 p = FixedList_u8(f_name, f_type, list_elements)
484 self.packers.append(p)
485 size += p.size
Ole Troane5ff5a32019-08-23 22:55:18 +0200486 elif f_type == 'string':
487 p = String(f_name, list_elements, self.options)
488 self.packers.append(p)
489 size += p.size
Ole Troana7564e82018-06-12 21:06:44 +0200490 else:
491 p = FixedList(f_name, f_type, list_elements)
492 self.packers.append(p)
493 size += p.size
Ole Troan85465582019-04-30 10:04:36 +0200494 elif fieldlen == 4: # Variable length list
Ole Troan413f4a52018-11-28 11:36:05 +0100495 length_index = self.fields.index(f[3])
496 p = VLAList(f_name, f_type, f[3], length_index)
497 self.packers.append(p)
Ole Troana7564e82018-06-12 21:06:44 +0200498 else:
Ole Troan40dc4b32019-10-22 14:01:53 +0200499 # Support default for basetypes and enums
500 if 'default' in self.options:
501 try:
502 p = BaseTypes(f_type, 0, self.options)
503 except KeyError:
504 p = class_types[f_type](f_name, types[f_type].msgdef, self.options)
505 else:
506 p = types[f_type]
Ole Troan9ac11382019-04-23 17:11:01 +0200507 self.packers.append(p)
508 size += p.size
Ole Troana7564e82018-06-12 21:06:44 +0200509
510 self.size = size
511 self.tuple = collections.namedtuple(name, self.fields, rename=True)
512 types[name] = self
Ole Troan75761b92019-09-11 17:49:08 +0200513 self.toplevelconversion = False
Ole Troana7564e82018-06-12 21:06:44 +0200514
515 def pack(self, data, kwargs=None):
516 if not kwargs:
517 kwargs = data
Ole Troana7564e82018-06-12 21:06:44 +0200518 b = bytes()
Ole Troan31555a32018-10-22 09:30:26 +0200519
Ole Troan0bcad322018-12-11 13:04:01 +0100520 # Try one of the format functions
521 if data and conversion_required(data, self.name):
522 return conversion_packer(data, self.name)
523
524 for i, a in enumerate(self.fields):
Ole Troan31555a32018-10-22 09:30:26 +0200525 if data and type(data) is not dict and a not in data:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800526 raise VPPSerializerValueError(
527 "Invalid argument: {} expected {}.{}".
528 format(data, self.name, a))
Ole Troan31555a32018-10-22 09:30:26 +0200529
530 # Defaulting to zero.
531 if not data or a not in data: # Default to 0
532 arg = None
533 kwarg = None # No default for VLA
534 else:
535 arg = data[a]
536 kwarg = kwargs[a] if a in kwargs else None
Ole Troana7564e82018-06-12 21:06:44 +0200537 if isinstance(self.packers[i], VPPType):
Ole Troan0bcad322018-12-11 13:04:01 +0100538 b += self.packers[i].pack(arg, kwarg)
Ole Troana7564e82018-06-12 21:06:44 +0200539 else:
Ole Troan31555a32018-10-22 09:30:26 +0200540 b += self.packers[i].pack(arg, kwargs)
541
Ole Troana7564e82018-06-12 21:06:44 +0200542 return b
543
Ole Troan0bcad322018-12-11 13:04:01 +0100544 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200545 # Return a list of arguments
546 result = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200547 total = 0
Ole Troan75761b92019-09-11 17:49:08 +0200548 if ntc == False and self.name in vpp_format.conversion_unpacker_table:
549 # Disable type conversion for dependent types
550 ntc = True
551 self.toplevelconversion = True
552
Ole Troana7564e82018-06-12 21:06:44 +0200553 for p in self.packers:
Ole Troan0bcad322018-12-11 13:04:01 +0100554 x, size = p.unpack(data, offset, result, ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200555 if type(x) is tuple and len(x) == 1:
556 x = x[0]
557 result.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200558 offset += size
559 total += size
560 t = self.tuple._make(result)
Ole Troan75761b92019-09-11 17:49:08 +0200561
562 if self.toplevelconversion:
563 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100564 t = conversion_unpacker(t, self.name)
Ole Troanc84cbad2018-09-06 22:58:05 +0200565 return t, total
Ole Troana7564e82018-06-12 21:06:44 +0200566
567
568class VPPMessage(VPPType):
569 pass