Merge "Remove duplicate dependency declaration"
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / netconf / nettyutil / handler / NetconfXMLToHelloMessageDecoder.java
1 /*
2  * Copyright (c) 2014 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.controller.netconf.nettyutil.handler;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Charsets;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.Lists;
15 import io.netty.buffer.ByteBuf;
16 import io.netty.buffer.ByteBufUtil;
17 import io.netty.channel.ChannelHandlerContext;
18 import io.netty.handler.codec.ByteToMessageDecoder;
19 import java.io.ByteArrayInputStream;
20 import java.io.IOException;
21 import java.nio.ByteBuffer;
22 import java.util.Arrays;
23 import java.util.List;
24 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.controller.netconf.api.NetconfMessage;
26 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
27 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
28 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.w3c.dom.Document;
32 import org.xml.sax.SAXException;
33
34 /**
35  * Customized NetconfXMLToMessageDecoder that reads additional header with
36  * session metadata from
37  * {@link org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage}
38  *
39  *
40  * This handler should be replaced in pipeline by regular message handler as last step of negotiation.
41  * It serves as a message barrier and halts all non-hello netconf messages.
42  * Netconf messages after hello should be processed once the negotiation succeeded.
43  *
44  */
45 public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder {
46     private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToHelloMessageDecoder.class);
47
48     private static final List<byte[]> POSSIBLE_ENDS = ImmutableList.of(
49             new byte[] { ']', '\n' },
50             new byte[] { ']', '\r', '\n' });
51     private static final List<byte[]> POSSIBLE_STARTS = ImmutableList.of(
52             new byte[] { '[' },
53             new byte[] { '\r', '\n', '[' },
54             new byte[] { '\n', '[' });
55
56     // State variables do not have to by synchronized
57     // Netty uses always the same (1) thread per pipeline
58     // We use instance of this per pipeline
59     private final List<NetconfMessage> nonHelloMessages = Lists.newArrayList();
60     private boolean helloReceived = false;
61
62     @Override
63     @VisibleForTesting
64     public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws IOException, SAXException, NetconfDocumentedException {
65         if (in.readableBytes() == 0) {
66             LOG.debug("No more content in incoming buffer.");
67             return;
68         }
69
70         in.markReaderIndex();
71         try {
72             if (LOG.isTraceEnabled()) {
73                 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
74             }
75
76             byte[] bytes = new byte[in.readableBytes()];
77             in.readBytes(bytes);
78
79             logMessage(bytes);
80
81             // Extract bytes containing header with additional metadata
82             String additionalHeader = null;
83             if (startsWithAdditionalHeader(bytes)) {
84                 // Auth information containing username, ip address... extracted for monitoring
85                 int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
86                 if (endOfAuthHeader > -1) {
87                     byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2);
88                     additionalHeader = additionalHeaderToString(additionalHeaderBytes);
89                     bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length);
90                 }
91             }
92
93             Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));
94
95             final NetconfMessage message = getNetconfMessage(additionalHeader, doc);
96             if (message instanceof NetconfHelloMessage) {
97                 Preconditions.checkState(helloReceived == false,
98                         "Multiple hello messages received, unexpected hello: %s", message);
99                 out.add(message);
100                 helloReceived = true;
101             // Non hello message, suspend the message and insert into cache
102             } else {
103                 Preconditions.checkState(helloReceived, "Hello message not received, instead received: %s", message);
104                 LOG.debug("Netconf message received during negotiation, caching {}", message);
105                 nonHelloMessages.add(message);
106             }
107         } finally {
108             in.discardReadBytes();
109         }
110     }
111
112     private NetconfMessage getNetconfMessage(final String additionalHeader, final Document doc) throws NetconfDocumentedException {
113         NetconfMessage msg = new NetconfMessage(doc);
114         if(NetconfHelloMessage.isHelloMessage(msg)) {
115             if (additionalHeader != null) {
116                 return new NetconfHelloMessage(doc, NetconfHelloMessageAdditionalHeader.fromString(additionalHeader));
117             } else {
118                 return new NetconfHelloMessage(doc);
119             }
120         }
121
122         return msg;
123     }
124
125     private int getAdditionalHeaderEndIndex(final byte[] bytes) {
126         for (byte[] possibleEnd : POSSIBLE_ENDS) {
127             int idx = findByteSequence(bytes, possibleEnd);
128
129             if (idx != -1) {
130                 return idx;
131             }
132         }
133
134         return -1;
135     }
136
137     private static int findByteSequence(final byte[] bytes, final byte[] sequence) {
138         if (bytes.length < sequence.length) {
139             throw new IllegalArgumentException("Sequence to be found is longer than the given byte array.");
140         }
141         if (bytes.length == sequence.length) {
142             if (Arrays.equals(bytes, sequence)) {
143                 return 0;
144             } else {
145                 return -1;
146             }
147         }
148         int j = 0;
149         for (int i = 0; i < bytes.length; i++) {
150             if (bytes[i] == sequence[j]) {
151                 j++;
152                 if (j == sequence.length) {
153                     return i - j + 1;
154                 }
155             } else {
156                 j = 0;
157             }
158         }
159         return -1;
160     }
161
162
163     private void logMessage(final byte[] bytes) {
164         String s = Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
165         LOG.debug("Parsing message \n{}", s);
166     }
167
168     private boolean startsWithAdditionalHeader(final byte[] bytes) {
169         for (byte[] possibleStart : POSSIBLE_STARTS) {
170             int i = 0;
171             for (byte b : possibleStart) {
172                 if(bytes[i++] != b) {
173                     break;
174                 }
175
176                 if(i == possibleStart.length) {
177                     return true;
178                 }
179             }
180         }
181
182         return false;
183     }
184
185     private String additionalHeaderToString(final byte[] bytes) {
186         return Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
187     }
188
189     /**
190      * @return Collection of NetconfMessages that were not hello, but were received during negotiation
191      */
192     public Iterable<NetconfMessage> getPostHelloNetconfMessages() {
193         return nonHelloMessages;
194     }
195 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.