Bump upstreams
[openflowplugin.git] / libraries / liblldp / src / main / java / org / opendaylight / openflowplugin / libraries / liblldp / Packet.java
1 /*
2  * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.openflowplugin.libraries.liblldp;
9
10 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
11 import java.util.Arrays;
12 import java.util.Map;
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;
18
19 /**
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
22  * deserialize.
23  */
24 public abstract class Packet {
25     private static final Logger LOG = LoggerFactory.getLogger(Packet.class);
26
27     // Access level granted to this packet
28     protected final boolean writeAccess;
29
30     // When deserialized from wire, packet could result corrupted
31     protected boolean corrupted;
32
33     // The packet that encapsulate this packet
34     protected Packet parent;
35
36     // The packet encapsulated by this packet
37     protected Packet payload;
38
39     // The unparsed raw payload carried by this packet
40     protected byte[] rawPayload;
41
42     // Bit coordinates of packet header fields
43     protected Map<String, Pair<Integer, Integer>> hdrFieldCoordMap;
44
45     // Header fields values: Map<FieldName,Value>
46     protected Map<String, byte[]> hdrFieldsMap;
47
48     // The class of the encapsulated packet object
49     protected Supplier<Packet> payloadFactory;
50
51     public Packet() {
52         writeAccess = false;
53         corrupted = false;
54     }
55
56     public Packet(final boolean writeAccess) {
57         this.writeAccess = writeAccess;
58         corrupted = false;
59     }
60
61     public Packet getParent() {
62         return parent;
63     }
64
65     public Packet getPayload() {
66         return payload;
67     }
68
69     public void setParent(final Packet parent) {
70         this.parent = parent;
71     }
72
73     public void setPayload(final Packet payload) {
74         this.payload = payload;
75     }
76
77     public void setHeaderField(final String headerField, final byte[] readValue) {
78         hdrFieldsMap.put(headerField, readValue);
79     }
80
81     /**
82      * This method deserializes the data bits obtained from the wire into the
83      * respective header and payload which are of type Packet.
84      *
85      * @param data - data from wire to deserialize
86      * @param bitOffset bit position where packet header starts in data
87      *        array
88      * @param size size of packet in bits
89      * @return Packet
90      * @throws PacketException if deserialization fails
91      */
92     public Packet deserialize(final byte[] data, final int bitOffset, final int size)
93             throws PacketException {
94
95         // Deserialize the header fields one by one
96         int startOffset = 0;
97         int numBits = 0;
98         for (Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
99                 .entrySet()) {
100             String hdrField = pairs.getKey();
101             startOffset = bitOffset + getfieldOffset(hdrField);
102             numBits = getfieldnumBits(hdrField);
103
104             byte[] hdrFieldBytes;
105             try {
106                 hdrFieldBytes = BitBufferHelper.getBits(data, startOffset,
107                         numBits);
108             } catch (final BufferException e) {
109                 throw new PacketException("getBits failed", e);
110             }
111
112             /*
113              * Store the raw read value, checks the payload type and set the
114              * payloadClass accordingly
115              */
116             setHeaderField(hdrField, hdrFieldBytes);
117
118             if (LOG.isTraceEnabled()) {
119                 LOG.trace("{}: {}: {} (offset {} bitsize {})", this.getClass().getSimpleName(), hdrField,
120                         HexEncode.bytesToHexString(hdrFieldBytes), startOffset, numBits);
121             }
122         }
123
124         // Deserialize the payload now
125         int payloadStart = startOffset + numBits;
126         int payloadSize = data.length * NetUtils.NUM_BITS_IN_A_BYTE - payloadStart;
127
128         if (payloadFactory != null) {
129             payload = payloadFactory.get();
130             payload.deserialize(data, payloadStart, payloadSize);
131             payload.setParent(this);
132         } else {
133             /*
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.
136              */
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);
140         }
141
142         // Take care of computation that can be done only after deserialization
143         postDeserializeCustomOperation(data, payloadStart - getHeaderSize());
144
145         return this;
146     }
147
148     /**
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.
151      *
152      * @return The byte array representing the serialized Packet
153      * @throws PacketException if serialization fails
154      */
155     public byte[] serialize() throws PacketException {
156
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;
163         }
164         int payloadSize = payloadBytes == null ? 0 : payloadBytes.length;
165
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);
171         }
172
173         // Serialize this packet header, field by field
174         for (Map.Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
175                 .entrySet()) {
176             String field = pairs.getKey();
177             byte[] fieldBytes = hdrFieldsMap.get(field);
178             // Let's skip optional fields when not set
179             if (fieldBytes != null) {
180                 try {
181                     BitBufferHelper.copyBitsFromLsb(packetBytes, fieldBytes,
182                             getfieldOffset(field), getfieldnumBits(field));
183                 } catch (final BufferException e) {
184                     throw new PacketException("setBytes failed", e);
185                 }
186             }
187         }
188
189         // Perform post serialize operations (like checksum computation)
190         postSerializeCustomOperation(packetBytes);
191
192         if (LOG.isTraceEnabled()) {
193             LOG.trace("packet {}: {}", this.getClass().getSimpleName(),
194                     HexEncode.bytesToHexString(packetBytes));
195         }
196
197         return packetBytes;
198     }
199
200     /**
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
205      * for IPv4
206      *
207      * @param myBytes serialized bytes
208      * @throws PacketException on failure
209      */
210     protected void postSerializeCustomOperation(final byte[] myBytes) throws PacketException {
211         // no op
212     }
213
214     /**
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.
220      *
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
224      */
225     protected void postDeserializeCustomOperation(final byte[] data, final int startBitOffset) throws PacketException {
226         // no op
227     }
228
229     /**
230      * Gets the header length in bits.
231      *
232      * @return int the header length in bits
233      */
234     public int getHeaderSize() {
235         int size = 0;
236         /*
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
240          */
241         for (Map.Entry<String, byte[]> fieldEntry : hdrFieldsMap.entrySet()) {
242             if (fieldEntry.getValue() != null) {
243                 String field = fieldEntry.getKey();
244                 size += getfieldnumBits(field);
245             }
246         }
247         return size;
248     }
249
250     /**
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
254      *
255      * @return Integer - startOffset of the requested field
256      */
257     public int getfieldOffset(final String fieldName) {
258         return hdrFieldCoordMap.get(fieldName).getLeft();
259     }
260
261     /**
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
265      *
266      * @return Integer - number of bits of the requested field
267      */
268     public int getfieldnumBits(final String fieldName) {
269         return hdrFieldCoordMap.get(fieldName).getRight();
270     }
271
272     @Override
273     public String toString() {
274         StringBuilder ret = new StringBuilder();
275         ret.append(this.getClass().getSimpleName());
276         ret.append(": [");
277         for (String field : hdrFieldCoordMap.keySet()) {
278             byte[] value = hdrFieldsMap.get(field);
279             ret.append(field);
280             ret.append(": ");
281             ret.append(HexEncode.bytesToHexString(value));
282             ret.append(", ");
283         }
284         ret.replace(ret.length() - 2, ret.length() - 1, "]");
285         return ret.toString();
286     }
287
288     /**
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.
291      *
292      * @return The raw payload if not parsable as an array of bytes, null otherwise
293      */
294     @SuppressFBWarnings("EI_EXPOSE_REP")
295     public byte[] getRawPayload() {
296         return rawPayload;
297     }
298
299     /**
300      * Set a raw payload in the packet class.
301      *
302      * @param bytes The raw payload as byte array
303      */
304     public void setRawPayload(final byte[] bytes) {
305         rawPayload = Arrays.copyOf(bytes, bytes.length);
306     }
307
308     /**
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.
314      *
315      *
316      * @return true if the deserialized packet's recomputed checksum is not
317      *         equal to the packet carried checksum
318      */
319     public boolean isCorrupted() {
320         return corrupted;
321     }
322
323     @Override
324     public int hashCode() {
325         final int prime = 31;
326         int result = super.hashCode();
327         result = prime * result
328                 + (hdrFieldsMap == null ? 0 : hdrFieldsMap.hashCode());
329         return result;
330     }
331
332     @Override
333     public boolean equals(final Object obj) {
334         if (obj == null) {
335             return false;
336         }
337
338         if (this == obj) {
339             return true;
340         }
341         if (getClass() != obj.getClass()) {
342             return false;
343         }
344         Packet other = (Packet) obj;
345         if (hdrFieldsMap == other.hdrFieldsMap) {
346             return true;
347         }
348         if (hdrFieldsMap == null || other.hdrFieldsMap == null) {
349             return false;
350         }
351         for (Entry<String, byte[]> entry : hdrFieldsMap.entrySet()) {
352             String field = entry.getKey();
353             if (!Arrays.equals(entry.getValue(), other.hdrFieldsMap.get(field))) {
354                 return false;
355             }
356         }
357         return true;
358     }
359 }