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.util.Arrays;
13 import java.util.Map.Entry;
15 import org.apache.commons.lang3.tuple.Pair;
16 import org.opendaylight.controller.sal.utils.HexEncode;
17 import org.opendaylight.controller.sal.utils.NetUtils;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
22 * Abstract class which represents the generic network packet object It provides
23 * the basic methods which are common for all the packets, like serialize and
27 public abstract class Packet {
28 protected static final Logger logger = LoggerFactory
29 .getLogger(Packet.class);
30 // Access level granted to this packet
31 protected boolean writeAccess;
32 // When deserialized from wire, packet could result corrupted
33 protected boolean corrupted;
34 // The packet that encapsulate this packet
35 protected Packet parent;
36 // The packet encapsulated by this packet
37 protected Packet payload;
38 // The unparsed raw payload carried by this packet
39 protected byte[] rawPayload;
40 // Bit coordinates of packet header fields
41 protected Map<String, Pair<Integer, Integer>> hdrFieldCoordMap;
42 // Header fields values: Map<FieldName,Value>
43 protected Map<String, byte[]> hdrFieldsMap;
44 // The class of the encapsulated packet object
45 protected Class<? extends Packet> payloadClass;
52 public Packet(boolean writeAccess) {
53 this.writeAccess = writeAccess;
57 public Packet getParent() {
61 public Packet getPayload() {
65 public void setParent(Packet parent) {
69 public void setPayload(Packet payload) {
70 this.payload = payload;
73 public void setHeaderField(String headerField, byte[] readValue) {
74 hdrFieldsMap.put(headerField, readValue);
78 * This method deserializes the data bits obtained from the wire into the
79 * respective header and payload which are of type Packet
81 * @param byte[] data - data from wire to deserialize
82 * @param int bitOffset bit position where packet header starts in data
84 * @param int size of packet in bits
86 * @throws PacketException
88 public Packet deserialize(byte[] data, int bitOffset, int size)
89 throws PacketException {
91 // Deserialize the header fields one by one
92 int startOffset = 0, numBits = 0;
93 for (Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
95 String hdrField = pairs.getKey();
96 startOffset = bitOffset + this.getfieldOffset(hdrField);
97 numBits = this.getfieldnumBits(hdrField);
99 byte[] hdrFieldBytes = null;
101 hdrFieldBytes = BitBufferHelper.getBits(data, startOffset,
103 } catch (BufferException e) {
104 throw new PacketException(e.getMessage());
108 * Store the raw read value, checks the payload type and set the
109 * payloadClass accordingly
111 this.setHeaderField(hdrField, hdrFieldBytes);
113 if (logger.isTraceEnabled()) {
114 logger.trace("{}: {}: {} (offset {} bitsize {})",
115 new Object[] { this.getClass().getSimpleName(), hdrField,
116 HexEncode.bytesToHexString(hdrFieldBytes),
117 startOffset, numBits });
121 // Deserialize the payload now
122 int payloadStart = startOffset + numBits;
123 int payloadSize = data.length * NetUtils.NumBitsInAByte - payloadStart;
125 if (payloadClass != null) {
127 payload = payloadClass.newInstance();
128 } catch (Exception e) {
129 throw new RuntimeException(
130 "Error parsing payload for Ethernet packet", e);
132 payload.deserialize(data, payloadStart, payloadSize);
133 payload.setParent(this);
136 * The payload class was not set, it means no class for parsing
137 * this payload is present. Let's store the raw payload if any.
139 int start = payloadStart / NetUtils.NumBitsInAByte;
140 int stop = start + payloadSize / NetUtils.NumBitsInAByte;
141 rawPayload = Arrays.copyOfRange(data, start, stop);
145 // Take care of computation that can be done only after deserialization
146 postDeserializeCustomOperation(data, payloadStart - getHeaderSize());
152 * This method serializes the header and payload from the respective
153 * packet class, into a single stream of bytes to be sent on the wire
155 * @return The byte array representing the serialized Packet
156 * @throws PacketException
158 public byte[] serialize() throws PacketException {
160 // Acquire or compute the serialized payload
161 byte[] payloadBytes = null;
162 if (payload != null) {
163 payloadBytes = payload.serialize();
164 } else if (rawPayload != null) {
165 payloadBytes = rawPayload;
167 int payloadSize = (payloadBytes == null) ? 0 : payloadBytes.length;
169 // Allocate the buffer to contain the full (header + payload) packet
170 int headerSize = this.getHeaderSize() / NetUtils.NumBitsInAByte;
171 byte packetBytes[] = new byte[headerSize + payloadSize];
172 if (payloadBytes != null) {
173 System.arraycopy(payloadBytes, 0, packetBytes, headerSize, payloadSize);
176 // Serialize this packet header, field by field
177 for (Map.Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
179 String field = pairs.getKey();
180 byte[] fieldBytes = hdrFieldsMap.get(field);
181 // Let's skip optional fields when not set
182 if (fieldBytes != null) {
184 BitBufferHelper.setBytes(packetBytes, fieldBytes,
185 getfieldOffset(field), getfieldnumBits(field));
186 } catch (BufferException e) {
187 throw new PacketException(e.getMessage());
192 // Perform post serialize operations (like checksum computation)
193 postSerializeCustomOperation(packetBytes);
195 if (logger.isTraceEnabled()) {
196 logger.trace("{}: {}", this.getClass().getSimpleName(),
197 HexEncode.bytesToHexString(packetBytes));
204 * This method gets called at the end of the serialization process It is
205 * intended for the child packets to insert some custom data into the output
206 * byte stream which cannot be done or cannot be done efficiently during the
207 * normal Packet.serialize() path. An example is the checksum computation
210 * @param byte[] - serialized bytes
211 * @throws PacketException
213 protected void postSerializeCustomOperation(byte[] myBytes)
214 throws PacketException {
219 * This method re-computes the checksum of the bits received on the wire and
220 * validates it with the checksum in the bits received Since the computation
221 * of checksum varies based on the protocol, this method is overridden.
222 * Currently only IPv4 and ICMP do checksum computation and validation. TCP
223 * and UDP need to implement these if required.
225 * @param byte[] data The byte stream representing the Ethernet frame
226 * @param int startBitOffset The bit offset from where the byte array corresponding to this Packet starts in the frame
227 * @throws PacketException
229 protected void postDeserializeCustomOperation(byte[] data, int startBitOffset)
230 throws PacketException {
235 * Gets the header length in bits
237 * @return int the header length in bits
239 public int getHeaderSize() {
242 * We need to iterate over the fields that were read in the frame
243 * (hdrFieldsMap) not all the possible ones described in
244 * hdrFieldCoordMap. For ex, 802.1Q may or may not be there
246 for (Map.Entry<String, byte[]> fieldEntry : hdrFieldsMap.entrySet()) {
247 if (fieldEntry.getValue() != null) {
248 String field = fieldEntry.getKey();
249 size += getfieldnumBits(field);
256 * This method fetches the start bit offset for header field specified by
257 * 'fieldname'. The offset is present in the hdrFieldCoordMap of the
258 * respective packet class
262 * @return Integer - startOffset of the requested field
264 public int getfieldOffset(String fieldName) {
265 return hdrFieldCoordMap.get(fieldName).getLeft();
269 * This method fetches the number of bits for header field specified by
270 * 'fieldname'. The numBits are present in the hdrFieldCoordMap of the
271 * respective packet class
275 * @return Integer - number of bits of the requested field
277 public int getfieldnumBits(String fieldName) {
278 return hdrFieldCoordMap.get(fieldName).getRight();
282 public String toString() {
283 StringBuilder ret = new StringBuilder();
284 ret.append(this.getClass().getSimpleName());
286 for (String field : hdrFieldCoordMap.keySet()) {
287 byte[] value = hdrFieldsMap.get(field);
290 ret.append(HexEncode.bytesToHexString(value));
293 ret.replace(ret.length()-2, ret.length()-1, "]");
294 return ret.toString();
298 * Returns the raw payload carried by this packet in case payload was not
299 * parsed. Caller can call this function in case the getPaylod() returns null.
301 * @return The raw payload if not parsable as an array of bytes, null otherwise
303 public byte[] getRawPayload() {
308 * Set a raw payload in the packet class
310 * @param payload The raw payload as byte array
312 public void setRawPayload(byte[] payload) {
313 this.rawPayload = Arrays.copyOf(payload, payload.length);
317 * Return whether the deserialized packet is to be considered corrupted.
318 * This is the case when the checksum computed after reconstructing the
319 * packet received from wire is not equal to the checksum read from the
320 * stream. For the Packet class which do not have a checksum field, this
321 * function will always return false.
324 * @return true if the deserialized packet's recomputed checksum is not
325 * equal to the packet carried checksum
327 public boolean isCorrupted() {
332 public int hashCode() {
333 final int prime = 31;
334 int result = super.hashCode();
335 result = prime * result
336 + ((this.hdrFieldsMap == null) ? 0 : hdrFieldsMap.hashCode());
341 public boolean equals(Object obj) {
345 if (getClass() != obj.getClass()) {
348 Packet other = (Packet) obj;
349 if (hdrFieldsMap == other.hdrFieldsMap) {
352 if (hdrFieldsMap == null || other.hdrFieldsMap == null) {
355 if (hdrFieldsMap != null && other.hdrFieldsMap != null) {
356 for (String field : hdrFieldsMap.keySet()) {
357 if (!Arrays.equals(hdrFieldsMap.get(field), other.hdrFieldsMap.get(field))) {