1#!/usr/bin/env python3 2# 3# Copyright (c) 2019, The OpenThread Authors. 4# All rights reserved. 5# 6# Redistribution and use in source and binary forms, with or without 7# modification, are permitted provided that the following conditions are met: 8# 1. Redistributions of source code must retain the above copyright 9# notice, this list of conditions and the following disclaimer. 10# 2. Redistributions in binary form must reproduce the above copyright 11# notice, this list of conditions and the following disclaimer in the 12# documentation and/or other materials provided with the distribution. 13# 3. Neither the name of the copyright holder nor the 14# names of its contributors may be used to endorse or promote products 15# derived from this software without specific prior written permission. 16# 17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 21# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 27# POSSIBILITY OF SUCH DAMAGE. 28 29import io 30import logging 31 32 33class UnknownTlv(object): 34 35 def __init__(self, type, data): 36 self.type = type 37 self.data = data 38 39 def __repr__(self): 40 return 'UnknownTlv(%d, %s)' % (self.type, self.data) 41 42 43class UnknownTlvFactory(object): 44 45 def __init__(self, type): 46 self._type = type 47 48 def parse(self, data, message_info): 49 return UnknownTlv(self._type, data) 50 51 52class SubTlvsFactory(object): 53 54 def __init__(self, sub_tlvs_factories): 55 self._sub_tlvs_factories = sub_tlvs_factories 56 57 def _get_factory(self, _type): 58 try: 59 return self._sub_tlvs_factories[_type] 60 except KeyError: 61 logging.error('Could not find TLV factory. Unsupported TLV type: {}'.format(_type)) 62 return UnknownTlvFactory(_type) 63 64 def parse(self, data, message_info): 65 sub_tlvs = [] 66 67 while data.tell() < len(data.getvalue()): 68 _type = ord(data.read(1)) 69 70 length = ord(data.read(1)) 71 value = data.read(length) 72 73 factory = self._get_factory(_type) 74 75 message_info.length = length 76 tlv = factory.parse(io.BytesIO(value), message_info) 77 78 sub_tlvs.append(tlv) 79 80 return sub_tlvs 81