2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.nettyutil.handler;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.Lists;
14 import io.netty.buffer.ByteBuf;
15 import io.netty.buffer.ByteBufUtil;
16 import io.netty.channel.ChannelHandlerContext;
17 import io.netty.handler.codec.ByteToMessageDecoder;
18 import java.io.ByteArrayInputStream;
19 import java.io.IOException;
20 import java.nio.ByteBuffer;
21 import java.nio.charset.StandardCharsets;
22 import java.util.Arrays;
23 import java.util.List;
24 import org.opendaylight.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.netconf.api.NetconfMessage;
26 import org.opendaylight.netconf.api.messages.NetconfHelloMessage;
27 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
28 import org.opendaylight.netconf.api.xml.XmlUtil;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.w3c.dom.Document;
32 import org.xml.sax.SAXException;
35 * Customized NetconfXMLToMessageDecoder that reads additional header with
36 * session metadata from
37 * {@link NetconfHelloMessage}*
38 * This handler should be replaced in pipeline by regular message handler as last step of negotiation.
39 * It serves as a message barrier and halts all non-hello netconf messages.
40 * Netconf messages after hello should be processed once the negotiation succeeded.
43 public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder {
44 private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToHelloMessageDecoder.class);
46 private static final List<byte[]> POSSIBLE_ENDS = ImmutableList.of(
47 new byte[] { ']', '\n' },
48 new byte[] { ']', '\r', '\n' });
49 private static final List<byte[]> POSSIBLE_STARTS = ImmutableList.of(
51 new byte[] { '\r', '\n', '[' },
52 new byte[] { '\n', '[' });
54 // State variables do not have to by synchronized
55 // Netty uses always the same (1) thread per pipeline
56 // We use instance of this per pipeline
57 private final List<NetconfMessage> nonHelloMessages = Lists.newArrayList();
58 private boolean helloReceived = false;
62 public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
63 throws IOException, SAXException, NetconfDocumentedException {
64 if (in.readableBytes() == 0) {
65 LOG.debug("No more content in incoming buffer.");
71 if (LOG.isTraceEnabled()) {
72 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
75 byte[] bytes = new byte[in.readableBytes()];
80 // Extract bytes containing header with additional metadata
81 String additionalHeader = null;
82 if (startsWithAdditionalHeader(bytes)) {
83 // Auth information containing username, ip address... extracted for monitoring
84 int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
85 if (endOfAuthHeader > -1) {
86 byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader);
87 additionalHeader = additionalHeaderToString(additionalHeaderBytes);
88 bytes = Arrays.copyOfRange(bytes, endOfAuthHeader, bytes.length);
92 Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));
94 final NetconfMessage message = getNetconfMessage(additionalHeader, doc);
95 if (message instanceof NetconfHelloMessage) {
96 Preconditions.checkState(!helloReceived,
97 "Multiple hello messages received, unexpected hello: %s", message);
100 // Non hello message, suspend the message and insert into cache
102 Preconditions.checkState(helloReceived, "Hello message not received, instead received: %s", message);
103 LOG.debug("Netconf message received during negotiation, caching {}", message);
104 nonHelloMessages.add(message);
107 in.discardReadBytes();
111 private static NetconfMessage getNetconfMessage(final String additionalHeader, final Document doc)
112 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));
118 return new NetconfHelloMessage(doc);
125 private static int getAdditionalHeaderEndIndex(final byte[] bytes) {
126 for (byte[] possibleEnd : POSSIBLE_ENDS) {
127 int idx = findByteSequence(bytes, possibleEnd);
130 return idx + possibleEnd.length;
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.");
141 if (bytes.length == sequence.length) {
142 if (Arrays.equals(bytes, sequence)) {
149 for (int i = 0; i < bytes.length; i++) {
150 if (bytes[i] == sequence[index]) {
152 if (index == sequence.length) {
153 return i - index + 1;
162 private static void logMessage(final byte[] bytes) {
163 if (LOG.isDebugEnabled()) {
164 String string = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
165 LOG.debug("Parsing message \n{}", string);
169 private static boolean startsWithAdditionalHeader(final byte[] bytes) {
170 for (byte[] possibleStart : POSSIBLE_STARTS) {
172 for (byte b : possibleStart) {
173 if (bytes[index++] != b) {
177 if (index == possibleStart.length) {
186 private static String additionalHeaderToString(final byte[] bytes) {
187 return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
191 * Get netconf messages received during negotiation.
193 * @return Collection of NetconfMessages that were not hello, but were received during negotiation.
195 public Iterable<NetconfMessage> getPostHelloNetconfMessages() {
196 return nonHelloMessages;