2 * Copyright (c) 2013-2014 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.liblldp;
11 import java.util.Arrays;
13 import java.util.Map.Entry;
15 import org.apache.commons.lang3.tuple.Pair;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
20 * Abstract class which represents the generic network packet object It provides
21 * the basic methods which are common for all the packets, like serialize and
25 public abstract class Packet {
26 protected static final Logger logger = LoggerFactory
27 .getLogger(Packet.class);
28 // Access level granted to this packet
29 protected boolean writeAccess;
30 // When deserialized from wire, packet could result corrupted
31 protected boolean corrupted;
32 // The packet that encapsulate this packet
33 protected Packet parent;
34 // The packet encapsulated by this packet
35 protected Packet payload;
36 // The unparsed raw payload carried by this packet
37 protected byte[] rawPayload;
38 // Bit coordinates of packet header fields
39 protected Map<String, Pair<Integer, Integer>> hdrFieldCoordMap;
40 // Header fields values: Map<FieldName,Value>
41 protected Map<String, byte[]> hdrFieldsMap;
42 // The class of the encapsulated packet object
43 protected Class<? extends Packet> payloadClass;
50 public Packet(boolean writeAccess) {
51 this.writeAccess = writeAccess;
55 public Packet getParent() {
59 public Packet getPayload() {
63 public void setParent(Packet parent) {
67 public void setPayload(Packet payload) {
68 this.payload = payload;
71 public void setHeaderField(String headerField, byte[] readValue) {
72 hdrFieldsMap.put(headerField, readValue);
76 * This method deserializes the data bits obtained from the wire into the
77 * respective header and payload which are of type Packet
79 * @param byte[] data - data from wire to deserialize
80 * @param int bitOffset bit position where packet header starts in data
82 * @param int size of packet in bits
84 * @throws PacketException
86 public Packet deserialize(byte[] data, int bitOffset, int size)
87 throws PacketException {
89 // Deserialize the header fields one by one
90 int startOffset = 0, numBits = 0;
91 for (Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
93 String hdrField = pairs.getKey();
94 startOffset = bitOffset + this.getfieldOffset(hdrField);
95 numBits = this.getfieldnumBits(hdrField);
97 byte[] hdrFieldBytes = null;
99 hdrFieldBytes = BitBufferHelper.getBits(data, startOffset,
101 } catch (BufferException e) {
102 throw new PacketException(e.getMessage());
106 * Store the raw read value, checks the payload type and set the
107 * payloadClass accordingly
109 this.setHeaderField(hdrField, hdrFieldBytes);
111 if (logger.isTraceEnabled()) {
112 logger.trace("{}: {}: {} (offset {} bitsize {})",
113 new Object[] { this.getClass().getSimpleName(), hdrField,
114 HexEncode.bytesToHexString(hdrFieldBytes),
115 startOffset, numBits });
119 // Deserialize the payload now
120 int payloadStart = startOffset + numBits;
121 int payloadSize = data.length * NetUtils.NumBitsInAByte - payloadStart;
123 if (payloadClass != null) {
125 payload = payloadClass.newInstance();
126 } catch (Exception e) {
127 throw new RuntimeException(
128 "Error parsing payload for Ethernet packet", e);
130 payload.deserialize(data, payloadStart, payloadSize);
131 payload.setParent(this);
134 * The payload class was not set, it means no class for parsing
135 * this payload is present. Let's store the raw payload if any.
137 int start = payloadStart / NetUtils.NumBitsInAByte;
138 int stop = start + payloadSize / NetUtils.NumBitsInAByte;
139 rawPayload = Arrays.copyOfRange(data, start, stop);
143 // Take care of computation that can be done only after deserialization
144 postDeserializeCustomOperation(data, payloadStart - getHeaderSize());
150 * This method serializes the header and payload from the respective
151 * packet class, into a single stream of bytes to be sent on the wire
153 * @return The byte array representing the serialized Packet
154 * @throws PacketException
156 public byte[] serialize() throws PacketException {
158 // Acquire or compute the serialized payload
159 byte[] payloadBytes = null;
160 if (payload != null) {
161 payloadBytes = payload.serialize();
162 } else if (rawPayload != null) {
163 payloadBytes = rawPayload;
165 int payloadSize = (payloadBytes == null) ? 0 : payloadBytes.length;
167 // Allocate the buffer to contain the full (header + payload) packet
168 int headerSize = this.getHeaderSize() / NetUtils.NumBitsInAByte;
169 byte packetBytes[] = new byte[headerSize + payloadSize];
170 if (payloadBytes != null) {
171 System.arraycopy(payloadBytes, 0, packetBytes, headerSize, payloadSize);
174 // Serialize this packet header, field by field
175 for (Map.Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
177 String field = pairs.getKey();
178 byte[] fieldBytes = hdrFieldsMap.get(field);
179 // Let's skip optional fields when not set
180 if (fieldBytes != null) {
182 BitBufferHelper.setBytes(packetBytes, fieldBytes,
183 getfieldOffset(field), getfieldnumBits(field));
184 } catch (BufferException e) {
185 throw new PacketException(e.getMessage());
190 // Perform post serialize operations (like checksum computation)
191 postSerializeCustomOperation(packetBytes);
193 if (logger.isTraceEnabled()) {
194 logger.trace("{}: {}", this.getClass().getSimpleName(),
195 HexEncode.bytesToHexString(packetBytes));
202 * This method gets called at the end of the serialization process It is
203 * intended for the child packets to insert some custom data into the output
204 * byte stream which cannot be done or cannot be done efficiently during the
205 * normal Packet.serialize() path. An example is the checksum computation
208 * @param byte[] - serialized bytes
209 * @throws PacketException
211 protected void postSerializeCustomOperation(byte[] myBytes)
212 throws PacketException {
217 * This method re-computes the checksum of the bits received on the wire and
218 * validates it with the checksum in the bits received Since the computation
219 * of checksum varies based on the protocol, this method is overridden.
220 * Currently only IPv4 and ICMP do checksum computation and validation. TCP
221 * and UDP need to implement these if required.
223 * @param byte[] data The byte stream representing the Ethernet frame
224 * @param int startBitOffset The bit offset from where the byte array corresponding to this Packet starts in the frame
225 * @throws PacketException
227 protected void postDeserializeCustomOperation(byte[] data, int startBitOffset)
228 throws PacketException {
233 * Gets the header length in bits
235 * @return int the header length in bits
237 public int getHeaderSize() {
240 * We need to iterate over the fields that were read in the frame
241 * (hdrFieldsMap) not all the possible ones described in
242 * hdrFieldCoordMap. For ex, 802.1Q may or may not be there
244 for (Map.Entry<String, byte[]> fieldEntry : hdrFieldsMap.entrySet()) {
245 if (fieldEntry.getValue() != null) {
246 String field = fieldEntry.getKey();
247 size += getfieldnumBits(field);
254 * This method fetches the start bit offset for header field specified by
255 * 'fieldname'. The offset is present in the hdrFieldCoordMap of the
256 * respective packet class
260 * @return Integer - startOffset of the requested field
262 public int getfieldOffset(String fieldName) {
263 return hdrFieldCoordMap.get(fieldName).getLeft();
267 * This method fetches the number of bits for header field specified by
268 * 'fieldname'. The numBits are present in the hdrFieldCoordMap of the
269 * respective packet class
273 * @return Integer - number of bits of the requested field
275 public int getfieldnumBits(String fieldName) {
276 return hdrFieldCoordMap.get(fieldName).getRight();
280 public String toString() {
281 StringBuilder ret = new StringBuilder();
282 ret.append(this.getClass().getSimpleName());
284 for (String field : hdrFieldCoordMap.keySet()) {
285 byte[] value = hdrFieldsMap.get(field);
288 ret.append(HexEncode.bytesToHexString(value));
291 ret.replace(ret.length()-2, ret.length()-1, "]");
292 return ret.toString();
296 * Returns the raw payload carried by this packet in case payload was not
297 * parsed. Caller can call this function in case the getPaylod() returns null.
299 * @return The raw payload if not parsable as an array of bytes, null otherwise
301 public byte[] getRawPayload() {
306 * Set a raw payload in the packet class
308 * @param payload The raw payload as byte array
310 public void setRawPayload(byte[] payload) {
311 this.rawPayload = Arrays.copyOf(payload, payload.length);
315 * Return whether the deserialized packet is to be considered corrupted.
316 * This is the case when the checksum computed after reconstructing the
317 * packet received from wire is not equal to the checksum read from the
318 * stream. For the Packet class which do not have a checksum field, this
319 * function will always return false.
322 * @return true if the deserialized packet's recomputed checksum is not
323 * equal to the packet carried checksum
325 public boolean isCorrupted() {
330 public int hashCode() {
331 final int prime = 31;
332 int result = super.hashCode();
333 result = prime * result
334 + ((this.hdrFieldsMap == null) ? 0 : hdrFieldsMap.hashCode());
339 public boolean equals(Object obj) {
343 if (getClass() != obj.getClass()) {
346 Packet other = (Packet) obj;
347 if (hdrFieldsMap == other.hdrFieldsMap) {
350 if (hdrFieldsMap == null || other.hdrFieldsMap == null) {
353 if (hdrFieldsMap != null && other.hdrFieldsMap != null) {
354 for (String field : hdrFieldsMap.keySet()) {
355 if (!Arrays.equals(hdrFieldsMap.get(field), other.hdrFieldsMap.get(field))) {