blob: 81ce53e378d4c395895a8bd75a9fd74a41ab13e0 [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
Paul Vinciguerra2e876062020-05-12 10:45:17 -040016from enum import IntFlag
Ole Troan85465582019-04-30 10:04:36 +020017import logging
Ole Troan85465582019-04-30 10:04:36 +020018import socket
Paul Vinciguerraae8819f2019-06-07 13:35:37 -040019import struct
20import sys
Paul Vinciguerra42bdba82019-03-07 11:26:23 -080021
Paul Vinciguerra2e876062020-05-12 10:45:17 -040022from . import vpp_format
Paul Vinciguerra42bdba82019-03-07 11:26:23 -080023
Ole Troana7564e82018-06-12 21:06:44 +020024
25#
26# Set log-level in application by doing e.g.:
27# logger = logging.getLogger('vpp_serializer')
28# logger.setLevel(logging.DEBUG)
29#
Paul Vinciguerra5395c6a2020-12-02 17:43:59 -050030logger = logging.getLogger('vpp_papi.serializer')
Ole Troana7564e82018-06-12 21:06:44 +020031
Paul Vinciguerrad7adc292020-12-02 14:34:27 -050032
33def check(d):
34 return type(d) is dict or type(d) is bytes
Ole Troan8006c6a2018-12-17 12:02:26 +010035
Ole Troan0bcad322018-12-11 13:04:01 +010036
37def conversion_required(data, field_type):
38 if check(data):
39 return False
40 try:
41 if type(data).__name__ in vpp_format.conversion_table[field_type]:
42 return True
43 except KeyError:
44 return False
45
46
47def conversion_packer(data, field_type):
48 t = type(data).__name__
49 return types[field_type].pack(vpp_format.
50 conversion_table[field_type][t](data))
51
52
53def conversion_unpacker(data, field_type):
54 if field_type not in vpp_format.conversion_unpacker_table:
55 return data
56 return vpp_format.conversion_unpacker_table[field_type](data)
57
Ole Troana7564e82018-06-12 21:06:44 +020058
Paul Vinciguerrad7adc292020-12-02 14:34:27 -050059class Packer:
Ole Troan418ebb72019-11-19 04:38:20 +010060 options = {}
61
62 def pack(self, data, kwargs):
63 raise NotImplementedError
64
65 def unpack(self, data, offset, result=None, ntc=False):
66 raise NotImplementedError
67
68 # override as appropriate in subclasses
Ole Troanda47f672019-11-24 15:22:55 +010069 @staticmethod
70 def _get_packer_with_options(f_type, options):
Ole Troan418ebb72019-11-19 04:38:20 +010071 return types[f_type]
72
73 def get_packer_with_options(self, f_type, options):
74 if options is not None:
75 try:
Ole Troanda47f672019-11-24 15:22:55 +010076 c = types[f_type].__class__
77 return c._get_packer_with_options(f_type, options)
Ole Troan418ebb72019-11-19 04:38:20 +010078 except IndexError:
79 raise VPPSerializerValueError(
80 "Options not supported for {}{} ({})".
Ole Troanda47f672019-11-24 15:22:55 +010081 format(f_type, types[f_type].__class__,
82 options))
Ole Troan418ebb72019-11-19 04:38:20 +010083
84
85class BaseTypes(Packer):
Ole Troan85465582019-04-30 10:04:36 +020086 def __init__(self, type, elements=0, options=None):
Paul Vinciguerra14b0b472019-11-23 23:49:57 -050087 self._type = type
88 self._elements = elements
Ole Troana7564e82018-06-12 21:06:44 +020089 base_types = {'u8': '>B',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040090 'i8': '>b',
Ole Troan413f4a52018-11-28 11:36:05 +010091 'string': '>s',
Ole Troana7564e82018-06-12 21:06:44 +020092 'u16': '>H',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040093 'i16': '>h',
Ole Troana7564e82018-06-12 21:06:44 +020094 'u32': '>I',
95 'i32': '>i',
96 'u64': '>Q',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040097 'i64': '>q',
Paul Vinciguerra888640a2019-05-14 21:01:28 -040098 'f64': '=d',
Ole Troanf47e9b62018-10-16 15:14:03 +020099 'bool': '>?',
Ole Troana7564e82018-06-12 21:06:44 +0200100 'header': '>HI'}
101
Ole Troan413f4a52018-11-28 11:36:05 +0100102 if elements > 0 and (type == 'u8' or type == 'string'):
Ole Troana7564e82018-06-12 21:06:44 +0200103 self.packer = struct.Struct('>%ss' % elements)
104 else:
105 self.packer = struct.Struct(base_types[type])
106 self.size = self.packer.size
Ole Troan85465582019-04-30 10:04:36 +0200107 self.options = options
108
Ole Troana7564e82018-06-12 21:06:44 +0200109 def pack(self, data, kwargs=None):
Ole Troan40dc4b32019-10-22 14:01:53 +0200110 if data is None: # Default to zero if not specified
Ole Troan85465582019-04-30 10:04:36 +0200111 if self.options and 'default' in self.options:
112 data = self.options['default']
113 else:
114 data = 0
Ole Troana7564e82018-06-12 21:06:44 +0200115 return self.packer.pack(data)
116
Ole Troan0bcad322018-12-11 13:04:01 +0100117 def unpack(self, data, offset, result=None, ntc=False):
Ole Troanc84cbad2018-09-06 22:58:05 +0200118 return self.packer.unpack_from(data, offset)[0], self.packer.size
Ole Troana7564e82018-06-12 21:06:44 +0200119
Ole Troanda47f672019-11-24 15:22:55 +0100120 @staticmethod
121 def _get_packer_with_options(f_type, options):
122 return BaseTypes(f_type, options=options)
Ole Troana7564e82018-06-12 21:06:44 +0200123
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500124 def __repr__(self):
125 return "BaseTypes(type=%s, elements=%s, options=%s)" % (self._type,
126 self._elements,
127 self.options)
128
Ole Troan418ebb72019-11-19 04:38:20 +0100129
130class String(Packer):
Ole Troane5ff5a32019-08-23 22:55:18 +0200131 def __init__(self, name, num, options):
132 self.name = name
133 self.num = num
Ole Troan413f4a52018-11-28 11:36:05 +0100134 self.size = 1
135 self.length_field_packer = BaseTypes('u32')
Ole Troane5ff5a32019-08-23 22:55:18 +0200136 self.limit = options['limit'] if 'limit' in options else num
137 self.fixed = True if num else False
138 if self.fixed and not self.limit:
Ole Troan9ac11382019-04-23 17:11:01 +0200139 raise VPPSerializerValueError(
Paul Vinciguerracebed412020-12-01 23:45:38 -0500140 "Invalid combination for: {}, {} fixed:{} limit:{}".
141 format(name, options, self.fixed, self.limit))
Ole Troan9ac11382019-04-23 17:11:01 +0200142
Ole Troane5ff5a32019-08-23 22:55:18 +0200143 def pack(self, list, kwargs=None):
144 if not list:
145 if self.fixed:
146 return b"\x00" * self.limit
147 return self.length_field_packer.pack(0) + b""
148 if self.limit and len(list) > self.limit - 1:
149 raise VPPSerializerValueError(
150 "Invalid argument length for: {}, {} maximum {}".
151 format(list, len(list), self.limit - 1))
152 if self.fixed:
153 return list.encode('ascii').ljust(self.limit, b'\x00')
154 return self.length_field_packer.pack(len(list)) + list.encode('ascii')
Ole Troan413f4a52018-11-28 11:36:05 +0100155
156 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troane5ff5a32019-08-23 22:55:18 +0200157 if self.fixed:
158 p = BaseTypes('u8', self.num)
159 s = p.unpack(data, offset)
160 s2 = s[0].split(b'\0', 1)[0]
161 return (s2.decode('ascii'), self.num)
162
Ole Troan413f4a52018-11-28 11:36:05 +0100163 length, length_field_size = self.length_field_packer.unpack(data,
164 offset)
165 if length == 0:
Ole Troane5ff5a32019-08-23 22:55:18 +0200166 return '', 0
Ole Troan413f4a52018-11-28 11:36:05 +0100167 p = BaseTypes('u8', length)
168 x, size = p.unpack(data, offset + length_field_size)
Ole Troan33a58172019-09-04 09:12:29 +0200169 return (x.decode('ascii', errors='replace'), size + length_field_size)
Ole Troan413f4a52018-11-28 11:36:05 +0100170
171
Paul Vinciguerraba2c7fa2019-11-23 21:02:27 -0500172types = {'u8': BaseTypes('u8'), 'i8': BaseTypes('i8'),
173 'u16': BaseTypes('u16'), 'i16': BaseTypes('i16'),
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800174 'u32': BaseTypes('u32'), 'i32': BaseTypes('i32'),
Paul Vinciguerraba2c7fa2019-11-23 21:02:27 -0500175 'u64': BaseTypes('u64'), 'i64': BaseTypes('i64'),
176 'f64': BaseTypes('f64'),
Ole Troan9ac11382019-04-23 17:11:01 +0200177 'bool': BaseTypes('bool'), 'string': String}
Ole Troana7564e82018-06-12 21:06:44 +0200178
Ole Troan40dc4b32019-10-22 14:01:53 +0200179class_types = {}
Ole Troana7564e82018-06-12 21:06:44 +0200180
Ole Troan418ebb72019-11-19 04:38:20 +0100181
Ole Troan0685da42018-10-16 14:42:50 +0200182def vpp_get_type(name):
183 try:
184 return types[name]
185 except KeyError:
186 return None
187
188
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800189class VPPSerializerValueError(ValueError):
190 pass
191
192
Ole Troan418ebb72019-11-19 04:38:20 +0100193class FixedList_u8(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200194 def __init__(self, name, field_type, num):
195 self.name = name
196 self.num = num
197 self.packer = BaseTypes(field_type, num)
198 self.size = self.packer.size
Ole Troan413f4a52018-11-28 11:36:05 +0100199 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200200
Ole Troan0bcad322018-12-11 13:04:01 +0100201 def pack(self, data, kwargs=None):
Ole Troana7564e82018-06-12 21:06:44 +0200202 """Packs a fixed length bytestring. Left-pads with zeros
203 if input data is too short."""
Ole Troan0bcad322018-12-11 13:04:01 +0100204 if not data:
Ole Troan31555a32018-10-22 09:30:26 +0200205 return b'\x00' * self.size
Ole Troan0bcad322018-12-11 13:04:01 +0100206
207 if len(data) > self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800208 raise VPPSerializerValueError(
209 'Fixed list length error for "{}", got: {}'
210 ' expected: {}'
Ole Troan0bcad322018-12-11 13:04:01 +0100211 .format(self.name, len(data), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200212
Ole Troan64e978b2019-10-17 21:40:36 +0200213 try:
214 return self.packer.pack(data)
215 except struct.error:
216 raise VPPSerializerValueError(
217 'Packing failed for "{}" {}'
218 .format(self.name, kwargs))
Ole Troan418ebb72019-11-19 04:38:20 +0100219
Ole Troan0bcad322018-12-11 13:04:01 +0100220 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200221 if len(data[offset:]) < self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800222 raise VPPSerializerValueError(
223 'Invalid array length for "{}" got {}'
224 ' expected {}'
225 .format(self.name, len(data[offset:]), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200226 return self.packer.unpack(data, offset)
227
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500228 def __repr__(self):
229 return "FixedList_u8(name=%s, field_type=%s, num=%s)" % (
230 self.name, self.field_type, self.num
231 )
232
Ole Troana7564e82018-06-12 21:06:44 +0200233
Ole Troan418ebb72019-11-19 04:38:20 +0100234class FixedList(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200235 def __init__(self, name, field_type, num):
236 self.num = num
237 self.packer = types[field_type]
238 self.size = self.packer.size * num
Ole Troan0bcad322018-12-11 13:04:01 +0100239 self.name = name
240 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200241
242 def pack(self, list, kwargs):
Ole Troana7564e82018-06-12 21:06:44 +0200243 if len(list) != self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800244 raise VPPSerializerValueError(
245 'Fixed list length error, got: {} expected: {}'
246 .format(len(list), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200247 b = bytes()
248 for e in list:
249 b += self.packer.pack(e)
250 return b
251
Ole Troan0bcad322018-12-11 13:04:01 +0100252 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200253 # Return a list of arguments
254 result = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200255 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200256 for e in range(self.num):
Ole Troan0bcad322018-12-11 13:04:01 +0100257 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200258 result.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200259 offset += size
260 total += size
261 return result, total
Ole Troana7564e82018-06-12 21:06:44 +0200262
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500263 def __repr__(self):
Paul Vinciguerra99fbf052019-11-26 14:15:53 -0500264 return "FixedList(name=%s, field_type=%s, num=%s)" % (
Ole Troanda47f672019-11-24 15:22:55 +0100265 self.name, self.field_type, self.num)
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500266
Ole Troana7564e82018-06-12 21:06:44 +0200267
Ole Troan418ebb72019-11-19 04:38:20 +0100268class VLAList(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200269 def __init__(self, name, field_type, len_field_name, index):
Ole Troanc84cbad2018-09-06 22:58:05 +0200270 self.name = name
Ole Troan413f4a52018-11-28 11:36:05 +0100271 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200272 self.index = index
273 self.packer = types[field_type]
274 self.size = self.packer.size
275 self.length_field = len_field_name
276
Ole Troan22674292019-10-21 18:59:11 +0200277 def pack(self, lst, kwargs=None):
278 if not lst:
Ole Troan31555a32018-10-22 09:30:26 +0200279 return b""
Ole Troan22674292019-10-21 18:59:11 +0200280 if len(lst) != kwargs[self.length_field]:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800281 raise VPPSerializerValueError(
282 'Variable length error, got: {} expected: {}'
Ole Troan22674292019-10-21 18:59:11 +0200283 .format(len(lst), kwargs[self.length_field]))
Ole Troana7564e82018-06-12 21:06:44 +0200284
285 # u8 array
286 if self.packer.size == 1:
Ole Troan22674292019-10-21 18:59:11 +0200287 if isinstance(lst, list):
288 return b''.join(lst)
289 return bytes(lst)
Ole Troana7564e82018-06-12 21:06:44 +0200290
Ole Troan22674292019-10-21 18:59:11 +0200291 b = bytes()
292 for e in lst:
Ole Troana7564e82018-06-12 21:06:44 +0200293 b += self.packer.pack(e)
294 return b
295
Ole Troan0bcad322018-12-11 13:04:01 +0100296 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200297 # Return a list of arguments
Ole Troanc84cbad2018-09-06 22:58:05 +0200298 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200299
300 # u8 array
301 if self.packer.size == 1:
302 if result[self.index] == 0:
Ole Troanc84cbad2018-09-06 22:58:05 +0200303 return b'', 0
Ole Troana7564e82018-06-12 21:06:44 +0200304 p = BaseTypes('u8', result[self.index])
Ole Troan0bcad322018-12-11 13:04:01 +0100305 return p.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200306
307 r = []
308 for e in range(result[self.index]):
Ole Troan0bcad322018-12-11 13:04:01 +0100309 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200310 r.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200311 offset += size
312 total += size
313 return r, total
Ole Troana7564e82018-06-12 21:06:44 +0200314
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500315 def __repr__(self):
316 return "VLAList(name=%s, field_type=%s, " \
317 "len_field_name=%s, index=%s)" % (
Ole Troanda47f672019-11-24 15:22:55 +0100318 self.name, self.field_type, self.length_field, self.index
319 )
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500320
Ole Troana7564e82018-06-12 21:06:44 +0200321
Ole Troan418ebb72019-11-19 04:38:20 +0100322class VLAList_legacy(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200323 def __init__(self, name, field_type):
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500324 self.name = name
325 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200326 self.packer = types[field_type]
327 self.size = self.packer.size
328
329 def pack(self, list, kwargs=None):
Ole Troana7564e82018-06-12 21:06:44 +0200330 if self.packer.size == 1:
331 return bytes(list)
332
333 b = bytes()
334 for e in list:
335 b += self.packer.pack(e)
336 return b
337
Ole Troan0bcad322018-12-11 13:04:01 +0100338 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troanc84cbad2018-09-06 22:58:05 +0200339 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200340 # Return a list of arguments
341 if (len(data) - offset) % self.packer.size:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800342 raise VPPSerializerValueError(
343 'Legacy Variable Length Array length mismatch.')
Ole Troana7564e82018-06-12 21:06:44 +0200344 elements = int((len(data) - offset) / self.packer.size)
345 r = []
Ole Troana7564e82018-06-12 21:06:44 +0200346 for e in range(elements):
Ole Troan0bcad322018-12-11 13:04:01 +0100347 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200348 r.append(x)
349 offset += self.packer.size
Ole Troanc84cbad2018-09-06 22:58:05 +0200350 total += size
351 return r, total
Ole Troana7564e82018-06-12 21:06:44 +0200352
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500353 def __repr__(self):
354 return "VLAList_legacy(name=%s, field_type=%s)" % (
355 self.name, self.field_type
356 )
357
Ole Troana7564e82018-06-12 21:06:44 +0200358
Ole Troan418ebb72019-11-19 04:38:20 +0100359class VPPEnumType(Packer):
Ole Troan40dc4b32019-10-22 14:01:53 +0200360 def __init__(self, name, msgdef, options=None):
Ole Troana7564e82018-06-12 21:06:44 +0200361 self.size = types['u32'].size
Ole Troan40dc4b32019-10-22 14:01:53 +0200362 self.name = name
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100363 self.enumtype = 'u32'
Ole Troan40dc4b32019-10-22 14:01:53 +0200364 self.msgdef = msgdef
Ole Troana7564e82018-06-12 21:06:44 +0200365 e_hash = {}
366 for f in msgdef:
367 if type(f) is dict and 'enumtype' in f:
368 if f['enumtype'] != 'u32':
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100369 self.size = types[f['enumtype']].size
370 self.enumtype = f['enumtype']
Ole Troana7564e82018-06-12 21:06:44 +0200371 continue
372 ename, evalue = f
373 e_hash[ename] = evalue
Ole Troan48ae19e2019-03-07 11:28:32 +0100374 self.enum = IntFlag(name, e_hash)
Ole Troana7564e82018-06-12 21:06:44 +0200375 types[name] = self
Ole Troan40dc4b32019-10-22 14:01:53 +0200376 class_types[name] = VPPEnumType
377 self.options = options
Ole Troan85465582019-04-30 10:04:36 +0200378
Ole Troana7564e82018-06-12 21:06:44 +0200379 def __getattr__(self, name):
380 return self.enum[name]
381
Paul Vinciguerraa089ae12019-07-08 15:41:07 -0400382 def __bool__(self):
Ole Troan0685da42018-10-16 14:42:50 +0200383 return True
384
Paul Vinciguerraa089ae12019-07-08 15:41:07 -0400385
Ole Troana7564e82018-06-12 21:06:44 +0200386 def pack(self, data, kwargs=None):
Ole Troan40dc4b32019-10-22 14:01:53 +0200387 if data is None: # Default to zero if not specified
388 if self.options and 'default' in self.options:
389 data = self.options['default']
390 else:
391 data = 0
392
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100393 return types[self.enumtype].pack(data)
Ole Troana7564e82018-06-12 21:06:44 +0200394
Ole Troan0bcad322018-12-11 13:04:01 +0100395 def unpack(self, data, offset=0, result=None, ntc=False):
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100396 x, size = types[self.enumtype].unpack(data, offset)
Ole Troanc84cbad2018-09-06 22:58:05 +0200397 return self.enum(x), size
Ole Troana7564e82018-06-12 21:06:44 +0200398
Ole Troanda47f672019-11-24 15:22:55 +0100399 @staticmethod
400 def _get_packer_with_options(f_type, options):
401 return VPPEnumType(f_type, types[f_type].msgdef, options=options)
Ole Troana7564e82018-06-12 21:06:44 +0200402
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500403 def __repr__(self):
404 return "VPPEnumType(name=%s, msgdef=%s, options=%s)" % (
405 self.name, self.msgdef, self.options
406 )
407
Ole Troan418ebb72019-11-19 04:38:20 +0100408
409class VPPUnionType(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200410 def __init__(self, name, msgdef):
411 self.name = name
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500412 self.msgdef = msgdef
Ole Troana7564e82018-06-12 21:06:44 +0200413 self.size = 0
414 self.maxindex = 0
415 fields = []
416 self.packers = collections.OrderedDict()
417 for i, f in enumerate(msgdef):
418 if type(f) is dict and 'crc' in f:
419 self.crc = f['crc']
420 continue
421 f_type, f_name = f
422 if f_type not in types:
423 logger.debug('Unknown union type {}'.format(f_type))
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800424 raise VPPSerializerValueError(
425 'Unknown message type {}'.format(f_type))
Ole Troana7564e82018-06-12 21:06:44 +0200426 fields.append(f_name)
427 size = types[f_type].size
428 self.packers[f_name] = types[f_type]
429 if size > self.size:
430 self.size = size
431 self.maxindex = i
432
433 types[name] = self
434 self.tuple = collections.namedtuple(name, fields, rename=True)
Ole Troana7564e82018-06-12 21:06:44 +0200435
Ole Troan31555a32018-10-22 09:30:26 +0200436 # Union of variable length?
Ole Troana7564e82018-06-12 21:06:44 +0200437 def pack(self, data, kwargs=None):
Ole Troan31555a32018-10-22 09:30:26 +0200438 if not data:
439 return b'\x00' * self.size
440
Ole Troana7564e82018-06-12 21:06:44 +0200441 for k, v in data.items():
442 logger.debug("Key: {} Value: {}".format(k, v))
443 b = self.packers[k].pack(v, kwargs)
Ole Troana7564e82018-06-12 21:06:44 +0200444 break
445 r = bytearray(self.size)
Ole Troanb199e982018-08-02 19:19:21 +0200446 r[:len(b)] = b
Ole Troana7564e82018-06-12 21:06:44 +0200447 return r
448
Ole Troan0bcad322018-12-11 13:04:01 +0100449 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200450 r = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200451 maxsize = 0
Ole Troana7564e82018-06-12 21:06:44 +0200452 for k, p in self.packers.items():
Ole Troan0bcad322018-12-11 13:04:01 +0100453 x, size = p.unpack(data, offset, ntc=ntc)
Ole Troanc84cbad2018-09-06 22:58:05 +0200454 if size > maxsize:
455 maxsize = size
456 r.append(x)
457 return self.tuple._make(r), maxsize
Ole Troana7564e82018-06-12 21:06:44 +0200458
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500459 def __repr__(self):
460 return"VPPUnionType(name=%s, msgdef=%r)" % (self.name, self.msgdef)
461
Ole Troana7564e82018-06-12 21:06:44 +0200462
Ole Troan418ebb72019-11-19 04:38:20 +0100463class VPPTypeAlias(Packer):
464 def __init__(self, name, msgdef, options=None):
Ole Troan0bcad322018-12-11 13:04:01 +0100465 self.name = name
Ole Troan418ebb72019-11-19 04:38:20 +0100466 self.msgdef = msgdef
Ole Troan0bcad322018-12-11 13:04:01 +0100467 t = vpp_get_type(msgdef['type'])
468 if not t:
Ole Troan75761b92019-09-11 17:49:08 +0200469 raise ValueError('No such type: {}'.format(msgdef['type']))
Ole Troan0bcad322018-12-11 13:04:01 +0100470 if 'length' in msgdef:
471 if msgdef['length'] == 0:
472 raise ValueError()
473 if msgdef['type'] == 'u8':
474 self.packer = FixedList_u8(name, msgdef['type'],
475 msgdef['length'])
476 self.size = self.packer.size
477 else:
478 self.packer = FixedList(name, msgdef['type'], msgdef['length'])
Ole Troan8c8acc02018-11-27 10:05:23 +0100479 else:
Ole Troan0bcad322018-12-11 13:04:01 +0100480 self.packer = t
481 self.size = t.size
482
483 types[name] = self
Ole Troan75761b92019-09-11 17:49:08 +0200484 self.toplevelconversion = False
Ole Troan418ebb72019-11-19 04:38:20 +0100485 self.options = options
Ole Troan0bcad322018-12-11 13:04:01 +0100486
487 def pack(self, data, kwargs=None):
488 if data and conversion_required(data, self.name):
489 try:
490 return conversion_packer(data, self.name)
491 # Python 2 and 3 raises different exceptions from inet_pton
492 except(OSError, socket.error, TypeError):
493 pass
Ole Troan418ebb72019-11-19 04:38:20 +0100494 if data is None: # Default to zero if not specified
495 if self.options and 'default' in self.options:
496 data = self.options['default']
497 else:
498 data = 0
Ole Troan0bcad322018-12-11 13:04:01 +0100499
500 return self.packer.pack(data, kwargs)
501
Ole Troanda47f672019-11-24 15:22:55 +0100502 @staticmethod
503 def _get_packer_with_options(f_type, options):
504 return VPPTypeAlias(f_type, types[f_type].msgdef, options=options)
Ole Troan418ebb72019-11-19 04:38:20 +0100505
Ole Troan0bcad322018-12-11 13:04:01 +0100506 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troan418ebb72019-11-19 04:38:20 +0100507 if ntc is False and self.name in vpp_format.conversion_unpacker_table:
Ole Troan75761b92019-09-11 17:49:08 +0200508 # Disable type conversion for dependent types
509 ntc = True
510 self.toplevelconversion = True
Ole Troan0bcad322018-12-11 13:04:01 +0100511 t, size = self.packer.unpack(data, offset, result, ntc=ntc)
Ole Troan75761b92019-09-11 17:49:08 +0200512 if self.toplevelconversion:
513 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100514 return conversion_unpacker(t, self.name), size
515 return t, size
Ole Troan53fffa12018-11-13 12:36:56 +0100516
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500517 def __repr__(self):
518 return "VPPTypeAlias(name=%s, msgdef=%s, options=%s)" % (
519 self.name, self.msgdef, self.options)
520
Ole Troan53fffa12018-11-13 12:36:56 +0100521
Ole Troan418ebb72019-11-19 04:38:20 +0100522class VPPType(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200523 # Set everything up to be able to pack / unpack
524 def __init__(self, name, msgdef):
525 self.name = name
526 self.msgdef = msgdef
527 self.packers = []
528 self.fields = []
529 self.fieldtypes = []
530 self.field_by_name = {}
531 size = 0
532 for i, f in enumerate(msgdef):
533 if type(f) is dict and 'crc' in f:
534 self.crc = f['crc']
535 continue
536 f_type, f_name = f[:2]
537 self.fields.append(f_name)
538 self.field_by_name[f_name] = None
539 self.fieldtypes.append(f_type)
540 if f_type not in types:
541 logger.debug('Unknown type {}'.format(f_type))
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800542 raise VPPSerializerValueError(
543 'Unknown message type {}'.format(f_type))
Ole Troan9ac11382019-04-23 17:11:01 +0200544
Ole Troan85465582019-04-30 10:04:36 +0200545 fieldlen = len(f)
Ole Troan9ac11382019-04-23 17:11:01 +0200546 options = [x for x in f if type(x) is dict]
547 if len(options):
548 self.options = options[0]
Ole Troan85465582019-04-30 10:04:36 +0200549 fieldlen -= 1
Ole Troan9ac11382019-04-23 17:11:01 +0200550 else:
551 self.options = {}
Ole Troan85465582019-04-30 10:04:36 +0200552 if fieldlen == 3: # list
Ole Troana7564e82018-06-12 21:06:44 +0200553 list_elements = f[2]
554 if list_elements == 0:
Ole Troane5ff5a32019-08-23 22:55:18 +0200555 if f_type == 'string':
556 p = String(f_name, 0, self.options)
557 else:
558 p = VLAList_legacy(f_name, f_type)
Ole Troana7564e82018-06-12 21:06:44 +0200559 self.packers.append(p)
Ole Troane5ff5a32019-08-23 22:55:18 +0200560 elif f_type == 'u8':
Ole Troana7564e82018-06-12 21:06:44 +0200561 p = FixedList_u8(f_name, f_type, list_elements)
562 self.packers.append(p)
563 size += p.size
Ole Troane5ff5a32019-08-23 22:55:18 +0200564 elif f_type == 'string':
565 p = String(f_name, list_elements, self.options)
566 self.packers.append(p)
567 size += p.size
Ole Troana7564e82018-06-12 21:06:44 +0200568 else:
569 p = FixedList(f_name, f_type, list_elements)
570 self.packers.append(p)
571 size += p.size
Ole Troan85465582019-04-30 10:04:36 +0200572 elif fieldlen == 4: # Variable length list
Ole Troan413f4a52018-11-28 11:36:05 +0100573 length_index = self.fields.index(f[3])
574 p = VLAList(f_name, f_type, f[3], length_index)
575 self.packers.append(p)
Ole Troana7564e82018-06-12 21:06:44 +0200576 else:
Ole Troan418ebb72019-11-19 04:38:20 +0100577 # default support for types that decay to basetype
Ole Troan40dc4b32019-10-22 14:01:53 +0200578 if 'default' in self.options:
Ole Troan418ebb72019-11-19 04:38:20 +0100579 p = self.get_packer_with_options(f_type, self.options)
Ole Troan40dc4b32019-10-22 14:01:53 +0200580 else:
581 p = types[f_type]
Ole Troan418ebb72019-11-19 04:38:20 +0100582
Ole Troan9ac11382019-04-23 17:11:01 +0200583 self.packers.append(p)
584 size += p.size
Ole Troana7564e82018-06-12 21:06:44 +0200585
586 self.size = size
587 self.tuple = collections.namedtuple(name, self.fields, rename=True)
588 types[name] = self
Ole Troan75761b92019-09-11 17:49:08 +0200589 self.toplevelconversion = False
Ole Troana7564e82018-06-12 21:06:44 +0200590
591 def pack(self, data, kwargs=None):
592 if not kwargs:
593 kwargs = data
Ole Troana7564e82018-06-12 21:06:44 +0200594 b = bytes()
Ole Troan31555a32018-10-22 09:30:26 +0200595
Ole Troan0bcad322018-12-11 13:04:01 +0100596 # Try one of the format functions
597 if data and conversion_required(data, self.name):
598 return conversion_packer(data, self.name)
599
600 for i, a in enumerate(self.fields):
Ole Troan31555a32018-10-22 09:30:26 +0200601 if data and type(data) is not dict and a not in data:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800602 raise VPPSerializerValueError(
603 "Invalid argument: {} expected {}.{}".
604 format(data, self.name, a))
Ole Troan31555a32018-10-22 09:30:26 +0200605
606 # Defaulting to zero.
607 if not data or a not in data: # Default to 0
608 arg = None
609 kwarg = None # No default for VLA
610 else:
611 arg = data[a]
612 kwarg = kwargs[a] if a in kwargs else None
Ole Troana7564e82018-06-12 21:06:44 +0200613 if isinstance(self.packers[i], VPPType):
Ole Troan0bcad322018-12-11 13:04:01 +0100614 b += self.packers[i].pack(arg, kwarg)
Ole Troana7564e82018-06-12 21:06:44 +0200615 else:
Ole Troan31555a32018-10-22 09:30:26 +0200616 b += self.packers[i].pack(arg, kwargs)
617
Ole Troana7564e82018-06-12 21:06:44 +0200618 return b
619
Ole Troan0bcad322018-12-11 13:04:01 +0100620 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200621 # Return a list of arguments
622 result = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200623 total = 0
Ole Troan418ebb72019-11-19 04:38:20 +0100624 if ntc is False and self.name in vpp_format.conversion_unpacker_table:
Ole Troan75761b92019-09-11 17:49:08 +0200625 # Disable type conversion for dependent types
626 ntc = True
627 self.toplevelconversion = True
628
Ole Troana7564e82018-06-12 21:06:44 +0200629 for p in self.packers:
Ole Troan0bcad322018-12-11 13:04:01 +0100630 x, size = p.unpack(data, offset, result, ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200631 if type(x) is tuple and len(x) == 1:
632 x = x[0]
633 result.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200634 offset += size
635 total += size
636 t = self.tuple._make(result)
Ole Troan75761b92019-09-11 17:49:08 +0200637
638 if self.toplevelconversion:
639 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100640 t = conversion_unpacker(t, self.name)
Ole Troanc84cbad2018-09-06 22:58:05 +0200641 return t, total
Ole Troana7564e82018-06-12 21:06:44 +0200642
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500643 def __repr__(self):
644 return "%s(name=%s, msgdef=%s)" % (
645 self.__class__.__name__, self.name, self.msgdef
646 )
647
Ole Troana7564e82018-06-12 21:06:44 +0200648
649class VPPMessage(VPPType):
650 pass