blob: 48a912112b5596070180327632a17b50f4e06c55 [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001package org.onlab.packet;
2
3import java.nio.ByteBuffer;
4import java.util.HashMap;
5import java.util.Map;
6
7public class MPLS extends BasePacket {
8 public static final int ADDRESS_LENGTH = 4;
9 public static final byte PROTOCOL_IPV4 = 0x1;
10 public static final byte PROTOCOL_MPLS = 0x6;
11 public static final Map<Byte, Class<? extends IPacket>> PROTOCOL_CLASS_MAP;
12
13 static {
14 PROTOCOL_CLASS_MAP = new HashMap<Byte, Class<? extends IPacket>>();
15 PROTOCOL_CLASS_MAP.put(PROTOCOL_IPV4, IPv4.class);
16 PROTOCOL_CLASS_MAP.put(PROTOCOL_MPLS, MPLS.class);
17 }
18
19 protected int label; //20bits
20 protected byte bos; //1bit
21 protected byte ttl; //8bits
22 protected byte protocol;
23
24 /**
25 * Default constructor that sets the version to 4.
26 */
27 public MPLS() {
28 super();
29 this.bos = 1;
30 this.protocol = PROTOCOL_IPV4;
31 }
32
33 @Override
34 public byte[] serialize() {
35 byte[] payloadData = null;
36 if (payload != null) {
37 payload.setParent(this);
38 payloadData = payload.serialize();
39 }
40
41 byte[] data = new byte[(4 + ((payloadData != null) ? payloadData.length : 0)) ];
42 ByteBuffer bb = ByteBuffer.wrap(data);
43
44 bb.putInt(((this.label & 0x000fffff) << 12) | ((this.bos & 0x1) << 8 | (this.ttl & 0xff)));
45 if (payloadData != null) {
46 bb.put(payloadData);
47 }
48
49 return data;
50 }
51
52 @Override
53 public IPacket deserialize(byte[] data, int offset, int length) {
54 ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
55
56 int mplsheader = bb.getInt();
57 this.label = ((mplsheader & 0xfffff000) >> 12);
58 this.bos = (byte) ((mplsheader & 0x00000100) >> 8);
59 this.bos = (byte) (mplsheader & 0x000000ff);
60 this.protocol = (this.bos == 1) ? PROTOCOL_IPV4 : PROTOCOL_MPLS;
61
62 IPacket payload;
63 if (IPv4.PROTOCOL_CLASS_MAP.containsKey(this.protocol)) {
64 Class<? extends IPacket> clazz = IPv4.PROTOCOL_CLASS_MAP.get(this.protocol);
65 try {
66 payload = clazz.newInstance();
67 } catch (Exception e) {
68 throw new RuntimeException("Error parsing payload for MPLS packet", e);
69 }
70 } else {
71 payload = new Data();
72 }
73 this.payload = payload.deserialize(data, bb.position(), bb.limit() - bb.position());
74 this.payload.setParent(this);
75
76 return this;
77 }
78
79 /**
80 * Returns the MPLS label.
81 *
82 * @return MPLS label
83 */
84 public int getLabel() {
85 return label;
86 }
87
88 /**
89 * Sets the MPLS label.
90 *
91 * @param label
92 */
93 public void setLabel(int label) {
94 this.label = label;
95 }
96
97 /**
98 * Returns the MPLS TTL of the packet.
99 *
100 * @return MPLS TTL of the packet
101 */
102 public byte getTtl() {
103 return ttl;
104 }
105
106 /**
107 * Sets the MPLS TTL of the packet.
108 *
109 * @param ttl MPLS TTL
110 */
111 public void setTtl(byte ttl) {
112 this.ttl = ttl;
113 }
114
115}