Skip to content
This repository was archived by the owner on Apr 22, 2024. It is now read-only.

Commit ce81263

Browse files
erickvermotmacartur
authored andcommitted
separate packet validation from unpack
1 parent 8f36308 commit ce81263

1 file changed

Lines changed: 22 additions & 9 deletions

File tree

pyof/utils.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,30 @@
99
0x04: pyof.v0x04}
1010

1111

12+
def validate_packet(packet):
13+
"""Check if packet is valid OF packet."""
14+
if not 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+
1231
def unpack(packet):
1332
"""Unpack the OpenFlow Packet and returns a message."""
14-
try:
15-
version = packet[0]
16-
except IndexError:
17-
raise UnpackException('null packet')
33+
validate_packet(packet)
1834

35+
version = packet[0]
1936
try:
2037
pyof_lib = pyof_version_libs[version]
2138
except KeyError:
@@ -27,11 +44,7 @@ def unpack(packet):
2744
message = pyof_lib.common.utils.new_message_from_header(header)
2845
binary_data = packet[8:]
2946
if binary_data:
30-
if len(binary_data) == header.length - 8:
31-
message.unpack(binary_data)
32-
else:
33-
raise UnpackException(
34-
'packet size does not match packet length field')
47+
message.unpack(binary_data)
3548
return message
3649
except (UnpackException, ValueError) as e:
3750
raise UnpackException(e)

0 commit comments

Comments
 (0)