2 * Copyright (c) 2013, 2015 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
8 package org.opendaylight.openflowplugin.libraries.liblldp;
10 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
11 import java.util.Arrays;
13 import java.util.Map.Entry;
14 import java.util.function.Supplier;
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
24 public abstract class Packet {
25 private static final Logger LOG = LoggerFactory.getLogger(Packet.class);
27 // Access level granted to this packet
28 protected final boolean writeAccess;
30 // When deserialized from wire, packet could result corrupted
31 protected boolean corrupted;
33 // The packet that encapsulate this packet
34 protected Packet parent;
36 // The packet encapsulated by this packet
37 protected Packet payload;
39 // The unparsed raw payload carried by this packet
40 protected byte[] rawPayload;
42 // Bit coordinates of packet header fields
43 protected Map<String, Pair<Integer, Integer>> hdrFieldCoordMap;
45 // Header fields values: Map<FieldName,Value>
46 protected Map<String, byte[]> hdrFieldsMap;
48 // The class of the encapsulated packet object
49 protected Supplier<Packet> payloadFactory;
56 public Packet(final boolean writeAccess) {
57 this.writeAccess = writeAccess;
61 public Packet getParent() {
65 public Packet getPayload() {
69 public void setParent(final Packet parent) {
73 public void setPayload(final Packet payload) {
74 this.payload = payload;
77 public void setHeaderField(final String headerField, final byte[] readValue) {
78 hdrFieldsMap.put(headerField, readValue);
82 * This method deserializes the data bits obtained from the wire into the
83 * respective header and payload which are of type Packet.
85 * @param data - data from wire to deserialize
86 * @param bitOffset bit position where packet header starts in data
88 * @param size size of packet in bits
90 * @throws PacketException if deserialization fails
92 public Packet deserialize(final byte[] data, final int bitOffset, final int size)
93 throws PacketException {
95 // Deserialize the header fields one by one
98 for (Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
100 String hdrField = pairs.getKey();
101 startOffset = bitOffset + getfieldOffset(hdrField);
102 numBits = getfieldnumBits(hdrField);
104 byte[] hdrFieldBytes;
106 hdrFieldBytes = BitBufferHelper.getBits(data, startOffset,
108 } catch (final BufferException e) {
109 throw new PacketException("getBits failed", e);
113 * Store the raw read value, checks the payload type and set the
114 * payloadClass accordingly
116 setHeaderField(hdrField, hdrFieldBytes);
118 if (LOG.isTraceEnabled()) {
119 LOG.trace("{}: {}: {} (offset {} bitsize {})", this.getClass().getSimpleName(), hdrField,
120 HexEncode.bytesToHexString(hdrFieldBytes), startOffset, numBits);
124 // Deserialize the payload now
125 int payloadStart = startOffset + numBits;
126 int payloadSize = data.length * NetUtils.NUM_BITS_IN_A_BYTE - payloadStart;
128 if (payloadFactory != null) {
129 payload = payloadFactory.get();
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.NUM_BITS_IN_A_BYTE;
138 int stop = start + payloadSize / NetUtils.NUM_BITS_IN_A_BYTE;
139 rawPayload = Arrays.copyOfRange(data, start, stop);
142 // Take care of computation that can be done only after deserialization
143 postDeserializeCustomOperation(data, payloadStart - getHeaderSize());
149 * This method serializes the header and payload from the respective
150 * packet class, into a single stream of bytes to be sent on the wire.
152 * @return The byte array representing the serialized Packet
153 * @throws PacketException if serialization fails
155 public byte[] serialize() throws PacketException {
157 // Acquire or compute the serialized payload
158 byte[] payloadBytes = null;
159 if (payload != null) {
160 payloadBytes = payload.serialize();
161 } else if (rawPayload != null) {
162 payloadBytes = rawPayload;
164 int payloadSize = payloadBytes == null ? 0 : payloadBytes.length;
166 // Allocate the buffer to contain the full (header + payload) packet
167 int headerSize = getHeaderSize() / NetUtils.NUM_BITS_IN_A_BYTE;
168 byte[] packetBytes = new byte[headerSize + payloadSize];
169 if (payloadBytes != null) {
170 System.arraycopy(payloadBytes, 0, packetBytes, headerSize, payloadSize);
173 // Serialize this packet header, field by field
174 for (Map.Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
176 String field = pairs.getKey();
177 byte[] fieldBytes = hdrFieldsMap.get(field);
178 // Let's skip optional fields when not set
179 if (fieldBytes != null) {
181 BitBufferHelper.copyBitsFromLsb(packetBytes, fieldBytes,
182 getfieldOffset(field), getfieldnumBits(field));
183 } catch (final BufferException e) {
184 throw new PacketException("setBytes failed", e);
189 // Perform post serialize operations (like checksum computation)
190 postSerializeCustomOperation(packetBytes);
192 if (LOG.isTraceEnabled()) {
193 LOG.trace("packet {}: {}", this.getClass().getSimpleName(),
194 HexEncode.bytesToHexString(packetBytes));
201 * This method gets called at the end of the serialization process It is
202 * intended for the child packets to insert some custom data into the output
203 * byte stream which cannot be done or cannot be done efficiently during the
204 * normal Packet.serialize() path. An example is the checksum computation
207 * @param myBytes serialized bytes
208 * @throws PacketException on failure
210 protected void postSerializeCustomOperation(final byte[] myBytes) throws PacketException {
215 * This method re-computes the checksum of the bits received on the wire and
216 * validates it with the checksum in the bits received Since the computation
217 * of checksum varies based on the protocol, this method is overridden.
218 * Currently only IPv4 and ICMP do checksum computation and validation. TCP
219 * and UDP need to implement these if required.
221 * @param data The byte stream representing the Ethernet frame
222 * @param startBitOffset The bit offset from where the byte array corresponding to this Packet starts in the frame
223 * @throws PacketException on failure
225 protected void postDeserializeCustomOperation(final byte[] data, final int startBitOffset) throws PacketException {
230 * Gets the header length in bits.
232 * @return int the header length in bits
234 public int getHeaderSize() {
237 * We need to iterate over the fields that were read in the frame
238 * (hdrFieldsMap) not all the possible ones described in
239 * hdrFieldCoordMap. For ex, 802.1Q may or may not be there
241 for (Map.Entry<String, byte[]> fieldEntry : hdrFieldsMap.entrySet()) {
242 if (fieldEntry.getValue() != null) {
243 String field = fieldEntry.getKey();
244 size += getfieldnumBits(field);
251 * This method fetches the start bit offset for header field specified by
252 * 'fieldname'. The offset is present in the hdrFieldCoordMap of the
253 * respective packet class
255 * @return Integer - startOffset of the requested field
257 public int getfieldOffset(final String fieldName) {
258 return hdrFieldCoordMap.get(fieldName).getLeft();
262 * This method fetches the number of bits for header field specified by
263 * 'fieldname'. The numBits are present in the hdrFieldCoordMap of the
264 * respective packet class
266 * @return Integer - number of bits of the requested field
268 public int getfieldnumBits(final String fieldName) {
269 return hdrFieldCoordMap.get(fieldName).getRight();
273 public String toString() {
274 StringBuilder ret = new StringBuilder();
275 ret.append(this.getClass().getSimpleName());
277 for (String field : hdrFieldCoordMap.keySet()) {
278 byte[] value = hdrFieldsMap.get(field);
281 ret.append(HexEncode.bytesToHexString(value));
284 ret.replace(ret.length() - 2, ret.length() - 1, "]");
285 return ret.toString();
289 * Returns the raw payload carried by this packet in case payload was not
290 * parsed. Caller can call this function in case the getPaylod() returns null.
292 * @return The raw payload if not parsable as an array of bytes, null otherwise
294 @SuppressFBWarnings("EI_EXPOSE_REP")
295 public byte[] getRawPayload() {
300 * Set a raw payload in the packet class.
302 * @param bytes The raw payload as byte array
304 public void setRawPayload(final byte[] bytes) {
305 rawPayload = Arrays.copyOf(bytes, bytes.length);
309 * Return whether the deserialized packet is to be considered corrupted.
310 * This is the case when the checksum computed after reconstructing the
311 * packet received from wire is not equal to the checksum read from the
312 * stream. For the Packet class which do not have a checksum field, this
313 * function will always return false.
316 * @return true if the deserialized packet's recomputed checksum is not
317 * equal to the packet carried checksum
319 public boolean isCorrupted() {
324 public int hashCode() {
325 final int prime = 31;
326 int result = super.hashCode();
327 result = prime * result
328 + (hdrFieldsMap == null ? 0 : hdrFieldsMap.hashCode());
333 public boolean equals(final Object obj) {
341 if (getClass() != obj.getClass()) {
344 Packet other = (Packet) obj;
345 if (hdrFieldsMap == other.hdrFieldsMap) {
348 if (hdrFieldsMap == null || other.hdrFieldsMap == null) {
351 for (Entry<String, byte[]> entry : hdrFieldsMap.entrySet()) {
352 String field = entry.getKey();
353 if (!Arrays.equals(entry.getValue(), other.hdrFieldsMap.get(field))) {