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.
18 from ryu.lib import stringify
21 @six.add_metaclass(abc.ABCMeta)
22 class PacketBase(stringify.StringifyMixin):
23 """A base class for a protocol (ethernet, ipv4, ...) header."""
27 def get_packet_type(cls, type_):
28 """Per-protocol dict-like get method.
30 Provided for convenience of protocol implementers.
32 return cls._TYPES.get(type_)
35 def register_packet_type(cls, cls_, type_):
36 """Per-protocol dict-like set method.
38 Provided for convenience of protocol implementers.
40 cls._TYPES[type_] = cls_
43 super(PacketBase, self).__init__()
49 def protocol_name(self):
50 return self.__class__.__name__
55 """Decode a protocol header.
57 This method is used only when decoding a packet.
59 Decode a protocol header at offset 0 in bytearray *buf*.
60 Returns the following three objects.
62 * An object to describe the decoded header.
64 * A packet_base.PacketBase subclass appropriate for the rest of
65 the packet. None when the rest of the packet should be considered
73 def serialize(self, payload, prev):
74 """Encode a protocol header.
76 This method is used only when encoding a packet.
78 Encode a protocol header.
79 Returns a bytearray which contains the header.
81 *payload* is the rest of the packet which will immediately follow
84 *prev* is a packet_base.PacketBase subclass for the outer protocol
85 header. *prev* is None if the current header is the outer-most.
86 For example, *prev* is ipv4 or ipv6 for tcp.serialize.