pyof.utils.unpack()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.3332

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 26
ccs 8
cts 12
cp 0.6667
rs 9.8
c 0
b 0
f 0
cc 3
nop 1
crap 3.3332
1
"""General Unpack utils for python-openflow.
2
3
This package was moved from kytos/of_core for the purpose of creating a generic
4
method to perform package unpack independent of the OpenFlow version.
5
"""
6 1
from pyof import v0x01, v0x04
7 1
from pyof.foundation.exceptions import UnpackException
8 1
from pyof.v0x01.common import utils as u_v0x01  # pylint: disable=unused-import
9 1
from pyof.v0x04.common import utils as u_v0x04  # pylint: disable=unused-import
10
11 1
PYOF_VERSION_LIBS = {0x01: v0x01,
12
                     0x04: v0x04}
13
14
15 1
def validate_packet(packet):
16
    """Check if packet is valid OF packet.
17
18
    Raises:
19
        UnpackException: If the packet is invalid.
20
21
    """
22 1
    if not isinstance(packet, bytes):
23
        raise UnpackException('invalid packet')
24
25 1
    packet_length = len(packet)
26
27 1
    if packet_length < 8 or packet_length > 2**16:
28
        raise UnpackException('invalid packet')
29
30 1
    if packet_length != int.from_bytes(packet[2:4], byteorder='big'):
31
        raise UnpackException('invalid packet')
32
33 1
    version = packet[0]
34 1
    if version == 0 or version >= 128:
35 1
        raise UnpackException('invalid packet')
36
37
38 1
def unpack(packet):
39
    """Unpack the OpenFlow Packet and returns a message.
40
41
    Args:
42
        packet: buffer with the openflow packet.
43
44
    Returns:
45
        GenericMessage: Message unpacked based on openflow packet.
46
47
    Raises:
48
        UnpackException: if the packet can't be unpacked.
49
50
    """
51 1
    validate_packet(packet)
52
53 1
    version = packet[0]
54 1
    try:
55 1
        pyof_lib = PYOF_VERSION_LIBS[version]
56
    except KeyError:
57
        raise UnpackException('Version not supported')
58
59 1
    try:
60 1
        message = pyof_lib.common.utils.unpack_message(packet)
61 1
        return message
62
    except (UnpackException, ValueError) as exception:
63
        raise UnpackException(exception)
64