2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.sal.packet;
11 import java.net.InetAddress;
12 import java.net.UnknownHostException;
14 import java.util.Map.Entry;
16 import org.apache.commons.lang3.tuple.Pair;
17 import org.opendaylight.controller.sal.utils.HexEncode;
18 import org.opendaylight.controller.sal.utils.NetUtils;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * Abstract class which represents the generic network packet object It provides
24 * the basic methods which are common for all the packets, like serialize and
30 public abstract class Packet {
31 protected static final Logger logger = LoggerFactory
32 .getLogger(Packet.class);
33 // Access level granted to this packet
34 protected boolean writeAccess;
35 // When deserialized from wire, packet could result corrupted
36 protected boolean corrupted;
37 // The packet that encapsulate this packet
38 protected Packet parent;
39 // The packet encapsulated by this packet
40 protected Packet payload;
41 // Bit coordinates of packet header fields
42 protected Map<String, Pair<Integer, Integer>> hdrFieldCoordMap;
43 // Header fields values: Map<FieldName,Value>
44 protected Map<String, byte[]> hdrFieldsMap;
45 // The class of the encapsulated packet object
46 protected Class<? extends Packet> payloadClass;
53 public Packet(boolean writeAccess) {
54 this.writeAccess = writeAccess;
55 this.corrupted = false;
58 public Packet getParent() {
62 public Packet getPayload() {
66 public void setParent(Packet parent) {
70 public void setPayload(Packet payload) {
71 this.payload = payload;
74 public void setHeaderField(String headerField, byte[] readValue) {
75 hdrFieldsMap.put(headerField, readValue);
79 * This method deserializes the data bits obtained from the wire into the
80 * respective header and payload which are of type Packet
82 * @param byte[] data - data from wire to deserialize
83 * @param int bitOffset bit position where packet header starts in data
85 * @param int size of packet in bits
87 * @throws PacketException
90 public Packet deserialize(byte[] data, int bitOffset, int size)
91 throws PacketException {
93 Integer startOffset = 0, numBits = 0;
96 for (Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
98 hdrField = pairs.getKey();
99 startOffset = bitOffset + this.getfieldOffset(hdrField);
100 numBits = this.getfieldnumBits(hdrField);
103 hdrFieldBytes = BitBufferHelper.getBits(data, startOffset,
105 } catch (BufferException e) {
106 throw new PacketException(e.getMessage());
109 * Store the raw read value, checks the payload type and set the
110 * payloadClass accordingly
112 this.setHeaderField(hdrField, hdrFieldBytes);
115 postDeserializeCustomOperation(data, startOffset);
117 int payloadStart = startOffset + numBits;
118 // int payloadSize = size - payloadStart;
119 int payloadSize = data.length * NetUtils.NumBitsInAByte - payloadStart;
121 if (payloadClass != null) {
123 payload = payloadClass.newInstance();
124 } catch (Exception e) {
125 throw new RuntimeException(
126 "Error parsing payload for Ethernet packet", e);
128 payload.deserialize(data, payloadStart, payloadSize);
129 payload.setParent(this);
131 // For now let's discard unparsable payload
137 * This method serializes the header and payload bytes from the respective
138 * packet class, into a single stream of bytes to be sent on the wire
140 * @return byte[] - serialized bytes
141 * @throws PacketException
144 public byte[] serialize() throws PacketException {
145 byte[] payloadBytes = null;
147 int headerSize = this.getHeaderSize();
148 int payloadByteOffset = headerSize / NetUtils.NumBitsInAByte;
151 if (payload != null) {
152 payloadBytes = payload.serialize();
153 payloadSize = payloadBytes.length * NetUtils.NumBitsInAByte;
156 size = headerSize + payloadSize;
157 int length = size / NetUtils.NumBitsInAByte;
158 byte headerBytes[] = new byte[length];
160 if (payload != null) {
161 System.arraycopy(payloadBytes, 0, headerBytes, payloadByteOffset,
162 payloadBytes.length);
167 Integer startOffset, numBits;
169 for (Map.Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
171 field = pairs.getKey();
172 fieldBytes = hdrFieldsMap.get(field);
173 // Let's skip optional fields when not set
174 if (fieldBytes != null) {
175 startOffset = this.getfieldOffset(field);
176 numBits = this.getfieldnumBits(field);
178 BitBufferHelper.setBytes(headerBytes, fieldBytes,
179 startOffset, numBits);
180 } catch (BufferException e) {
181 throw new PacketException(e.getMessage());
185 postSerializeCustomOperation(headerBytes);
191 * This method gets called at the end of the serialization process It is
192 * intended for the child packets to insert some custom data into the output
193 * byte stream which cannot be done or cannot be done efficiently during the
194 * normal Packet.serialize() path. An example is the checksum computation
197 * @param byte[] - serialized bytes
198 * @throws PacketException
200 protected void postSerializeCustomOperation(byte[] myBytes)
201 throws PacketException {
206 * This method re-computes the checksum of the bits received on the wire and
207 * validates it with the checksum in the bits received Since the computation
208 * of checksum varies based on the protocol, this method is overridden
209 * Currently only IPv4 does checksum computation and validation TCP and UDP
210 * need to implement these if required
213 * @param int endBitOffset
214 * @throws PacketException
216 protected void postDeserializeCustomOperation(byte[] data, int endBitOffset)
217 throws PacketException {
222 * Gets the header length in bits
224 * @return int the header length in bits
226 public int getHeaderSize() {
229 * We need to iterate over the fields that were read in the frame
230 * (hdrFieldsMap) not all the possible ones described in
231 * hdrFieldCoordMap. For ex, 802.1Q may or may not be there
233 for (Map.Entry<String, byte[]> fieldEntry : hdrFieldsMap.entrySet()) {
234 if (fieldEntry.getValue() != null) {
235 String field = fieldEntry.getKey();
236 size += getfieldnumBits(field);
243 * This method fetches the start bit offset for header field specified by
244 * 'fieldname'. The offset is present in the hdrFieldCoordMap of the
245 * respective packet class
249 * @return Integer - startOffset of the requested field
251 public int getfieldOffset(String fieldName) {
252 return (((Pair<Integer, Integer>) hdrFieldCoordMap.get(fieldName))
257 * This method fetches the number of bits for header field specified by
258 * 'fieldname'. The numBits are present in the hdrFieldCoordMap of the
259 * respective packet class
263 * @return Integer - number of bits of the requested field
265 public int getfieldnumBits(String fieldName) {
266 return (((Pair<Integer, Integer>) hdrFieldCoordMap.get(fieldName))
271 public String toString() {
272 StringBuffer ret = new StringBuffer();
273 for (Map.Entry<String, byte[]> entry : hdrFieldsMap.entrySet()) {
274 ret.append(entry.getKey() + ": ");
275 if (entry.getValue().length == 6) {
276 ret.append(HexEncode.bytesToHexString(entry.getValue()) + " ");
277 } else if (entry.getValue().length == 4) {
279 ret.append(InetAddress.getByAddress(entry.getValue())
280 .getHostAddress() + " ");
281 } catch (UnknownHostException e) {
285 ret.append(((Long) BitBufferHelper.getLong(entry.getValue()))
289 return ret.toString();
293 * Returns true if the packet is corrupted
297 protected boolean isPacketCorrupted() {