1 # Copyright (C) 2016 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.
21 from . import packet_base
22 from ryu.lib import type_desc
24 LOG = logging.getLogger(__name__)
27 UDP_DST_PORT_OLD = 8472 # for backward compatibility like Linux
30 class vxlan(packet_base.PacketBase):
31 """VXLAN (RFC 7348) header encoder/decoder class.
33 An instance has the following attributes at least.
34 Most of them are same to the on-wire counterparts but in host byte order.
35 __init__ takes the corresponding args in this order.
37 ============== ====================
39 ============== ====================
40 vni VXLAN Network Identifier
41 ============== ====================
44 # Note: Python has no format character for 24 bits field.
45 # we use uint32 format character instead and bit-shift at serializing.
47 _MIN_LEN = struct.calcsize(_PACK_STR)
50 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
51 # |R|R|R|R|I|R|R|R| Reserved |
52 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
53 # | VXLAN Network Identifier (VNI) | Reserved |
54 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
56 def __init__(self, vni):
57 super(vxlan, self).__init__()
62 (flags_reserved, vni_rserved) = struct.unpack_from(cls._PACK_STR, buf)
64 # Check VXLAN flags is valid
65 assert (1 << 3) == (flags_reserved >> 24)
67 # Note: To avoid cyclic import, import ethernet module here
68 from ryu.lib.packet import ethernet
69 return cls(vni_rserved >> 8), ethernet.ethernet, buf[cls._MIN_LEN:]
71 def serialize(self, payload, prev):
72 return struct.pack(self._PACK_STR,
73 1 << (3 + 24), self.vni << 8)
76 def vni_from_bin(buf):
78 Converts binary representation VNI to integer.
80 :param buf: binary representation of VNI.
83 return type_desc.Int3.to_user(six.binary_type(buf))
88 Converts integer VNI to binary representation.
90 :param vni: integer of VNI
91 :return: binary representation of VNI.
93 return type_desc.Int3.from_user(vni)