1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
|
"""Basic types used in structures and messages."""
# System imports
import struct
# Local source tree imports
from pyof.v0x01.foundation import exceptions
from pyof.v0x01.foundation.base import GenericStruct, GenericType
# Third-party imports
__all__ = ('UBInt8', 'UBInt16', 'UBInt32', 'UBInt64', 'Char', 'PAD',
'HWAddress', 'BinaryData', 'FixedTypeList', 'ConstantTypeList')
class PAD(GenericType):
"""Class for padding attributes."""
_fmt = ''
def __init__(self, length=0):
"""Pad up to ``length``, in bytes.
Args:
length (int): Total length, in bytes.
"""
super().__init__()
self._length = length
def __repr__(self):
return "{}({})".format(type(self).__name__, self._length)
def __str__(self):
return self.pack()
def get_size(self, value=None):
"""Return the type size in bytes.
Args:
value (int): In structs, the user can assign other value instead of
this class' instance. Here, in such cases, ``self`` is a class
attribute of the struct.
Returns:
int: Size in bytes.
"""
return self._length
def unpack(self, buff, offset=0):
"""Unpack *buff* into this object.
Do nothing, since the _length is already defined and it is just a PAD.
Keep buff and offset just for compability with other unpack methods.
Args:
buff: Buffer where data is located.
offset (int): Where data stream begins.
"""
pass
def pack(self, value=None):
"""Pack the object.
Args:
value (int): In structs, the user can assign other value instead of
this class' instance. Here, in such cases, ``self`` is a class
attribute of the struct.
Returns:
bytes: the byte 0 (zero) *length* times.
"""
return b'\x00' * self._length
class UBInt8(GenericType):
"""Format character for an Unsigned Char.
Class for an 8-bit (1-byte) Unsigned Integer.
"""
_fmt = "!B"
class UBInt16(GenericType):
"""Format character for an Unsigned Short.
Class for an 16-bit (2-byte) Unsigned Integer.
"""
_fmt = "!H"
class UBInt32(GenericType):
"""Format character for an Unsigned Int.
Class for an 32-bit (4-byte) Unsigned Integer.
"""
_fmt = "!I"
class UBInt64(GenericType):
"""Format character for an Unsigned Long Long.
Class for an 64-bit (8-byte) Unsigned Integer.
"""
_fmt = "!Q"
class Char(GenericType):
"""Build a double char type according to the length."""
def __init__(self, value=None, length=0):
"""The constructor takes the optional parameters below.
Args:
value: The character to be build.
length (int): Character size.
"""
super().__init__(value)
self.length = length
self._fmt = '!{}{}'.format(self.length, 's')
def pack(self, value=None):
"""Pack the value as a binary representation.
Returns:
bytes: The binary representation.
Raises:
struct.error: If the value does not fit the binary format.
"""
if isinstance(value, type(self)):
return value.pack()
try:
if value is None:
value = self.value
packed = struct.pack(self._fmt, bytes(value, 'ascii'))
return packed[:-1] + b'\0' # null-terminated
except struct.error as err:
msg = "Char Pack error. "
msg += "Class: {}, struct error: {} ".format(type(value).__name__,
err)
raise exceptions.PackException(msg)
def unpack(self, buff, offset=0):
"""Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking.
Raises:
Exception: If there is a struct unpacking error.
"""
try:
begin = offset
end = begin + self.length
unpacked_data = struct.unpack(self._fmt, buff[begin:end])[0]
except struct.error:
raise Exception("%s: %s" % (offset, buff))
self._value = unpacked_data.decode('ascii').rstrip('\0')
class HWAddress(GenericType):
"""Defines a hardware address."""
def __init__(self, hw_address='00:00:00:00:00:00'):
"""The constructor takes the parameters below.
Args:
hw_address (bytes): Hardware address. Defaults to
'00:00:00:00:00:00'.
"""
super().__init__(hw_address)
def pack(self, value=None):
"""Pack the value as a binary representation.
Returns
bytes: The binary representation.
Raises:
struct.error: If the value does not fit the binary format.
"""
if isinstance(value, type(self)):
return value.pack()
if value is not None:
value = value.split(':')
else:
value = self._value.split(':')
try:
return struct.pack('!6B', *[int(x, 16) for x in value])
except struct.error as err:
msg = "HWAddress error. "
msg += "Class: {}, struct error: {} ".format(type(value).__name__,
err)
raise exceptions.PackException(msg)
def unpack(self, buff, offset=0):
"""Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking.
Raises:
Exception: If there is a struct unpacking error.
"""
def _int2hex(n):
h = hex(n)[2:] # remove '0x' prefix
if len(h) == 1:
return '0' + h
else:
return h
try:
unpacked_data = struct.unpack('!6B', buff[offset:offset+6])
except:
raise Exception("%s: %s" % (offset, buff))
transformed_data = ':'.join([_int2hex(x) for x in unpacked_data])
self._value = transformed_data
def get_size(self, value=None):
"""Return the address size in bytes.
Args:
value: In structs, the user can assign other value instead of
this class' instance. Here, in such cases, ``self`` is a class
attribute of the struct.
Returns:
int: The address size in bytes.
"""
return 6
class BinaryData(GenericType):
"""Class to create objects that represent binary data.
This is used in the ``data`` attribute from :class:`.PacketIn` and
:class:`.PacketOut` messages. Both the :meth:`pack` and :meth:`unpack`
methods will return the binary data itself. :meth:`get_size` method will
return the size of the instance using Python's :func:`len`.
"""
def __init__(self, value=b''):
"""The constructor takes the parameter below.
Args:
value (bytes): The binary data. Defaults to an empty value.
"""
super().__init__(value)
def pack(self, value=None):
"""Pack the value as a binary representation.
Returns:
bytes: The binary representation.
Raises:
:exc:`~.exceptions.NotBinaryData`: If value is not :class:`bytes`.
"""
if isinstance(value, type(self)):
return value.pack()
if value is None:
value = self._value
if isinstance(value, bytes) and len(value) > 0:
return value
else:
return b''
def unpack(self, buff, offset=0):
"""Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results. Since the *buff* is binary data, no conversion is done.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking.
"""
self._value = buff
def get_size(self, value=None):
"""Return the size in bytes.
Args:
value (bytes): In structs, the user can assign other value instead
of this class' instance. Here, in such cases, ``self`` is a
class attribute of the struct.
Returns:
int: The address size in bytes.
"""
if value is None:
return len(self._value)
elif isinstance(value, type(self)):
return value.get_size()
else:
return len(value)
class TypeList(list, GenericStruct):
"""Base class for lists that store objects of one single type."""
def __init__(self, items):
"""Initialize the list with one item or a list of items.
Args:
items (iterable, ``pyof_class``): Items to be stored.
"""
super().__init__()
if isinstance(items, list):
self.extend(items)
elif items:
self.append(items)
def extend(self, items):
"""Extend the list by adding all items of ``items``.
Args:
items (iterable): Items to be added to the list.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has an unexpected
type.
"""
for item in items:
self.append(item)
def pack(self, value=None):
"""Pack the value as a binary representation.
Returns:
bytes: The binary representation.
"""
if isinstance(value, type(self)):
return value.pack()
if value is None:
value = self
else:
container = type(self)()
container.extend(value)
value = container
bin_message = b''
try:
for item in value:
bin_message += item.pack()
return bin_message
except exceptions.PackException as err:
msg = "{} pack error: {}".format(type(self).__name__, err)
raise exceptions.PackException(msg)
def unpack(self, buff, item_class, offset=0):
"""Unpack the elements of the list.
This unpack method considers that all elements have the same size.
To use this class with a pyof_class that accepts elements with
different sizes, you must reimplement the unpack method.
Args:
buff (bytes): The binary data to be unpacked.
item_class (:obj:`type`): Class of the expected items on this list.
offset (int): If we need to shift the beginning of the data.
"""
item_size = item_class().get_size()
binary_items = (buff[i:i+item_size] for i in range(offset, len(buff),
item_size))
for binary_item in binary_items:
item = item_class()
item.unpack(binary_item)
self.append(item)
def get_size(self, value=None):
"""Return the size in bytes.
Args:
value: In structs, the user can assign other value instead of
this class' instance. Here, in such cases, ``self`` is a class
attribute of the struct.
Returns:
int: The size in bytes.
"""
if value is None:
if len(self) == 0:
# If this is a empty list, then returns zero
return 0
elif issubclass(type(self[0]), GenericType):
# If the type of the elements is GenericType, then returns the
# length of the list multiplied by the size of the GenericType.
return len(self) * self[0].get_size()
else:
# Otherwise iter over the list accumulating the sizes.
return sum(item.get_size() for item in self)
else:
return type(self)(value).get_size()
def __str__(self):
"""Human-readable object representantion."""
return "{}".format([str(item) for item in self])
class FixedTypeList(TypeList):
"""A list that stores instances of one pyof class."""
_pyof_class = None
def __init__(self, pyof_class, items=None):
"""The constructor parameters follows.
Args:
pyof_class (:obj:`type`): Class of the items to be stored.
items (iterable, ``pyof_class``): Items to be stored.
"""
self._pyof_class = pyof_class
super().__init__(items)
def append(self, item):
"""Append one item to the list.
Args:
item: Item to be appended. Its type must match the one defined in
the constructor.
Raises:
:exc:`~.exceptions.WrongListItemType`: If the item has a different
type than the one specified in the constructor.
"""
if isinstance(item, list):
self.extend(item)
elif item.__class__ == self._pyof_class:
list.append(self, item)
else:
raise exceptions.WrongListItemType(item.__class__.__name__,
self._pyof_class.__name__)
def insert(self, index, item):
"""Insert an item at the specified index.
Args:
index (int): Position to insert the item.
item: Item to be inserted. It must have the type specified in the
constructor.
Raises:
:exc:`~.exceptions.WrongListItemType`: If the item has a different
type than the one specified in the constructor.
"""
if item.__class__ == self._pyof_class:
list.insert(self, index, item)
else:
raise exceptions.WrongListItemType(item.__class__.__name__,
self._pyof_class.__name__)
def unpack(self, buff, offset=0):
"""Unpack the elements of the list.
This unpack method considers that all elements have the same size.
To use this class with a pyof_class that accepts elements with
different sizes, you must reimplement the unpack method.
Args:
buff (bytes): The binary data to be unpacked.
offset (int): If we need to shift the beginning of the data.
"""
super().unpack(buff, self._pyof_class, offset)
class ConstantTypeList(TypeList):
"""List that contains only objects of the same type (class).
The types of all items are expected to be the same as the first item's.
Otherwise, :exc:`~.exceptions.WrongListItemType` is raised in many
list operations.
"""
def __init__(self, items=None):
"""The contructor can contain the items to be stored.
Args:
items (iterable, :class:`object`): Items to be stored.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored.
"""
super().__init__(items)
def append(self, item):
"""Append one item to the list.
Args:
item: Item to be appended.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored.
"""
if isinstance(item, list):
self.extend(item)
elif len(self) == 0:
list.append(self, item)
elif item.__class__ == self[0].__class__:
list.append(self, item)
else:
raise exceptions.WrongListItemType(item.__class__.__name__,
self[0].__class__.__name__)
def insert(self, index, item):
"""Insert an item at the specified index.
Args:
index (int): Position to insert the item.
item: Item to be inserted.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored.
"""
if len(self) == 0:
list.append(self, item)
elif item.__class__ == self[0].__class__:
list.insert(self, index, item)
else:
raise exceptions.WrongListItemType(item.__class__.__name__,
self[0].__class__.__name__)
|