Passed
Pull Request — master (#421)
by
unknown
01:55
created

BinaryData.get_size()   A

Complexity

Conditions 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 7
cts 8
cp 0.875
rs 9.4285
c 0
b 0
f 0
cc 3
crap 3.0175
1
"""Basic types used in structures and messages."""
2
3
# System imports
4 1
import struct
5
6
# Local source tree imports
7 1
from pyof.foundation import exceptions
8 1
from pyof.foundation.base import GenericStruct, GenericType
9
10
# Third-party imports
11
12 1
__all__ = ('BinaryData', 'Char', 'ConstantTypeList', 'FixedTypeList',
13
           'IPAddress', 'DPID', 'HWAddress', 'Pad', 'UBInt8', 'UBInt16',
14
           'UBInt32', 'UBInt64')
15
16
17 1
class Pad(GenericType):
18
    """Class for padding attributes."""
19
20 1
    _fmt = ''
21
22 1
    def __init__(self, length=0):
23
        """Pad up to ``length``, in bytes.
24
25
        Args:
26
            length (int): Total length, in bytes.
27
        """
28 1
        super().__init__()
29 1
        self._length = length
30
31 1
    def __repr__(self):
32
        return "{}({})".format(type(self).__name__, self._length)
33
34 1
    def __str__(self):
35
        return '0' * self._length
36
37 1
    def get_size(self, value=None):
38
        """Return the type size in bytes.
39
40
        Args:
41
            value (int): In structs, the user can assign other value instead of
42
                this class' instance. Here, in such cases, ``self`` is a class
43
                attribute of the struct.
44
45
        Returns:
46
            int: Size in bytes.
47
        """
48 1
        return self._length
49
50 1
    def unpack(self, buff, offset=0):
51
        """Unpack *buff* into this object.
52
53
        Do nothing, since the _length is already defined and it is just a Pad.
54
        Keep buff and offset just for compability with other unpack methods.
55
56
        Args:
57
            buff: Buffer where data is located.
58
            offset (int): Where data stream begins.
59
        """
60 1
        pass
61
62 1
    def pack(self, value=None):
63
        """Pack the object.
64
65
        Args:
66
            value (int): In structs, the user can assign other value instead of
67
                this class' instance. Here, in such cases, ``self`` is a class
68
                attribute of the struct.
69
70
        Returns:
71
            bytes: the byte 0 (zero) *length* times.
72
        """
73 1
        return b'\x00' * self._length
74
75
76 1
class UBInt8(GenericType):
77
    """Format character for an Unsigned Char.
78
79
    Class for an 8-bit (1-byte) Unsigned Integer.
80
    """
81
82 1
    _fmt = "!B"
83
84
85 1
class UBInt16(GenericType):
86
    """Format character for an Unsigned Short.
87
88
    Class for an 16-bit (2-byte) Unsigned Integer.
89
    """
90
91 1
    _fmt = "!H"
92
93
94 1
class UBInt32(GenericType):
95
    """Format character for an Unsigned Int.
96
97
    Class for an 32-bit (4-byte) Unsigned Integer.
98
    """
99
100 1
    _fmt = "!I"
101
102
103 1
class UBInt64(GenericType):
104
    """Format character for an Unsigned Long Long.
105
106
    Class for an 64-bit (8-byte) Unsigned Integer.
107
    """
108
109 1
    _fmt = "!Q"
110
111
112 1
class DPID(GenericType):
113
    """DataPath ID. Identifies a switch."""
114
115 1
    _fmt = "!8B"
116
117 1
    def __init__(self, dpid=None):
118
        """Create an instance and optionally set its dpid value.
119
120
        Args:
121
            dpid (str): String with DPID value(e.g. `00:00:00:00:00:00:00:01`).
122
        """
123 1
        super().__init__(value=dpid)
124
125 1
    def __str__(self):
126
        return self._value
127
128 1
    @property
129
    def value(self):
130
        """Return dpid value.
131
132
        Returns:
133 1
            str: DataPath ID stored by DPID class.
134
        """
135
        return self._value
136
137
    def pack(self, value=None):
138
        """Pack the value as a binary representation.
139
140
        Returns:
141
            bytes: The binary representation.
142 1
143 1
        Raises:
144 1
            struct.error: If the value does not fit the binary format.
145 1
        """
146 1
        if isinstance(value, type(self)):
147
            return value.pack()
148 1
        if value is None:
149
            value = self._value
150
        return struct.pack('!8B', *[int(v, 16) for v in value.split(':')])
151
152
    def unpack(self, buff, offset=0):
153
        """Unpack a binary message into this object's attributes.
154
155
        Unpack the binary value *buff* and update this object attributes based
156
        on the results.
157
158
        Args:
159
            buff (bytes): Binary data package to be unpacked.
160
            offset (int): Where to begin unpacking.
161 1
162 1
        Raises:
163 1
            Exception: If there is a struct unpacking error.
164 1
        """
165 1
        begin = offset
166 1
        hexas = []
167 1
        while begin < offset + 8:
168
            number = struct.unpack("!B", buff[begin:begin+1])[0]
169
            hexas.append("%.2x" % number)
170 1
            begin += 1
171
        self._value = ':'.join(hexas)
172
173 1
174
class Char(GenericType):
175
    """Build a double char type according to the length."""
176
177
    def __init__(self, value=None, length=0):
178
        """The constructor takes the optional parameters below.
179
180 1
        Args:
181 1
            value: The character to be build.
182 1
            length (int): Character size.
183
        """
184 1
        super().__init__(value)
185
        self.length = length
186
        self._fmt = '!{}{}'.format(self.length, 's')
187
188 View Code Duplication
    def pack(self, value=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
189
        """Pack the value as a binary representation.
190
191
        Returns:
192
            bytes: The binary representation.
193 1
194 1
        Raises:
195
            struct.error: If the value does not fit the binary format.
196 1
        """
197 1
        if isinstance(value, type(self)):
198 1
            return value.pack()
199 1
200 1
        try:
201
            if value is None:
202
                value = self.value
203
            packed = struct.pack(self._fmt, bytes(value, 'ascii'))
204
            return packed[:-1] + b'\0'  # null-terminated
205
        except struct.error as err:
206
            msg = "Char Pack error. "
207 1
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
208
                                                         err)
209
            raise exceptions.PackException(msg)
210
211
    def unpack(self, buff, offset=0):
212
        """Unpack a binary message into this object's attributes.
213
214
        Unpack the binary value *buff* and update this object attributes based
215
        on the results.
216
217
        Args:
218
            buff (bytes): Binary data package to be unpacked.
219
            offset (int): Where to begin unpacking.
220 1
221 1
        Raises:
222 1
            Exception: If there is a struct unpacking error.
223 1
        """
224
        try:
225
            begin = offset
226
            end = begin + self.length
227 1
            unpacked_data = struct.unpack(self._fmt, buff[begin:end])[0]
228
        except struct.error:
229
            raise Exception("%s: %s" % (offset, buff))
230 1
231
        self._value = unpacked_data.decode('ascii').rstrip('\0')
232
233 1
234 1
class IPAddress(GenericType):
235
    """Defines a IP address."""
236 1
237
    netmask = UBInt32()
238
    max_prefix = UBInt32(32)
239
240
    def __init__(self, address="0.0.0.0/32"):
241
        """The constructor takes the parameters below.
242
243 1
        Args:
244 1
            address (str): IP Address using ipv4. Defaults to '0.0.0.0/32'
245
        """
246 1
        if address.find('/') >= 0:
247
            address, netmask = address.split('/')
248 1
        else:
249 1
            netmask = 32
250
251 1
        super().__init__(address)
252
        self.netmask = int(netmask)
253
254 View Code Duplication
    def pack(self, value=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
255
        """Pack the value as a binary representation.
256
257
        If the value is None the self._value will be used to pack.
258
259
        Args:
260
            value (str): IP Address with ipv4 format.
261
262
        Returns:
263
            bytes: The binary representation.
264
265 1
        Raises:
266 1
            struct.error: If the value does not fit the binary format.
267
        """
268 1
        if isinstance(value, type(self)):
269 1
            return value.pack()
270
271 1
        if value is None:
272
            value = self._value
273
274 1
        if value.find('/') >= 0:
275 1
            value = value.split('/')[0]
276 1
277
        try:
278
            value = value.split('.')
279
            return struct.pack('!4B', *[int(x) for x in value])
280
        except struct.error as err:
281
            msg = "IPAddress error. "
282
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
283 1
                                                         err)
284
            raise exceptions.PackException(msg)
285
286
    def unpack(self, buff, offset=0):
287
        """Unpack a binary message into this object's attributes.
288
289
        Unpack the binary value *buff* and update this object attributes based
290
        on the results.
291
292
        Args:
293
            buff (bytes): Binary data package to be unpacked.
294
            offset (int): Where to begin unpacking.
295
296 1
        Raises:
297 1
            Exception: If there is a struct unpacking error.
298 1
        """
299
        try:
300
            unpacked_data = struct.unpack('!4B', buff[offset:offset+4])
301
            self._value = '.'.join([str(x) for x in unpacked_data])
302 1
        except struct.error as e:
303
            raise exceptions.UnpackException('%s; %s: %s' % (e, offset, buff))
304
305
    def get_size(self, value=None):
306
        """Return the ip address size in bytes.
307
308
        Args:
309
            value: In structs, the user can assign other value instead of
310
                this class' instance. Here, in such cases, ``self`` is a class
311
                attribute of the struct.
312
313 1
        Returns:
314
            int: The address size in bytes.
315
        """
316 1
        return 4
317
318
319 1
class HWAddress(GenericType):
320
    """Defines a hardware address."""
321
322
    def __init__(self, hw_address='00:00:00:00:00:00'):  # noqa
323
        """The constructor takes the parameters below.
324
325
        Args:
326 1
            hw_address (bytes): Hardware address. Defaults to
327
                '00:00:00:00:00:00'.
328 1
        """
329
        super().__init__(hw_address)
330
331 View Code Duplication
    def pack(self, value=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
332
        """Pack the value as a binary representation.
333
334
        If the passed value (or the self._value) is zero (int), then the pack
335
        will assume that the value to be packed is '00:00:00:00:00:00'.
336
337
        Returns
338
            bytes: The binary representation.
339
340 1
        Raises:
341 1
            struct.error: If the value does not fit the binary format.
342
        """
343 1
        if isinstance(value, type(self)):
344 1
            return value.pack()
345
346 1
        if value is None:
347
            value = self._value
348
349 1
        if value == 0:
350
            value = '00:00:00:00:00:00'
351 1
352 1
        value = value.split(':')
353
354
        try:
355
            return struct.pack('!6B', *[int(x, 16) for x in value])
356
        except struct.error as err:
357
            msg = "HWAddress error. "
358
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
359 1
                                                         err)
360
            raise exceptions.PackException(msg)
361
362
    def unpack(self, buff, offset=0):
363
        """Unpack a binary message into this object's attributes.
364
365
        Unpack the binary value *buff* and update this object attributes based
366
        on the results.
367
368
        Args:
369
            buff (bytes): Binary data package to be unpacked.
370
            offset (int): Where to begin unpacking.
371
372 1
        Raises:
373 1
            Exception: If there is a struct unpacking error.
374
        """
375 1
        def _int2hex(n):
376 1
            return "{0:0{1}x}".format(n, 2)
377
378
        try:
379
            unpacked_data = struct.unpack('!6B', buff[offset:offset+6])
380 1
        except struct.error as e:
381 1
            raise exceptions.UnpackException('%s; %s: %s' % (e, offset, buff))
382
383 1
        transformed_data = ':'.join([_int2hex(x) for x in unpacked_data])
384
        self._value = transformed_data
385
386
    def get_size(self, value=None):
387
        """Return the address size in bytes.
388
389
        Args:
390
            value: In structs, the user can assign other value instead of
391
                this class' instance. Here, in such cases, ``self`` is a class
392
                attribute of the struct.
393
394 1
        Returns:
395
            int: The address size in bytes.
396 1
        """
397
        return 6
398
399
    def is_broadcast(self):
400
        """Return true if the value is a broadcast address. False otherwise."""
401 1
        return self.value == 'ff:ff:ff:ff:ff:ff'
402
403
404
class BinaryData(GenericType):
405
    """Class to create objects that represent binary data.
406
407
    This is used in the ``data`` attribute from
408
    :class:`~pyof.v0x01.asynchronous.packet_in.PacketIn` and
409
    :class:`~pyof.v0x01.controller2switch.packet_out.PacketOut` messages.
410 1
    Both the :meth:`pack` and :meth:`unpack` methods will return the
411
    binary data itself. :meth:`get_size` method will
412
    return the size of the instance using Python's :func:`len`.
413
    """
414
415
    def __init__(self, value=None):  # noqa
416 1
        """The constructor takes the parameter below.
417
418 1
        Args:
419
            value (bytes): The binary data. Defaults to an empty value.
420
421
        Raises:
422
            ValueError: If given value is not bytes.
423
        """
424
        value = self._pack_if_necessary(value)
425
        super().__init__(value)
426
427 1
    @staticmethod
428 1
    def _pack_if_necessary(value):
429
        if hasattr(value, 'pack') and callable(value.pack):
430 1
            value = value.pack()
431 1
        elif not value:
432
            value = b''
433 1
434 1
        if not isinstance(value, bytes):
435
            msg = 'BinaryData value must contain bytes or have pack method; '
436 1
            msg += 'Received type {} value: {}'.format(type(value), value)
437
            raise ValueError(msg)
438 1
439
        return value
440
441
    def pack(self, value=None):
442
        """Pack the value as a binary representation.
443
444
        Returns:
445
            bytes: The binary representation.
446
447
        Raises:
448 1
            :exc:`~.exceptions.NotBinaryData`: If value is not :class:`bytes`.
449
        """
450 1
        if value is None:
451
            value = self._value
452
        else:
453
            value = self._pack_if_necessary(value)
454
        return value
455
456
    def unpack(self, buff, offset=0):
457
        """Unpack a binary message into this object's attributes.
458
459
        Unpack the binary value *buff* and update this object attributes based
460
        on the results. Since the *buff* is binary data, no conversion is done.
461 1
462 1
        Args:
463 1
            buff (bytes): Binary data package to be unpacked.
464 1
            offset (int): Where to begin unpacking.
465
        """
466 1
        self._value = buff[offset:]
467
468
    def get_size(self, value=None):
469 1
        """Return the size in bytes.
470
471
        Args:
472 1
            value (bytes): In structs, the user can assign other value instead
473
                of this class' instance. Here, in such cases, ``self`` is a
474
                class attribute of the struct.
475
476
        Returns:
477
            int: The address size in bytes.
478 1
        """
479 1
        if value is None:
480 1
            return len(self._value)
481 1
        elif hasattr(value, 'get_size'):
482
            return value.get_size()
483
484 1
        return len(value)
485
486
487
class TypeList(list, GenericStruct):
488
    """Base class for lists that store objects of one single type."""
489
490
    def __init__(self, items):
491
        """Initialize the list with one item or a list of items.
492
493
        Args:
494 1
            items (iterable, ``pyof_class``): Items to be stored.
495 1
        """
496
        super().__init__()
497 1
        if isinstance(items, list):
498
            self.extend(items)
499
        elif items:
500
            self.append(items)
501
502
    def extend(self, items):
503 1
        """Extend the list by adding all items of ``items``.
504 1
505
        Args:
506 1
            items (iterable): Items to be added to the list.
507 1
508
        Raises:
509 1
            :exc:`~.exceptions.WrongListItemType`: If an item has an unexpected
510 1
                type.
511 1
        """
512
        for item in items:
513 1
            self.append(item)
514 1
515 1
    def pack(self, value=None):
516 1
        """Pack the value as a binary representation.
517 1
518
        Returns:
519
            bytes: The binary representation.
520
        """
521
        if isinstance(value, type(self)):
522 1
            return value.pack()
523
524
        if value is None:
525
            value = self
526
        else:
527
            container = type(self)(items=None)
528
            container.extend(value)
529
            value = container
530
531
        bin_message = b''
532
        try:
533
            for item in value:
534 1
                bin_message += item.pack()
535 1
            return bin_message
536
        except exceptions.PackException as err:
537 1
            msg = "{} pack error: {}".format(type(self).__name__, err)
538 1
            raise exceptions.PackException(msg)
539 1
540 1
    def unpack(self, buff, item_class, offset=0):
541 1
        """Unpack the elements of the list.
542
543 1
        This unpack method considers that all elements have the same size.
544
        To use this class with a pyof_class that accepts elements with
545
        different sizes, you must reimplement the unpack method.
546
547
        Args:
548
            buff (bytes): The binary data to be unpacked.
549
            item_class (:obj:`type`): Class of the expected items on this list.
550
            offset (int): If we need to shift the beginning of the data.
551
        """
552
        begin = offset
553
        limit_buff = len(buff)
554 1
555 1
        while begin < limit_buff:
556
            item = item_class()
557 1
            item.unpack(buff, begin)
558 1
            self.append(item)
559
            begin += item.get_size()
560
561
    def get_size(self, value=None):
562
        """Return the size in bytes.
563
564 1
        Args:
565
            value: In structs, the user can assign other value instead of
566 1
                this class' instance. Here, in such cases, ``self`` is a class
567
                attribute of the struct.
568 1
569
        Returns:
570
            int: The size in bytes.
571
        """
572
        if value is None:
573 1
            if not self:
574
                # If this is a empty list, then returns zero
575
                return 0
576 1
            elif issubclass(type(self[0]), GenericType):
577
                # If the type of the elements is GenericType, then returns the
578 1
                # length of the list multiplied by the size of the GenericType.
579
                return len(self) * self[0].get_size()
580
581
            # Otherwise iter over the list accumulating the sizes.
582
            return sum(item.get_size() for item in self)
583
584
        return type(self)(value).get_size()
585 1
586 1
    def __str__(self):
587
        """Human-readable object representantion."""
588 1
        return "{}".format([str(item) for item in self])
589
590
591
class FixedTypeList(TypeList):
592
    """A list that stores instances of one pyof class."""
593
594
    _pyof_class = None
595
596
    def __init__(self, pyof_class, items=None):
597
        """The constructor parameters follows.
598
599 1
        Args:
600
            pyof_class (:obj:`type`): Class of the items to be stored.
601 1
            items (iterable, ``pyof_class``): Items to be stored.
602 1
        """
603
        self._pyof_class = pyof_class
604
        super().__init__(items)
605
606
    def append(self, item):
607 1
        """Append one item to the list.
608
609
        Args:
610
            item: Item to be appended. Its type must match the one defined in
611
                the constructor.
612
613
        Raises:
614
            :exc:`~.exceptions.WrongListItemType`: If the item has a different
615
                type than the one specified in the constructor.
616
        """
617
        if isinstance(item, list):
618
            self.extend(item)
619
        elif issubclass(item.__class__, self._pyof_class):
620
            list.append(self, item)
621
        else:
622
            raise exceptions.WrongListItemType(item.__class__.__name__,
623
                                               self._pyof_class.__name__)
624
625 1
    def insert(self, index, item):
626
        """Insert an item at the specified index.
627
628
        Args:
629
            index (int): Position to insert the item.
630
            item: Item to be inserted. It must have the type specified in the
631
                constructor.
632
633
        Raises:
634
            :exc:`~.exceptions.WrongListItemType`: If the item has a different
635
                type than the one specified in the constructor.
636 1
        """
637
        if issubclass(item.__class__, self._pyof_class):
638
            list.insert(self, index, item)
639 1
        else:
640
            raise exceptions.WrongListItemType(item.__class__.__name__,
641
                                               self._pyof_class.__name__)
642
643
    def unpack(self, buff, offset=0):
644
        """Unpack the elements of the list.
645
646
        This unpack method considers that all elements have the same size.
647 1
        To use this class with a pyof_class that accepts elements with
648
        different sizes, you must reimplement the unpack method.
649
650
        Args:
651
            buff (bytes): The binary data to be unpacked.
652
            offset (int): If we need to shift the beginning of the data.
653
        """
654
        super().unpack(buff, self._pyof_class, offset)
655
656
657
class ConstantTypeList(TypeList):
658
    """List that contains only objects of the same type (class).
659 1
660
    The types of all items are expected to be the same as the first item's.
661
    Otherwise, :exc:`~.exceptions.WrongListItemType` is raised in many
662
    list operations.
663
    """
664
665
    def __init__(self, items=None):  # noqa
666
        """The contructor can contain the items to be stored.
667
668
        Args:
669
            items (iterable, :class:`object`): Items to be stored.
670
671
        Raises:
672
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
673
                type than the first item to be stored.
674
        """
675
        super().__init__(items)
676
677
    def append(self, item):
678
        """Append one item to the list.
679 1
680
        Args:
681
            item: Item to be appended.
682
683
        Raises:
684
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
685
                type than the first item to be stored.
686
        """
687
        if isinstance(item, list):
688
            self.extend(item)
689
        elif not self:
690
            list.append(self, item)
691
        elif item.__class__ == self[0].__class__:
692
            list.append(self, item)
693
        else:
694
            raise exceptions.WrongListItemType(item.__class__.__name__,
695
                                               self[0].__class__.__name__)
696
697
    def insert(self, index, item):
698
        """Insert an item at the specified index.
699
700
        Args:
701
            index (int): Position to insert the item.
702
            item: Item to be inserted.
703
704
        Raises:
705
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
706
                type than the first item to be stored.
707
        """
708
        if not self:
709
            list.append(self, item)
710
        elif item.__class__ == self[0].__class__:
711
            list.insert(self, index, item)
712
        else:
713
            raise exceptions.WrongListItemType(item.__class__.__name__,
714
                                               self[0].__class__.__name__)
715