Passed
Pull Request — master (#397)
by
unknown
01:51
created

validate_packet()   B

Complexity

Conditions 7

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
c 1
b 0
f 0
dl 0
loc 17
rs 7.3333
1
"""General Unpack utils for python-openflow."""
2
import pyof.v0x01.common.header
3
import pyof.v0x01.common.utils
4
import pyof.v0x04.common.header
5
import pyof.v0x04.common.utils
6
from pyof.foundation.exceptions import UnpackException
7
8
pyof_version_libs = {0x01: pyof.v0x01,
9
                     0x04: pyof.v0x04}
10
11
12
def validate_packet(packet):
13
    """Check if packet is valid OF packet."""
14
    if isinstance(packet, bytes):
15
        raise UnpackException('invalid packet')
16
17
    packet_length = len(packet)
18
19
    if packet_length < 8 or packet_length > 2**16:
20
        raise UnpackException('invalid packet')
21
22
    if packet_length != int.from_bytes(packet[2:4],
23
                                       byteorder='big'):
24
        raise UnpackException('invalid packet')
25
26
    version = packet[0]
27
    if version == 0 or version >= 128:
28
        raise UnpackException('invalid packet')
29
30
31
def unpack(packet):
32
    """Unpack the OpenFlow Packet and returns a message."""
33
    validate_packet(packet)
34
35
    version = packet[0]
36
    try:
37
        pyof_lib = pyof_version_libs[version]
38
    except KeyError:
39
        raise UnpackException('Version not supported')
40
41
    try:
42
        header = pyof_lib.common.header.Header()
43
        header.unpack(packet[:8])
44
        message = pyof_lib.common.utils.new_message_from_header(header)
45
        binary_data = packet[8:]
46
        if binary_data:
47
            message.unpack(binary_data)
48
        return message
49
    except (UnpackException, ValueError) as e:
50
        raise UnpackException(e)
51