Passed
Pull Request — master (#397)
by
unknown
02:04
created

validate_packet()   B

Complexity

Conditions 5

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
c 1
b 0
f 0
dl 0
loc 13
rs 8.5454
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
27
def unpack(packet):
28
    """Unpack the OpenFlow Packet and returns a message."""
29
    validate_packet(packet)
30
31
    version = packet[0]
32
    if version == 0 or version >= 128:
33
        raise UnpackException('invalid packet')
34
35
    try:
36
        pyof_lib = pyof_version_libs[version]
37
    except KeyError:
38
        raise UnpackException('Version not supported')
39
40
    try:
41
        header = pyof_lib.common.header.Header()
42
        header.unpack(packet[:8])
43
        message = pyof_lib.common.utils.new_message_from_header(header)
44
        binary_data = packet[8:]
45
        if binary_data:
46
            message.unpack(binary_data)
47
        return message
48
    except (UnpackException, ValueError) as e:
49
        raise UnpackException(e)
50