1 # Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
20 from . import packet_base
21 from ryu.lib import type_desc
24 class mpls(packet_base.PacketBase):
25 """MPLS (RFC 3032) header encoder/decoder class.
27 NOTE: When decoding, this implementation assumes that the inner protocol
30 An instance has the following attributes at least.
31 Most of them are same to the on-wire counterparts but in host byte order.
32 __init__ takes the corresponding args in this order.
34 ============== ====================
36 ============== ====================
41 ============== ====================
45 _MIN_LEN = struct.calcsize(_PACK_STR)
47 def __init__(self, label=0, exp=0, bsb=1, ttl=255):
48 super(mpls, self).__init__()
56 (label,) = struct.unpack_from(cls._PACK_STR, buf)
58 bsb = (label >> 8) & 1
59 exp = (label >> 9) & 7
61 msg = cls(label, exp, bsb, ttl)
64 return msg, ipv4.ipv4, buf[msg._MIN_LEN:]
66 return msg, mpls, buf[msg._MIN_LEN:]
68 def serialize(self, payload, prev):
69 val = self.label << 12 | self.exp << 9 | self.bsb << 8 | self.ttl
70 return struct.pack(mpls._PACK_STR, val)
73 def label_from_bin(buf):
75 Converts binary representation label to integer.
77 :param buf: Binary representation of label.
78 :return: MPLS Label and BoS bit.
81 mpls_label = type_desc.Int3.to_user(six.binary_type(buf))
82 return mpls_label >> 4, mpls_label & 1
85 def label_to_bin(mpls_label, is_bos=True):
87 Converts integer label to binary representation.
89 :param mpls_label: MPLS Label.
90 :param is_bos: BoS bit.
91 :return: Binary representation of label.
93 return type_desc.Int3.from_user(mpls_label << 4 | is_bos)