Test Failed
Pull Request — master (#404)
by
unknown
01:50
created

Char.__init__()   A

Complexity

Conditions 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 4
cts 4
cp 1
c 0
b 0
f 0
rs 9.4285
cc 1
crap 1
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 CharStringBase(GenericType):
175
    """A null terminated ascii char string."""
176
177
    def pack(self, value=None):
178
        """Pack the value as a binary representation.
179
180 1
        Returns:
181 1
            bytes: The binary representation.
182 1
183
        Raises:
184 1
            struct.error: If the value does not fit the binary format.
185
        """
186
        if isinstance(value, type(self)):
187
            return value.pack()
188 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
189
        try:
190
            if value is None:
191
                value = self.value
192
            packed = struct.pack(self._fmt, bytes(value, 'ascii'))
193 1
            return packed[:-1] + b'\0'  # null-terminated
194 1
        except struct.error as err:
195
            msg = "Char Pack error. "
196 1
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
197 1
                                                         err)
198 1
            raise exceptions.PackException(msg)
199 1
200 1
    def unpack(self, buff, offset=0):
201
        """Unpack a binary message into this object's attributes.
202
203
        Unpack the binary value *buff* and update this object attributes based
204
        on the results.
205
206
        Args:
207 1
            buff (bytes): Binary data package to be unpacked.
208
            offset (int): Where to begin unpacking.
209
210
        Raises:
211
            Exception: If there is a struct unpacking error.
212
        """
213
        try:
214
            begin = offset
215
            end = begin + self.length
216
            unpacked_data = struct.unpack(self._fmt, buff[begin:end])[0]
217
        except struct.error:
218
            raise Exception("%s: %s" % (offset, buff))
219
220 1
        self._value = unpacked_data.decode('ascii').rstrip('\0')
221 1
222 1
223 1
def Char(value=None, length=0):
224
    """Return a CharString class with given length and initial value."""
225
    string_length = length
226
227 1
    class CharString(CharStringBase):
228
        """Class for null terminated ascii strings of fixed length"""
229
        length = string_length
230 1
        _fmt = '!{}{}'.format(length, 's')
231
232
    return CharString(value)
233 1
234 1
235
class IPAddress(GenericType):
236 1
    """Defines a IP address."""
237
238
    netmask = UBInt32()
239
    max_prefix = UBInt32(32)
240
241
    def __init__(self, address="0.0.0.0/32"):
242
        """The constructor takes the parameters below.
243 1
244 1
        Args:
245
            address (str): IP Address using ipv4. Defaults to '0.0.0.0/32'
246 1
        """
247
        if address.find('/') >= 0:
248 1
            address, netmask = address.split('/')
249 1
        else:
250
            netmask = 32
251 1
252
        super().__init__(address)
253
        self.netmask = int(netmask)
254
255
    def pack(self, value=None):
256
        """Pack the value as a binary representation.
257
258
        If the value is None the self._value will be used to pack.
259
260
        Args:
261
            value (str): IP Address with ipv4 format.
262
263
        Returns:
264
            bytes: The binary representation.
265 1
266 1
        Raises:
267
            struct.error: If the value does not fit the binary format.
268 1
        """
269 1
        if isinstance(value, type(self)):
270
            return value.pack()
271 1
272
        if value is None:
273
            value = self._value
274 1
275 1
        if value.find('/') >= 0:
276 1
            value = value.split('/')[0]
277
278
        try:
279
            value = value.split('.')
280
            return struct.pack('!4B', *[int(x) for x in value])
281
        except struct.error as err:
282
            msg = "IPAddress error. "
283 1
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
284
                                                         err)
285
            raise exceptions.PackException(msg)
286
287
    def unpack(self, buff, offset=0):
288
        """Unpack a binary message into this object's attributes.
289
290
        Unpack the binary value *buff* and update this object attributes based
291
        on the results.
292
293
        Args:
294
            buff (bytes): Binary data package to be unpacked.
295
            offset (int): Where to begin unpacking.
296 1
297 1
        Raises:
298 1
            Exception: If there is a struct unpacking error.
299
        """
300
        try:
301
            unpacked_data = struct.unpack('!4B', buff[offset:offset+4])
302 1
            self._value = '.'.join([str(x) for x in unpacked_data])
303
        except struct.error as e:
304
            raise exceptions.UnpackException('%s; %s: %s' % (e, offset, buff))
305
306
    def get_size(self, value=None):
307
        """Return the ip address size in bytes.
308
309
        Args:
310
            value: In structs, the user can assign other value instead of
311
                this class' instance. Here, in such cases, ``self`` is a class
312
                attribute of the struct.
313 1
314
        Returns:
315
            int: The address size in bytes.
316 1
        """
317
        return 4
318
319 1
320
class HWAddress(GenericType):
321
    """Defines a hardware address."""
322
323
    def __init__(self, hw_address='00:00:00:00:00:00'):  # noqa
324
        """The constructor takes the parameters below.
325
326 1
        Args:
327
            hw_address (bytes): Hardware address. Defaults to
328 1
                '00:00:00:00:00:00'.
329
        """
330
        super().__init__(hw_address)
331 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
332
    def pack(self, value=None):
333
        """Pack the value as a binary representation.
334
335
        If the passed value (or the self._value) is zero (int), then the pack
336
        will assume that the value to be packed is '00:00:00:00:00:00'.
337
338
        Returns
339
            bytes: The binary representation.
340 1
341 1
        Raises:
342
            struct.error: If the value does not fit the binary format.
343 1
        """
344 1
        if isinstance(value, type(self)):
345
            return value.pack()
346 1
347
        if value is None:
348
            value = self._value
349 1
350
        if value == 0:
351 1
            value = '00:00:00:00:00:00'
352 1
353
        value = value.split(':')
354
355
        try:
356
            return struct.pack('!6B', *[int(x, 16) for x in value])
357
        except struct.error as err:
358
            msg = "HWAddress error. "
359 1
            msg += "Class: {}, struct error: {} ".format(type(value).__name__,
360
                                                         err)
361
            raise exceptions.PackException(msg)
362
363
    def unpack(self, buff, offset=0):
364
        """Unpack a binary message into this object's attributes.
365
366
        Unpack the binary value *buff* and update this object attributes based
367
        on the results.
368
369
        Args:
370
            buff (bytes): Binary data package to be unpacked.
371
            offset (int): Where to begin unpacking.
372 1
373 1
        Raises:
374
            Exception: If there is a struct unpacking error.
375 1
        """
376 1
        def _int2hex(n):
377
            return "{0:0{1}x}".format(n, 2)
378
379
        try:
380 1
            unpacked_data = struct.unpack('!6B', buff[offset:offset+6])
381 1
        except struct.error as e:
382
            raise exceptions.UnpackException('%s; %s: %s' % (e, offset, buff))
383 1
384
        transformed_data = ':'.join([_int2hex(x) for x in unpacked_data])
385
        self._value = transformed_data
386
387
    def get_size(self, value=None):
388
        """Return the address size in bytes.
389
390
        Args:
391
            value: In structs, the user can assign other value instead of
392
                this class' instance. Here, in such cases, ``self`` is a class
393
                attribute of the struct.
394 1
395
        Returns:
396 1
            int: The address size in bytes.
397
        """
398
        return 6
399
400
    def is_broadcast(self):
401 1
        """Return true if the value is a broadcast address. False otherwise."""
402
        return self.value == 'ff:ff:ff:ff:ff:ff'
403
404
405
class BinaryData(GenericType):
406
    """Class to create objects that represent binary data.
407
408
    This is used in the ``data`` attribute from
409
    :class:`~pyof.v0x01.asynchronous.packet_in.PacketIn` and
410 1
    :class:`~pyof.v0x01.controller2switch.packet_out.PacketOut` messages.
411
    Both the :meth:`pack` and :meth:`unpack` methods will return the
412
    binary data itself. :meth:`get_size` method will
413
    return the size of the instance using Python's :func:`len`.
414
    """
415
416 1
    def __init__(self, value=b''):  # noqa
417
        """The constructor takes the parameter below.
418 1
419
        Args:
420
            value (bytes): The binary data. Defaults to an empty value.
421
422
        Raises:
423
            ValueError: If given value is not bytes.
424
        """
425
        if not isinstance(value, bytes):
426
            raise ValueError('BinaryData must contain bytes.')
427 1
        super().__init__(value)
428 1
429
    def pack(self, value=None):
430 1
        """Pack the value as a binary representation.
431 1
432
        Returns:
433 1
            bytes: The binary representation.
434 1
435
        Raises:
436 1
            :exc:`~.exceptions.NotBinaryData`: If value is not :class:`bytes`.
437
        """
438 1
        if isinstance(value, type(self)):
439
            return value.pack()
440
441
        if value is None:
442
            value = self._value
443
444
        if value:
445
            if isinstance(value, bytes):
446
                return value
447
            raise ValueError('BinaryData must contain bytes.')
448 1
449
        return b''
450 1
451
    def unpack(self, buff, offset=0):
452
        """Unpack a binary message into this object's attributes.
453
454
        Unpack the binary value *buff* and update this object attributes based
455
        on the results. Since the *buff* is binary data, no conversion is done.
456
457
        Args:
458
            buff (bytes): Binary data package to be unpacked.
459
            offset (int): Where to begin unpacking.
460
        """
461 1
        self._value = buff[offset:]
462 1
463 1
    def get_size(self, value=None):
464 1
        """Return the size in bytes.
465
466 1
        Args:
467
            value (bytes): In structs, the user can assign other value instead
468
                of this class' instance. Here, in such cases, ``self`` is a
469 1
                class attribute of the struct.
470
471
        Returns:
472 1
            int: The address size in bytes.
473
        """
474
        if value is None:
475
            return len(self._value)
476
        elif hasattr(value, 'get_size'):
477
            return value.get_size()
478 1
479 1
        return len(value)
480 1
481 1
482
class TypeList(list, GenericStruct):
483
    """Base class for lists that store objects of one single type."""
484 1
485
    def __init__(self, items):
486
        """Initialize the list with one item or a list of items.
487
488
        Args:
489
            items (iterable, ``pyof_class``): Items to be stored.
490
        """
491
        super().__init__()
492
        if isinstance(items, list):
493
            self.extend(items)
494 1
        elif items:
495 1
            self.append(items)
496
497 1
    def extend(self, items):
498
        """Extend the list by adding all items of ``items``.
499
500
        Args:
501
            items (iterable): Items to be added to the list.
502
503 1
        Raises:
504 1
            :exc:`~.exceptions.WrongListItemType`: If an item has an unexpected
505
                type.
506 1
        """
507 1
        for item in items:
508
            self.append(item)
509 1
510 1
    def pack(self, value=None):
511 1
        """Pack the value as a binary representation.
512
513 1
        Returns:
514 1
            bytes: The binary representation.
515 1
        """
516 1
        if isinstance(value, type(self)):
517 1
            return value.pack()
518
519
        if value is None:
520
            value = self
521
        else:
522 1
            container = type(self)(items=None)
523
            container.extend(value)
524
            value = container
525
526
        bin_message = b''
527
        try:
528
            for item in value:
529
                bin_message += item.pack()
530
            return bin_message
531
        except exceptions.PackException as err:
532
            msg = "{} pack error: {}".format(type(self).__name__, err)
533
            raise exceptions.PackException(msg)
534 1
535 1
    def unpack(self, buff, item_class, offset=0):
536
        """Unpack the elements of the list.
537 1
538 1
        This unpack method considers that all elements have the same size.
539 1
        To use this class with a pyof_class that accepts elements with
540 1
        different sizes, you must reimplement the unpack method.
541 1
542
        Args:
543 1
            buff (bytes): The binary data to be unpacked.
544
            item_class (:obj:`type`): Class of the expected items on this list.
545
            offset (int): If we need to shift the beginning of the data.
546
        """
547
        begin = offset
548
        limit_buff = len(buff)
549
550
        while begin < limit_buff:
551
            item = item_class()
552
            item.unpack(buff, begin)
553
            self.append(item)
554 1
            begin += item.get_size()
555 1
556
    def get_size(self, value=None):
557 1
        """Return the size in bytes.
558 1
559
        Args:
560
            value: In structs, the user can assign other value instead of
561
                this class' instance. Here, in such cases, ``self`` is a class
562
                attribute of the struct.
563
564 1
        Returns:
565
            int: The size in bytes.
566 1
        """
567
        if value is None:
568 1
            if not self:
569
                # If this is a empty list, then returns zero
570
                return 0
571
            elif issubclass(type(self[0]), GenericType):
572
                # If the type of the elements is GenericType, then returns the
573 1
                # length of the list multiplied by the size of the GenericType.
574
                return len(self) * self[0].get_size()
575
576 1
            # Otherwise iter over the list accumulating the sizes.
577
            return sum(item.get_size() for item in self)
578 1
579
        return type(self)(value).get_size()
580
581
    def __str__(self):
582
        """Human-readable object representantion."""
583
        return "{}".format([str(item) for item in self])
584
585 1
586 1
class FixedTypeList(TypeList):
587
    """A list that stores instances of one pyof class."""
588 1
589
    _pyof_class = None
590
591
    def __init__(self, pyof_class, items=None):
592
        """The constructor parameters follows.
593
594
        Args:
595
            pyof_class (:obj:`type`): Class of the items to be stored.
596
            items (iterable, ``pyof_class``): Items to be stored.
597
        """
598
        self._pyof_class = pyof_class
599 1
        super().__init__(items)
600
601 1
    def append(self, item):
602 1
        """Append one item to the list.
603
604
        Args:
605
            item: Item to be appended. Its type must match the one defined in
606
                the constructor.
607 1
608
        Raises:
609
            :exc:`~.exceptions.WrongListItemType`: If the item has a different
610
                type than the one specified in the constructor.
611
        """
612
        if isinstance(item, list):
613
            self.extend(item)
614
        elif issubclass(item.__class__, self._pyof_class):
615
            list.append(self, item)
616
        else:
617
            raise exceptions.WrongListItemType(item.__class__.__name__,
618
                                               self._pyof_class.__name__)
619
620
    def insert(self, index, item):
621
        """Insert an item at the specified index.
622
623
        Args:
624
            index (int): Position to insert the item.
625 1
            item: Item to be inserted. It must have the type specified in the
626
                constructor.
627
628
        Raises:
629
            :exc:`~.exceptions.WrongListItemType`: If the item has a different
630
                type than the one specified in the constructor.
631
        """
632
        if issubclass(item.__class__, self._pyof_class):
633
            list.insert(self, index, item)
634
        else:
635
            raise exceptions.WrongListItemType(item.__class__.__name__,
636 1
                                               self._pyof_class.__name__)
637
638
    def unpack(self, buff, offset=0):
639 1
        """Unpack the elements of the list.
640
641
        This unpack method considers that all elements have the same size.
642
        To use this class with a pyof_class that accepts elements with
643
        different sizes, you must reimplement the unpack method.
644
645
        Args:
646
            buff (bytes): The binary data to be unpacked.
647 1
            offset (int): If we need to shift the beginning of the data.
648
        """
649
        super().unpack(buff, self._pyof_class, offset)
650
651
652
class ConstantTypeList(TypeList):
653
    """List that contains only objects of the same type (class).
654
655
    The types of all items are expected to be the same as the first item's.
656
    Otherwise, :exc:`~.exceptions.WrongListItemType` is raised in many
657
    list operations.
658
    """
659 1
660
    def __init__(self, items=None):  # noqa
661
        """The contructor can contain the items to be stored.
662
663
        Args:
664
            items (iterable, :class:`object`): Items to be stored.
665
666
        Raises:
667
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
668
                type than the first item to be stored.
669
        """
670
        super().__init__(items)
671
672
    def append(self, item):
673
        """Append one item to the list.
674
675
        Args:
676
            item: Item to be appended.
677
678
        Raises:
679 1
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
680
                type than the first item to be stored.
681
        """
682
        if isinstance(item, list):
683
            self.extend(item)
684
        elif not self:
685
            list.append(self, item)
686
        elif item.__class__ == self[0].__class__:
687
            list.append(self, item)
688
        else:
689
            raise exceptions.WrongListItemType(item.__class__.__name__,
690
                                               self[0].__class__.__name__)
691
692
    def insert(self, index, item):
693
        """Insert an item at the specified index.
694
695
        Args:
696
            index (int): Position to insert the item.
697
            item: Item to be inserted.
698
699
        Raises:
700
            :exc:`~.exceptions.WrongListItemType`: If an item has a different
701
                type than the first item to be stored.
702
        """
703
        if not self:
704
            list.append(self, item)
705
        elif item.__class__ == self[0].__class__:
706
            list.insert(self, index, item)
707
        else:
708
            raise exceptions.WrongListItemType(item.__class__.__name__,
709
                                               self[0].__class__.__name__)
710