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