Test Failed
Pull Request — master (#603)
by
unknown
02:35
created

pyof.utils   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 25%

Importance

Changes 0
Metric Value
wmc 10
eloc 30
dl 0
loc 64
ccs 7
cts 28
cp 0.25
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A unpack() 0 26 3
B validate_packet() 0 21 7
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
    if not isinstance(packet, bytes):
23
        raise UnpackException('invalid packet')
24
25
    packet_length = len(packet)
26
27
    if packet_length < 8 or packet_length > 2**16:
28
        raise UnpackException('invalid packet')
29
30
    if packet_length != int.from_bytes(packet[2:4], byteorder='big'):
31
        raise UnpackException('invalid packet')
32
33
    version = packet[0]
34
    if version == 0 or version >= 128:
35
        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
    validate_packet(packet)
52
53
    version = packet[0]
54
    try:
55
        pyof_lib = PYOF_VERSION_LIBS[version]
56
    except KeyError:
57
        raise UnpackException('Version not supported')
58
59
    try:
60
        message = pyof_lib.common.utils.unpack_message(packet)
61
        return message
62
    except (UnpackException, ValueError) as exception:
63
        raise UnpackException(exception)
64