Logging enhancement related to Packet
[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.net.InetAddress;
12 import java.net.UnknownHostException;
13 import java.util.Map;
14 import java.util.Map.Entry;
15
16 import org.apache.commons.lang3.tuple.Pair;
17 import org.opendaylight.controller.sal.utils.HexEncode;
18 import org.opendaylight.controller.sal.utils.NetUtils;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 /**
23  * Abstract class which represents the generic network packet object It provides
24  * the basic methods which are common for all the packets, like serialize and
25  * deserialize
26  * 
27  * 
28  */
29
30 public abstract class Packet {
31     protected static final Logger logger = LoggerFactory
32             .getLogger(Packet.class);
33     // Access level granted to this packet
34     protected boolean writeAccess;
35     // When deserialized from wire, packet could result corrupted
36     protected boolean corrupted;
37     // The packet that encapsulate this packet
38     protected Packet parent;
39     // The packet encapsulated by this packet
40     protected Packet payload;
41     // Bit coordinates of packet header fields
42     protected Map<String, Pair<Integer, Integer>> hdrFieldCoordMap;
43     // Header fields values: Map<FieldName,Value>
44     protected Map<String, byte[]> hdrFieldsMap;
45     // The class of the encapsulated packet object
46     protected Class<? extends Packet> payloadClass;
47
48     public Packet() {
49         writeAccess = false;
50         corrupted = false;
51     }
52
53     public Packet(boolean writeAccess) {
54         this.writeAccess = writeAccess;
55         this.corrupted = false;
56     }
57
58     public Packet getParent() {
59         return parent;
60     }
61
62     public Packet getPayload() {
63         return payload;
64     }
65
66     public void setParent(Packet parent) {
67         this.parent = parent;
68     }
69
70     public void setPayload(Packet payload) {
71         this.payload = payload;
72     }
73
74     public void setHeaderField(String headerField, byte[] readValue) {
75         hdrFieldsMap.put(headerField, readValue);
76     }
77
78     /**
79      * This method deserializes the data bits obtained from the wire into the
80      * respective header and payload which are of type Packet
81      * 
82      * @param byte[] data - data from wire to deserialize
83      * @param int bitOffset bit position where packet header starts in data
84      *        array
85      * @param int size of packet in bits
86      * @return Packet
87      * @throws PacketException
88      */
89
90     public Packet deserialize(byte[] data, int bitOffset, int size)
91             throws PacketException {
92         String hdrField;
93         Integer startOffset = 0, numBits = 0;
94         byte[] hdrFieldBytes;
95
96         for (Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
97                 .entrySet()) {
98             hdrField = pairs.getKey();
99             startOffset = bitOffset + this.getfieldOffset(hdrField);
100             numBits = this.getfieldnumBits(hdrField);
101
102             try {
103                 hdrFieldBytes = BitBufferHelper.getBits(data, startOffset,
104                         numBits);
105             } catch (BufferException e) {
106                 throw new PacketException(e.getMessage());
107             }
108             /*
109              * Store the raw read value, checks the payload type and set the
110              * payloadClass accordingly
111              */
112             logger.trace("{}: {}: {} (offset {} bitsize {})",
113                     new Object[] { this.getClass().getSimpleName(), hdrField,
114                             HexEncode.bytesToHexString(hdrFieldBytes),
115                             startOffset, numBits });
116
117             this.setHeaderField(hdrField, hdrFieldBytes);
118         }
119
120         postDeserializeCustomOperation(data, startOffset);
121
122         int payloadStart = startOffset + numBits;
123         // int payloadSize = size - payloadStart;
124         int payloadSize = data.length * NetUtils.NumBitsInAByte - payloadStart;
125
126         if (payloadClass != null) {
127             try {
128                 payload = payloadClass.newInstance();
129             } catch (Exception e) {
130                 throw new RuntimeException(
131                         "Error parsing payload for Ethernet packet", e);
132             }
133             payload.deserialize(data, payloadStart, payloadSize);
134             payload.setParent(this);
135         } else {
136             // For now let's discard unparsable payload
137         }
138         return this;
139     }
140
141     /**
142      * This method serializes the header and payload bytes from the respective
143      * packet class, into a single stream of bytes to be sent on the wire
144      * 
145      * @return byte[] - serialized bytes
146      * @throws PacketException
147      */
148
149     public byte[] serialize() throws PacketException {
150         byte[] payloadBytes = null;
151         int payloadSize = 0;
152         int headerSize = this.getHeaderSize();
153         int payloadByteOffset = headerSize / NetUtils.NumBitsInAByte;
154         int size = 0;
155
156         if (payload != null) {
157             payloadBytes = payload.serialize();
158             payloadSize = payloadBytes.length * NetUtils.NumBitsInAByte;
159         }
160
161         size = headerSize + payloadSize;
162         int length = size / NetUtils.NumBitsInAByte;
163         byte headerBytes[] = new byte[length];
164
165         if (payload != null) {
166             System.arraycopy(payloadBytes, 0, headerBytes, payloadByteOffset,
167                     payloadBytes.length);
168         }
169
170         String field;
171         byte[] fieldBytes;
172         Integer startOffset, numBits;
173
174         for (Map.Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
175                 .entrySet()) {
176             field = pairs.getKey();
177             fieldBytes = hdrFieldsMap.get(field);
178             // Let's skip optional fields when not set
179             if (fieldBytes != null) {
180                 startOffset = this.getfieldOffset(field);
181                 numBits = this.getfieldnumBits(field);
182                 try {
183                     BitBufferHelper.setBytes(headerBytes, fieldBytes,
184                             startOffset, numBits);
185                 } catch (BufferException e) {
186                     throw new PacketException(e.getMessage());
187                 }
188             }
189         }
190         postSerializeCustomOperation(headerBytes);
191
192         logger.trace("{}: {}", this.getClass().getSimpleName(),
193                 HexEncode.bytesToHexString(headerBytes));
194         return headerBytes;
195     }
196
197     /**
198      * This method gets called at the end of the serialization process It is
199      * intended for the child packets to insert some custom data into the output
200      * byte stream which cannot be done or cannot be done efficiently during the
201      * normal Packet.serialize() path. An example is the checksum computation
202      * for IPv4
203      * 
204      * @param byte[] - serialized bytes
205      * @throws PacketException
206      */
207     protected void postSerializeCustomOperation(byte[] myBytes)
208             throws PacketException {
209         // no op
210     }
211
212     /**
213      * This method re-computes the checksum of the bits received on the wire and
214      * validates it with the checksum in the bits received Since the computation
215      * of checksum varies based on the protocol, this method is overridden
216      * Currently only IPv4 does checksum computation and validation TCP and UDP
217      * need to implement these if required
218      * 
219      * @param byte[] data
220      * @param int endBitOffset
221      * @throws PacketException
222      */
223     protected void postDeserializeCustomOperation(byte[] data, int endBitOffset)
224             throws PacketException {
225         // no op
226     }
227
228     /**
229      * Gets the header length in bits
230      * 
231      * @return int the header length in bits
232      */
233     public int getHeaderSize() {
234         int size = 0;
235         /*
236          * We need to iterate over the fields that were read in the frame
237          * (hdrFieldsMap) not all the possible ones described in
238          * hdrFieldCoordMap. For ex, 802.1Q may or may not be there
239          */
240         for (Map.Entry<String, byte[]> fieldEntry : hdrFieldsMap.entrySet()) {
241             if (fieldEntry.getValue() != null) {
242                 String field = fieldEntry.getKey();
243                 size += getfieldnumBits(field);
244             }
245         }
246         return size;
247     }
248
249     /**
250      * This method fetches the start bit offset for header field specified by
251      * 'fieldname'. The offset is present in the hdrFieldCoordMap of the
252      * respective packet class
253      * 
254      * @param String
255      *            fieldName
256      * @return Integer - startOffset of the requested field
257      */
258     public int getfieldOffset(String fieldName) {
259         return (((Pair<Integer, Integer>) hdrFieldCoordMap.get(fieldName))
260                 .getLeft());
261     }
262
263     /**
264      * This method fetches the number of bits for header field specified by
265      * 'fieldname'. The numBits are present in the hdrFieldCoordMap of the
266      * respective packet class
267      * 
268      * @param String
269      *            fieldName
270      * @return Integer - number of bits of the requested field
271      */
272     public int getfieldnumBits(String fieldName) {
273         return (((Pair<Integer, Integer>) hdrFieldCoordMap.get(fieldName))
274                 .getRight());
275     }
276
277     @Override
278     public String toString() {
279         StringBuffer ret = new StringBuffer();
280         for (Map.Entry<String, byte[]> entry : hdrFieldsMap.entrySet()) {
281             ret.append(entry.getKey() + ": ");
282             if (entry.getValue().length == 6) {
283                 ret.append(HexEncode.bytesToHexString(entry.getValue()) + " ");
284             } else if (entry.getValue().length == 4) {
285                 try {
286                     ret.append(InetAddress.getByAddress(entry.getValue())
287                             .getHostAddress() + " ");
288                 } catch (UnknownHostException e) {
289                     logger.error("", e);
290                 }
291             } else {
292                 ret.append(((Long) BitBufferHelper.getLong(entry.getValue()))
293                         .toString() + " ");
294             }
295         }
296         return ret.toString();
297     }
298
299     /**
300      * Returns true if the packet is corrupted
301      * 
302      * @return boolean
303      */
304     protected boolean isPacketCorrupted() {
305         return corrupted;
306     }
307 }