blob: 09294875305ba0db20ecb142ca7c72ce322178a8 [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
Ole Troan418ebb72019-11-19 04:38:20 +010069# TODO: post 20.01, remove inherit from object.
70class Packer(object):
71 options = {}
72
73 def pack(self, data, kwargs):
74 raise NotImplementedError
75
76 def unpack(self, data, offset, result=None, ntc=False):
77 raise NotImplementedError
78
79 # override as appropriate in subclasses
Ole Troanda47f672019-11-24 15:22:55 +010080 @staticmethod
81 def _get_packer_with_options(f_type, options):
Ole Troan418ebb72019-11-19 04:38:20 +010082 return types[f_type]
83
84 def get_packer_with_options(self, f_type, options):
85 if options is not None:
86 try:
Ole Troanda47f672019-11-24 15:22:55 +010087 c = types[f_type].__class__
88 return c._get_packer_with_options(f_type, options)
Ole Troan418ebb72019-11-19 04:38:20 +010089 except IndexError:
90 raise VPPSerializerValueError(
91 "Options not supported for {}{} ({})".
Ole Troanda47f672019-11-24 15:22:55 +010092 format(f_type, types[f_type].__class__,
93 options))
Ole Troan418ebb72019-11-19 04:38:20 +010094
95
96class BaseTypes(Packer):
Ole Troan85465582019-04-30 10:04:36 +020097 def __init__(self, type, elements=0, options=None):
Paul Vinciguerra14b0b472019-11-23 23:49:57 -050098 self._type = type
99 self._elements = elements
Ole Troana7564e82018-06-12 21:06:44 +0200100 base_types = {'u8': '>B',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -0400101 'i8': '>b',
Ole Troan413f4a52018-11-28 11:36:05 +0100102 'string': '>s',
Ole Troana7564e82018-06-12 21:06:44 +0200103 'u16': '>H',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -0400104 'i16': '>h',
Ole Troana7564e82018-06-12 21:06:44 +0200105 'u32': '>I',
106 'i32': '>i',
107 'u64': '>Q',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -0400108 'i64': '>q',
Paul Vinciguerra888640a2019-05-14 21:01:28 -0400109 'f64': '=d',
Ole Troanf47e9b62018-10-16 15:14:03 +0200110 'bool': '>?',
Ole Troana7564e82018-06-12 21:06:44 +0200111 'header': '>HI'}
112
Ole Troan413f4a52018-11-28 11:36:05 +0100113 if elements > 0 and (type == 'u8' or type == 'string'):
Ole Troana7564e82018-06-12 21:06:44 +0200114 self.packer = struct.Struct('>%ss' % elements)
115 else:
116 self.packer = struct.Struct(base_types[type])
117 self.size = self.packer.size
Ole Troan85465582019-04-30 10:04:36 +0200118 self.options = options
119
Ole Troana7564e82018-06-12 21:06:44 +0200120 def pack(self, data, kwargs=None):
Ole Troan40dc4b32019-10-22 14:01:53 +0200121 if data is None: # Default to zero if not specified
Ole Troan85465582019-04-30 10:04:36 +0200122 if self.options and 'default' in self.options:
123 data = self.options['default']
124 else:
125 data = 0
Ole Troana7564e82018-06-12 21:06:44 +0200126 return self.packer.pack(data)
127
Ole Troan0bcad322018-12-11 13:04:01 +0100128 def unpack(self, data, offset, result=None, ntc=False):
Ole Troanc84cbad2018-09-06 22:58:05 +0200129 return self.packer.unpack_from(data, offset)[0], self.packer.size
Ole Troana7564e82018-06-12 21:06:44 +0200130
Ole Troanda47f672019-11-24 15:22:55 +0100131 @staticmethod
132 def _get_packer_with_options(f_type, options):
133 return BaseTypes(f_type, options=options)
Ole Troana7564e82018-06-12 21:06:44 +0200134
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500135 def __repr__(self):
136 return "BaseTypes(type=%s, elements=%s, options=%s)" % (self._type,
137 self._elements,
138 self.options)
139
Ole Troan418ebb72019-11-19 04:38:20 +0100140
141class String(Packer):
Ole Troane5ff5a32019-08-23 22:55:18 +0200142 def __init__(self, name, num, options):
143 self.name = name
144 self.num = num
Ole Troan413f4a52018-11-28 11:36:05 +0100145 self.size = 1
146 self.length_field_packer = BaseTypes('u32')
Ole Troane5ff5a32019-08-23 22:55:18 +0200147 self.limit = options['limit'] if 'limit' in options else num
148 self.fixed = True if num else False
149 if self.fixed and not self.limit:
Ole Troan9ac11382019-04-23 17:11:01 +0200150 raise VPPSerializerValueError(
151 "Invalid argument length for: {}, {} maximum {}".
152 format(list, len(list), self.limit))
153
Ole Troane5ff5a32019-08-23 22:55:18 +0200154 def pack(self, list, kwargs=None):
155 if not list:
156 if self.fixed:
157 return b"\x00" * self.limit
158 return self.length_field_packer.pack(0) + b""
159 if self.limit and len(list) > self.limit - 1:
160 raise VPPSerializerValueError(
161 "Invalid argument length for: {}, {} maximum {}".
162 format(list, len(list), self.limit - 1))
163 if self.fixed:
164 return list.encode('ascii').ljust(self.limit, b'\x00')
165 return self.length_field_packer.pack(len(list)) + list.encode('ascii')
Ole Troan413f4a52018-11-28 11:36:05 +0100166
167 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troane5ff5a32019-08-23 22:55:18 +0200168 if self.fixed:
169 p = BaseTypes('u8', self.num)
170 s = p.unpack(data, offset)
171 s2 = s[0].split(b'\0', 1)[0]
172 return (s2.decode('ascii'), self.num)
173
Ole Troan413f4a52018-11-28 11:36:05 +0100174 length, length_field_size = self.length_field_packer.unpack(data,
175 offset)
176 if length == 0:
Ole Troane5ff5a32019-08-23 22:55:18 +0200177 return '', 0
Ole Troan413f4a52018-11-28 11:36:05 +0100178 p = BaseTypes('u8', length)
179 x, size = p.unpack(data, offset + length_field_size)
Ole Troan33a58172019-09-04 09:12:29 +0200180 return (x.decode('ascii', errors='replace'), size + length_field_size)
Ole Troan413f4a52018-11-28 11:36:05 +0100181
182
Paul Vinciguerraba2c7fa2019-11-23 21:02:27 -0500183types = {'u8': BaseTypes('u8'), 'i8': BaseTypes('i8'),
184 'u16': BaseTypes('u16'), 'i16': BaseTypes('i16'),
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800185 'u32': BaseTypes('u32'), 'i32': BaseTypes('i32'),
Paul Vinciguerraba2c7fa2019-11-23 21:02:27 -0500186 'u64': BaseTypes('u64'), 'i64': BaseTypes('i64'),
187 'f64': BaseTypes('f64'),
Ole Troan9ac11382019-04-23 17:11:01 +0200188 'bool': BaseTypes('bool'), 'string': String}
Ole Troana7564e82018-06-12 21:06:44 +0200189
Ole Troan40dc4b32019-10-22 14:01:53 +0200190class_types = {}
Ole Troana7564e82018-06-12 21:06:44 +0200191
Ole Troan418ebb72019-11-19 04:38:20 +0100192
Ole Troan0685da42018-10-16 14:42:50 +0200193def vpp_get_type(name):
194 try:
195 return types[name]
196 except KeyError:
197 return None
198
199
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800200class VPPSerializerValueError(ValueError):
201 pass
202
203
Ole Troan418ebb72019-11-19 04:38:20 +0100204class FixedList_u8(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200205 def __init__(self, name, field_type, num):
206 self.name = name
207 self.num = num
208 self.packer = BaseTypes(field_type, num)
209 self.size = self.packer.size
Ole Troan413f4a52018-11-28 11:36:05 +0100210 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200211
Ole Troan0bcad322018-12-11 13:04:01 +0100212 def pack(self, data, kwargs=None):
Ole Troana7564e82018-06-12 21:06:44 +0200213 """Packs a fixed length bytestring. Left-pads with zeros
214 if input data is too short."""
Ole Troan0bcad322018-12-11 13:04:01 +0100215 if not data:
Ole Troan31555a32018-10-22 09:30:26 +0200216 return b'\x00' * self.size
Ole Troan0bcad322018-12-11 13:04:01 +0100217
218 if len(data) > self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800219 raise VPPSerializerValueError(
220 'Fixed list length error for "{}", got: {}'
221 ' expected: {}'
Ole Troan0bcad322018-12-11 13:04:01 +0100222 .format(self.name, len(data), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200223
Ole Troan64e978b2019-10-17 21:40:36 +0200224 try:
225 return self.packer.pack(data)
226 except struct.error:
227 raise VPPSerializerValueError(
228 'Packing failed for "{}" {}'
229 .format(self.name, kwargs))
Ole Troan418ebb72019-11-19 04:38:20 +0100230
Ole Troan0bcad322018-12-11 13:04:01 +0100231 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200232 if len(data[offset:]) < self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800233 raise VPPSerializerValueError(
234 'Invalid array length for "{}" got {}'
235 ' expected {}'
236 .format(self.name, len(data[offset:]), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200237 return self.packer.unpack(data, offset)
238
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500239 def __repr__(self):
240 return "FixedList_u8(name=%s, field_type=%s, num=%s)" % (
241 self.name, self.field_type, self.num
242 )
243
Ole Troana7564e82018-06-12 21:06:44 +0200244
Ole Troan418ebb72019-11-19 04:38:20 +0100245class FixedList(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200246 def __init__(self, name, field_type, num):
247 self.num = num
248 self.packer = types[field_type]
249 self.size = self.packer.size * num
Ole Troan0bcad322018-12-11 13:04:01 +0100250 self.name = name
251 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200252
253 def pack(self, list, kwargs):
Ole Troana7564e82018-06-12 21:06:44 +0200254 if len(list) != self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800255 raise VPPSerializerValueError(
256 'Fixed list length error, got: {} expected: {}'
257 .format(len(list), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200258 b = bytes()
259 for e in list:
260 b += self.packer.pack(e)
261 return b
262
Ole Troan0bcad322018-12-11 13:04:01 +0100263 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200264 # Return a list of arguments
265 result = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200266 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200267 for e in range(self.num):
Ole Troan0bcad322018-12-11 13:04:01 +0100268 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200269 result.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200270 offset += size
271 total += size
272 return result, total
Ole Troana7564e82018-06-12 21:06:44 +0200273
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500274 def __repr__(self):
Paul Vinciguerra99fbf052019-11-26 14:15:53 -0500275 return "FixedList(name=%s, field_type=%s, num=%s)" % (
Ole Troanda47f672019-11-24 15:22:55 +0100276 self.name, self.field_type, self.num)
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500277
Ole Troana7564e82018-06-12 21:06:44 +0200278
Ole Troan418ebb72019-11-19 04:38:20 +0100279class VLAList(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200280 def __init__(self, name, field_type, len_field_name, index):
Ole Troanc84cbad2018-09-06 22:58:05 +0200281 self.name = name
Ole Troan413f4a52018-11-28 11:36:05 +0100282 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200283 self.index = index
284 self.packer = types[field_type]
285 self.size = self.packer.size
286 self.length_field = len_field_name
287
Ole Troan22674292019-10-21 18:59:11 +0200288 def pack(self, lst, kwargs=None):
289 if not lst:
Ole Troan31555a32018-10-22 09:30:26 +0200290 return b""
Ole Troan22674292019-10-21 18:59:11 +0200291 if len(lst) != kwargs[self.length_field]:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800292 raise VPPSerializerValueError(
293 'Variable length error, got: {} expected: {}'
Ole Troan22674292019-10-21 18:59:11 +0200294 .format(len(lst), kwargs[self.length_field]))
Ole Troana7564e82018-06-12 21:06:44 +0200295
296 # u8 array
297 if self.packer.size == 1:
Ole Troan22674292019-10-21 18:59:11 +0200298 if isinstance(lst, list):
299 return b''.join(lst)
300 return bytes(lst)
Ole Troana7564e82018-06-12 21:06:44 +0200301
Ole Troan22674292019-10-21 18:59:11 +0200302 b = bytes()
303 for e in lst:
Ole Troana7564e82018-06-12 21:06:44 +0200304 b += self.packer.pack(e)
305 return b
306
Ole Troan0bcad322018-12-11 13:04:01 +0100307 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200308 # Return a list of arguments
Ole Troanc84cbad2018-09-06 22:58:05 +0200309 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200310
311 # u8 array
312 if self.packer.size == 1:
313 if result[self.index] == 0:
Ole Troanc84cbad2018-09-06 22:58:05 +0200314 return b'', 0
Ole Troana7564e82018-06-12 21:06:44 +0200315 p = BaseTypes('u8', result[self.index])
Ole Troan0bcad322018-12-11 13:04:01 +0100316 return p.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200317
318 r = []
319 for e in range(result[self.index]):
Ole Troan0bcad322018-12-11 13:04:01 +0100320 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200321 r.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200322 offset += size
323 total += size
324 return r, total
Ole Troana7564e82018-06-12 21:06:44 +0200325
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500326 def __repr__(self):
327 return "VLAList(name=%s, field_type=%s, " \
328 "len_field_name=%s, index=%s)" % (
Ole Troanda47f672019-11-24 15:22:55 +0100329 self.name, self.field_type, self.length_field, self.index
330 )
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500331
Ole Troana7564e82018-06-12 21:06:44 +0200332
Ole Troan418ebb72019-11-19 04:38:20 +0100333class VLAList_legacy(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200334 def __init__(self, name, field_type):
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500335 self.name = name
336 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200337 self.packer = types[field_type]
338 self.size = self.packer.size
339
340 def pack(self, list, kwargs=None):
Ole Troana7564e82018-06-12 21:06:44 +0200341 if self.packer.size == 1:
342 return bytes(list)
343
344 b = bytes()
345 for e in list:
346 b += self.packer.pack(e)
347 return b
348
Ole Troan0bcad322018-12-11 13:04:01 +0100349 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troanc84cbad2018-09-06 22:58:05 +0200350 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200351 # Return a list of arguments
352 if (len(data) - offset) % self.packer.size:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800353 raise VPPSerializerValueError(
354 'Legacy Variable Length Array length mismatch.')
Ole Troana7564e82018-06-12 21:06:44 +0200355 elements = int((len(data) - offset) / self.packer.size)
356 r = []
Ole Troana7564e82018-06-12 21:06:44 +0200357 for e in range(elements):
Ole Troan0bcad322018-12-11 13:04:01 +0100358 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200359 r.append(x)
360 offset += self.packer.size
Ole Troanc84cbad2018-09-06 22:58:05 +0200361 total += size
362 return r, total
Ole Troana7564e82018-06-12 21:06:44 +0200363
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500364 def __repr__(self):
365 return "VLAList_legacy(name=%s, field_type=%s)" % (
366 self.name, self.field_type
367 )
368
Ole Troana7564e82018-06-12 21:06:44 +0200369
Ole Troan418ebb72019-11-19 04:38:20 +0100370class VPPEnumType(Packer):
Ole Troan40dc4b32019-10-22 14:01:53 +0200371 def __init__(self, name, msgdef, options=None):
Ole Troana7564e82018-06-12 21:06:44 +0200372 self.size = types['u32'].size
Ole Troan40dc4b32019-10-22 14:01:53 +0200373 self.name = name
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100374 self.enumtype = 'u32'
Ole Troan40dc4b32019-10-22 14:01:53 +0200375 self.msgdef = msgdef
Ole Troana7564e82018-06-12 21:06:44 +0200376 e_hash = {}
377 for f in msgdef:
378 if type(f) is dict and 'enumtype' in f:
379 if f['enumtype'] != 'u32':
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100380 self.size = types[f['enumtype']].size
381 self.enumtype = f['enumtype']
Ole Troana7564e82018-06-12 21:06:44 +0200382 continue
383 ename, evalue = f
384 e_hash[ename] = evalue
Ole Troan48ae19e2019-03-07 11:28:32 +0100385 self.enum = IntFlag(name, e_hash)
Ole Troana7564e82018-06-12 21:06:44 +0200386 types[name] = self
Ole Troan40dc4b32019-10-22 14:01:53 +0200387 class_types[name] = VPPEnumType
388 self.options = options
Ole Troan85465582019-04-30 10:04:36 +0200389
Ole Troana7564e82018-06-12 21:06:44 +0200390 def __getattr__(self, name):
391 return self.enum[name]
392
Paul Vinciguerraa089ae12019-07-08 15:41:07 -0400393 def __bool__(self):
Ole Troan0685da42018-10-16 14:42:50 +0200394 return True
395
Ole Troan418ebb72019-11-19 04:38:20 +0100396 # TODO: Remove post 20.01.
Paul Vinciguerraa089ae12019-07-08 15:41:07 -0400397 if sys.version[0] == '2':
398 __nonzero__ = __bool__
399
Ole Troana7564e82018-06-12 21:06:44 +0200400 def pack(self, data, kwargs=None):
Ole Troan40dc4b32019-10-22 14:01:53 +0200401 if data is None: # Default to zero if not specified
402 if self.options and 'default' in self.options:
403 data = self.options['default']
404 else:
405 data = 0
406
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100407 return types[self.enumtype].pack(data)
Ole Troana7564e82018-06-12 21:06:44 +0200408
Ole Troan0bcad322018-12-11 13:04:01 +0100409 def unpack(self, data, offset=0, result=None, ntc=False):
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100410 x, size = types[self.enumtype].unpack(data, offset)
Ole Troanc84cbad2018-09-06 22:58:05 +0200411 return self.enum(x), size
Ole Troana7564e82018-06-12 21:06:44 +0200412
Ole Troanda47f672019-11-24 15:22:55 +0100413 @staticmethod
414 def _get_packer_with_options(f_type, options):
415 return VPPEnumType(f_type, types[f_type].msgdef, options=options)
Ole Troana7564e82018-06-12 21:06:44 +0200416
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500417 def __repr__(self):
418 return "VPPEnumType(name=%s, msgdef=%s, options=%s)" % (
419 self.name, self.msgdef, self.options
420 )
421
Ole Troan418ebb72019-11-19 04:38:20 +0100422
423class VPPUnionType(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200424 def __init__(self, name, msgdef):
425 self.name = name
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500426 self.msgdef = msgdef
Ole Troana7564e82018-06-12 21:06:44 +0200427 self.size = 0
428 self.maxindex = 0
429 fields = []
430 self.packers = collections.OrderedDict()
431 for i, f in enumerate(msgdef):
432 if type(f) is dict and 'crc' in f:
433 self.crc = f['crc']
434 continue
435 f_type, f_name = f
436 if f_type not in types:
437 logger.debug('Unknown union type {}'.format(f_type))
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800438 raise VPPSerializerValueError(
439 'Unknown message type {}'.format(f_type))
Ole Troana7564e82018-06-12 21:06:44 +0200440 fields.append(f_name)
441 size = types[f_type].size
442 self.packers[f_name] = types[f_type]
443 if size > self.size:
444 self.size = size
445 self.maxindex = i
446
447 types[name] = self
448 self.tuple = collections.namedtuple(name, fields, rename=True)
Ole Troana7564e82018-06-12 21:06:44 +0200449
Ole Troan31555a32018-10-22 09:30:26 +0200450 # Union of variable length?
Ole Troana7564e82018-06-12 21:06:44 +0200451 def pack(self, data, kwargs=None):
Ole Troan31555a32018-10-22 09:30:26 +0200452 if not data:
453 return b'\x00' * self.size
454
Ole Troana7564e82018-06-12 21:06:44 +0200455 for k, v in data.items():
456 logger.debug("Key: {} Value: {}".format(k, v))
457 b = self.packers[k].pack(v, kwargs)
Ole Troana7564e82018-06-12 21:06:44 +0200458 break
459 r = bytearray(self.size)
Ole Troanb199e982018-08-02 19:19:21 +0200460 r[:len(b)] = b
Ole Troana7564e82018-06-12 21:06:44 +0200461 return r
462
Ole Troan0bcad322018-12-11 13:04:01 +0100463 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200464 r = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200465 maxsize = 0
Ole Troana7564e82018-06-12 21:06:44 +0200466 for k, p in self.packers.items():
Ole Troan0bcad322018-12-11 13:04:01 +0100467 x, size = p.unpack(data, offset, ntc=ntc)
Ole Troanc84cbad2018-09-06 22:58:05 +0200468 if size > maxsize:
469 maxsize = size
470 r.append(x)
471 return self.tuple._make(r), maxsize
Ole Troana7564e82018-06-12 21:06:44 +0200472
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500473 def __repr__(self):
474 return"VPPUnionType(name=%s, msgdef=%r)" % (self.name, self.msgdef)
475
Ole Troana7564e82018-06-12 21:06:44 +0200476
Ole Troan418ebb72019-11-19 04:38:20 +0100477class VPPTypeAlias(Packer):
478 def __init__(self, name, msgdef, options=None):
Ole Troan0bcad322018-12-11 13:04:01 +0100479 self.name = name
Ole Troan418ebb72019-11-19 04:38:20 +0100480 self.msgdef = msgdef
Ole Troan0bcad322018-12-11 13:04:01 +0100481 t = vpp_get_type(msgdef['type'])
482 if not t:
Ole Troan75761b92019-09-11 17:49:08 +0200483 raise ValueError('No such type: {}'.format(msgdef['type']))
Ole Troan0bcad322018-12-11 13:04:01 +0100484 if 'length' in msgdef:
485 if msgdef['length'] == 0:
486 raise ValueError()
487 if msgdef['type'] == 'u8':
488 self.packer = FixedList_u8(name, msgdef['type'],
489 msgdef['length'])
490 self.size = self.packer.size
491 else:
492 self.packer = FixedList(name, msgdef['type'], msgdef['length'])
Ole Troan8c8acc02018-11-27 10:05:23 +0100493 else:
Ole Troan0bcad322018-12-11 13:04:01 +0100494 self.packer = t
495 self.size = t.size
496
497 types[name] = self
Ole Troan75761b92019-09-11 17:49:08 +0200498 self.toplevelconversion = False
Ole Troan418ebb72019-11-19 04:38:20 +0100499 self.options = options
Ole Troan0bcad322018-12-11 13:04:01 +0100500
501 def pack(self, data, kwargs=None):
502 if data and conversion_required(data, self.name):
503 try:
504 return conversion_packer(data, self.name)
505 # Python 2 and 3 raises different exceptions from inet_pton
506 except(OSError, socket.error, TypeError):
507 pass
Ole Troan418ebb72019-11-19 04:38:20 +0100508 if data is None: # Default to zero if not specified
509 if self.options and 'default' in self.options:
510 data = self.options['default']
511 else:
512 data = 0
Ole Troan0bcad322018-12-11 13:04:01 +0100513
514 return self.packer.pack(data, kwargs)
515
Ole Troanda47f672019-11-24 15:22:55 +0100516 @staticmethod
517 def _get_packer_with_options(f_type, options):
518 return VPPTypeAlias(f_type, types[f_type].msgdef, options=options)
Ole Troan418ebb72019-11-19 04:38:20 +0100519
Ole Troan0bcad322018-12-11 13:04:01 +0100520 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troan418ebb72019-11-19 04:38:20 +0100521 if ntc is False and self.name in vpp_format.conversion_unpacker_table:
Ole Troan75761b92019-09-11 17:49:08 +0200522 # Disable type conversion for dependent types
523 ntc = True
524 self.toplevelconversion = True
Ole Troan0bcad322018-12-11 13:04:01 +0100525 t, size = self.packer.unpack(data, offset, result, ntc=ntc)
Ole Troan75761b92019-09-11 17:49:08 +0200526 if self.toplevelconversion:
527 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100528 return conversion_unpacker(t, self.name), size
529 return t, size
Ole Troan53fffa12018-11-13 12:36:56 +0100530
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500531 def __repr__(self):
532 return "VPPTypeAlias(name=%s, msgdef=%s, options=%s)" % (
533 self.name, self.msgdef, self.options)
534
Ole Troan53fffa12018-11-13 12:36:56 +0100535
Ole Troan418ebb72019-11-19 04:38:20 +0100536class VPPType(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200537 # Set everything up to be able to pack / unpack
538 def __init__(self, name, msgdef):
539 self.name = name
540 self.msgdef = msgdef
541 self.packers = []
542 self.fields = []
543 self.fieldtypes = []
544 self.field_by_name = {}
545 size = 0
546 for i, f in enumerate(msgdef):
547 if type(f) is dict and 'crc' in f:
548 self.crc = f['crc']
549 continue
550 f_type, f_name = f[:2]
551 self.fields.append(f_name)
552 self.field_by_name[f_name] = None
553 self.fieldtypes.append(f_type)
554 if f_type not in types:
555 logger.debug('Unknown type {}'.format(f_type))
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800556 raise VPPSerializerValueError(
557 'Unknown message type {}'.format(f_type))
Ole Troan9ac11382019-04-23 17:11:01 +0200558
Ole Troan85465582019-04-30 10:04:36 +0200559 fieldlen = len(f)
Ole Troan9ac11382019-04-23 17:11:01 +0200560 options = [x for x in f if type(x) is dict]
561 if len(options):
562 self.options = options[0]
Ole Troan85465582019-04-30 10:04:36 +0200563 fieldlen -= 1
Ole Troan9ac11382019-04-23 17:11:01 +0200564 else:
565 self.options = {}
Ole Troan85465582019-04-30 10:04:36 +0200566 if fieldlen == 3: # list
Ole Troana7564e82018-06-12 21:06:44 +0200567 list_elements = f[2]
568 if list_elements == 0:
Ole Troane5ff5a32019-08-23 22:55:18 +0200569 if f_type == 'string':
570 p = String(f_name, 0, self.options)
571 else:
572 p = VLAList_legacy(f_name, f_type)
Ole Troana7564e82018-06-12 21:06:44 +0200573 self.packers.append(p)
Ole Troane5ff5a32019-08-23 22:55:18 +0200574 elif f_type == 'u8':
Ole Troana7564e82018-06-12 21:06:44 +0200575 p = FixedList_u8(f_name, f_type, list_elements)
576 self.packers.append(p)
577 size += p.size
Ole Troane5ff5a32019-08-23 22:55:18 +0200578 elif f_type == 'string':
579 p = String(f_name, list_elements, self.options)
580 self.packers.append(p)
581 size += p.size
Ole Troana7564e82018-06-12 21:06:44 +0200582 else:
583 p = FixedList(f_name, f_type, list_elements)
584 self.packers.append(p)
585 size += p.size
Ole Troan85465582019-04-30 10:04:36 +0200586 elif fieldlen == 4: # Variable length list
Ole Troan413f4a52018-11-28 11:36:05 +0100587 length_index = self.fields.index(f[3])
588 p = VLAList(f_name, f_type, f[3], length_index)
589 self.packers.append(p)
Ole Troana7564e82018-06-12 21:06:44 +0200590 else:
Ole Troan418ebb72019-11-19 04:38:20 +0100591 # default support for types that decay to basetype
Ole Troan40dc4b32019-10-22 14:01:53 +0200592 if 'default' in self.options:
Ole Troan418ebb72019-11-19 04:38:20 +0100593 p = self.get_packer_with_options(f_type, self.options)
Ole Troan40dc4b32019-10-22 14:01:53 +0200594 else:
595 p = types[f_type]
Ole Troan418ebb72019-11-19 04:38:20 +0100596
Ole Troan9ac11382019-04-23 17:11:01 +0200597 self.packers.append(p)
598 size += p.size
Ole Troana7564e82018-06-12 21:06:44 +0200599
600 self.size = size
601 self.tuple = collections.namedtuple(name, self.fields, rename=True)
602 types[name] = self
Ole Troan75761b92019-09-11 17:49:08 +0200603 self.toplevelconversion = False
Ole Troana7564e82018-06-12 21:06:44 +0200604
605 def pack(self, data, kwargs=None):
606 if not kwargs:
607 kwargs = data
Ole Troana7564e82018-06-12 21:06:44 +0200608 b = bytes()
Ole Troan31555a32018-10-22 09:30:26 +0200609
Ole Troan0bcad322018-12-11 13:04:01 +0100610 # Try one of the format functions
611 if data and conversion_required(data, self.name):
612 return conversion_packer(data, self.name)
613
614 for i, a in enumerate(self.fields):
Ole Troan31555a32018-10-22 09:30:26 +0200615 if data and type(data) is not dict and a not in data:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800616 raise VPPSerializerValueError(
617 "Invalid argument: {} expected {}.{}".
618 format(data, self.name, a))
Ole Troan31555a32018-10-22 09:30:26 +0200619
620 # Defaulting to zero.
621 if not data or a not in data: # Default to 0
622 arg = None
623 kwarg = None # No default for VLA
624 else:
625 arg = data[a]
626 kwarg = kwargs[a] if a in kwargs else None
Ole Troana7564e82018-06-12 21:06:44 +0200627 if isinstance(self.packers[i], VPPType):
Ole Troan0bcad322018-12-11 13:04:01 +0100628 b += self.packers[i].pack(arg, kwarg)
Ole Troana7564e82018-06-12 21:06:44 +0200629 else:
Ole Troan31555a32018-10-22 09:30:26 +0200630 b += self.packers[i].pack(arg, kwargs)
631
Ole Troana7564e82018-06-12 21:06:44 +0200632 return b
633
Ole Troan0bcad322018-12-11 13:04:01 +0100634 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200635 # Return a list of arguments
636 result = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200637 total = 0
Ole Troan418ebb72019-11-19 04:38:20 +0100638 if ntc is False and self.name in vpp_format.conversion_unpacker_table:
Ole Troan75761b92019-09-11 17:49:08 +0200639 # Disable type conversion for dependent types
640 ntc = True
641 self.toplevelconversion = True
642
Ole Troana7564e82018-06-12 21:06:44 +0200643 for p in self.packers:
Ole Troan0bcad322018-12-11 13:04:01 +0100644 x, size = p.unpack(data, offset, result, ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200645 if type(x) is tuple and len(x) == 1:
646 x = x[0]
647 result.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200648 offset += size
649 total += size
650 t = self.tuple._make(result)
Ole Troan75761b92019-09-11 17:49:08 +0200651
652 if self.toplevelconversion:
653 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100654 t = conversion_unpacker(t, self.name)
Ole Troanc84cbad2018-09-06 22:58:05 +0200655 return t, total
Ole Troana7564e82018-06-12 21:06:44 +0200656
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500657 def __repr__(self):
658 return "%s(name=%s, msgdef=%s)" % (
659 self.__class__.__name__, self.name, self.msgdef
660 )
661
Ole Troana7564e82018-06-12 21:06:44 +0200662
663class VPPMessage(VPPType):
664 pass