59a786339d4e18d524deb4eb3a94e3f43aac843e
[controller.git] / opendaylight / commons / liblldp / src / main / java / org / opendaylight / controller / 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
9 package org.opendaylight.controller.liblldp;
10
11 import java.util.Arrays;
12 import java.util.Map;
13 import java.util.Map.Entry;
14
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
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;
44
45     public Packet() {
46         writeAccess = false;
47         corrupted = false;
48     }
49
50     public Packet(boolean writeAccess) {
51         this.writeAccess = writeAccess;
52         corrupted = false;
53     }
54
55     public Packet getParent() {
56         return parent;
57     }
58
59     public Packet getPayload() {
60         return payload;
61     }
62
63     public void setParent(Packet parent) {
64         this.parent = parent;
65     }
66
67     public void setPayload(Packet payload) {
68         this.payload = payload;
69     }
70
71     public void setHeaderField(String headerField, byte[] readValue) {
72         hdrFieldsMap.put(headerField, readValue);
73     }
74
75     /**
76      * This method deserializes the data bits obtained from the wire into the
77      * respective header and payload which are of type Packet
78      *
79      * @param byte[] data - data from wire to deserialize
80      * @param int bitOffset bit position where packet header starts in data
81      *        array
82      * @param int size of packet in bits
83      * @return Packet
84      * @throws PacketException
85      */
86     public Packet deserialize(byte[] data, int bitOffset, int size)
87             throws PacketException {
88
89         // Deserialize the header fields one by one
90         int startOffset = 0, numBits = 0;
91         for (Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
92                 .entrySet()) {
93             String hdrField = pairs.getKey();
94             startOffset = bitOffset + this.getfieldOffset(hdrField);
95             numBits = this.getfieldnumBits(hdrField);
96
97             byte[] hdrFieldBytes = null;
98             try {
99                 hdrFieldBytes = BitBufferHelper.getBits(data, startOffset,
100                         numBits);
101             } catch (BufferException e) {
102                 throw new PacketException(e.getMessage());
103             }
104
105             /*
106              * Store the raw read value, checks the payload type and set the
107              * payloadClass accordingly
108              */
109             this.setHeaderField(hdrField, hdrFieldBytes);
110
111             if (logger.isTraceEnabled()) {
112                 logger.trace("{}: {}: {} (offset {} bitsize {})",
113                         new Object[] { this.getClass().getSimpleName(), hdrField,
114                         HexEncode.bytesToHexString(hdrFieldBytes),
115                         startOffset, numBits });
116             }
117         }
118
119         // Deserialize the payload now
120         int payloadStart = startOffset + numBits;
121         int payloadSize = data.length * NetUtils.NumBitsInAByte - payloadStart;
122
123         if (payloadClass != null) {
124             try {
125                 payload = payloadClass.newInstance();
126             } catch (Exception e) {
127                 throw new RuntimeException(
128                         "Error parsing payload for Ethernet packet", e);
129             }
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.NumBitsInAByte;
138             int stop = start + payloadSize / NetUtils.NumBitsInAByte;
139             rawPayload = Arrays.copyOfRange(data, start, stop);
140         }
141
142
143         // Take care of computation that can be done only after deserialization
144         postDeserializeCustomOperation(data, payloadStart - getHeaderSize());
145
146         return this;
147     }
148
149     /**
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
152      *
153      * @return The byte array representing the serialized Packet
154      * @throws PacketException
155      */
156     public byte[] serialize() throws PacketException {
157
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;
164         }
165         int payloadSize = (payloadBytes == null) ? 0 : payloadBytes.length;
166
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);
172         }
173
174         // Serialize this packet header, field by field
175         for (Map.Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
176                 .entrySet()) {
177             String field = pairs.getKey();
178             byte[] fieldBytes = hdrFieldsMap.get(field);
179             // Let's skip optional fields when not set
180             if (fieldBytes != null) {
181                 try {
182                     BitBufferHelper.setBytes(packetBytes, fieldBytes,
183                             getfieldOffset(field), getfieldnumBits(field));
184                 } catch (BufferException e) {
185                     throw new PacketException(e.getMessage());
186                 }
187             }
188         }
189
190         // Perform post serialize operations (like checksum computation)
191         postSerializeCustomOperation(packetBytes);
192
193         if (logger.isTraceEnabled()) {
194             logger.trace("{}: {}", this.getClass().getSimpleName(),
195                     HexEncode.bytesToHexString(packetBytes));
196         }
197
198         return packetBytes;
199     }
200
201     /**
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
206      * for IPv4
207      *
208      * @param byte[] - serialized bytes
209      * @throws PacketException
210      */
211     protected void postSerializeCustomOperation(byte[] myBytes)
212             throws PacketException {
213         // no op
214     }
215
216     /**
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.
222      *
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
226      */
227     protected void postDeserializeCustomOperation(byte[] data, int startBitOffset)
228             throws PacketException {
229         // no op
230     }
231
232     /**
233      * Gets the header length in bits
234      *
235      * @return int the header length in bits
236      */
237     public int getHeaderSize() {
238         int size = 0;
239         /*
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
243          */
244         for (Map.Entry<String, byte[]> fieldEntry : hdrFieldsMap.entrySet()) {
245             if (fieldEntry.getValue() != null) {
246                 String field = fieldEntry.getKey();
247                 size += getfieldnumBits(field);
248             }
249         }
250         return size;
251     }
252
253     /**
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
257      *
258      * @param String
259      *            fieldName
260      * @return Integer - startOffset of the requested field
261      */
262     public int getfieldOffset(String fieldName) {
263         return hdrFieldCoordMap.get(fieldName).getLeft();
264     }
265
266     /**
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
270      *
271      * @param String
272      *            fieldName
273      * @return Integer - number of bits of the requested field
274      */
275     public int getfieldnumBits(String fieldName) {
276         return hdrFieldCoordMap.get(fieldName).getRight();
277     }
278
279     @Override
280     public String toString() {
281         StringBuilder ret = new StringBuilder();
282         ret.append(this.getClass().getSimpleName());
283         ret.append(": [");
284         for (String field : hdrFieldCoordMap.keySet()) {
285             byte[] value = hdrFieldsMap.get(field);
286             ret.append(field);
287             ret.append(": ");
288             ret.append(HexEncode.bytesToHexString(value));
289             ret.append(", ");
290         }
291         ret.replace(ret.length()-2, ret.length()-1, "]");
292         return ret.toString();
293     }
294
295     /**
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.
298      *
299      * @return The raw payload if not parsable as an array of bytes, null otherwise
300      */
301     public byte[] getRawPayload() {
302         return rawPayload;
303     }
304
305     /**
306      * Set a raw payload in the packet class
307      *
308      * @param payload The raw payload as byte array
309      */
310     public void setRawPayload(byte[] payload) {
311         this.rawPayload = Arrays.copyOf(payload, payload.length);
312     }
313
314     /**
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.
320      *
321      *
322      * @return true if the deserialized packet's recomputed checksum is not
323      *         equal to the packet carried checksum
324      */
325     public boolean isCorrupted() {
326         return corrupted;
327     }
328
329     @Override
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());
335         return result;
336     }
337
338     @Override
339     public boolean equals(Object obj) {
340         if (this == obj) {
341             return true;
342         }
343         if (getClass() != obj.getClass()) {
344             return false;
345         }
346         Packet other = (Packet) obj;
347         if (hdrFieldsMap == other.hdrFieldsMap) {
348             return true;
349         }
350         if (hdrFieldsMap == null || other.hdrFieldsMap == null) {
351             return false;
352         }
353         if (hdrFieldsMap != null && other.hdrFieldsMap != null) {
354             for (String field : hdrFieldsMap.keySet()) {
355                 if (!Arrays.equals(hdrFieldsMap.get(field), other.hdrFieldsMap.get(field))) {
356                     return false;
357                 }
358             }
359         } else {
360             return false;
361         }
362         return true;
363     }
364 }