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.controller.netconf.nettyutil.handler;
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;
35 * Customized NetconfXMLToMessageDecoder that reads additional header with
36 * session metadata from
37 * {@link org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage}
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.
45 public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder {
46 private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToHelloMessageDecoder.class);
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(
53 new byte[] { '\r', '\n', '[' },
54 new byte[] { '\n', '[' });
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 List<NetconfMessage> nonHelloMessages = Lists.newArrayList();
60 private boolean helloReceived = false;
64 public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws IOException, SAXException, NetconfDocumentedException {
65 if (in.readableBytes() == 0) {
66 LOG.debug("No more content in incoming buffer.");
72 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
73 byte[] bytes = new byte[in.readableBytes()];
78 // Extract bytes containing header with additional metadata
79 String additionalHeader = null;
80 if (startsWithAdditionalHeader(bytes)) {
81 // Auth information containing username, ip address... extracted for monitoring
82 int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
83 if (endOfAuthHeader > -1) {
84 byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2);
85 additionalHeader = additionalHeaderToString(additionalHeaderBytes);
86 bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length);
90 Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));
92 final NetconfMessage message = getNetconfMessage(additionalHeader, doc);
93 if (message instanceof NetconfHelloMessage) {
94 Preconditions.checkState(helloReceived == false,
95 "Multiple hello messages received, unexpected hello: %s",
96 XmlUtil.toString(message.getDocument()));
99 // Non hello message, suspend the message and insert into cache
101 Preconditions.checkState(helloReceived, "Hello message not received, instead received: %s",
102 XmlUtil.toString(message.getDocument()));
103 LOG.debug("Netconf message received during negotiation, caching {}",
104 XmlUtil.toString(message.getDocument()));
105 nonHelloMessages.add(message);
108 in.discardReadBytes();
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));
118 return new NetconfHelloMessage(doc);
125 private int getAdditionalHeaderEndIndex(byte[] bytes) {
126 for (byte[] possibleEnd : POSSIBLE_ENDS) {
127 int idx = findByteSequence(bytes, possibleEnd);
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[j]) {
152 if (j == sequence.length) {
163 private void logMessage(byte[] bytes) {
164 String s = Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
165 LOG.debug("Parsing message \n{}", s);
168 private boolean startsWithAdditionalHeader(byte[] bytes) {
169 for (byte[] possibleStart : POSSIBLE_STARTS) {
171 for (byte b : possibleStart) {
172 if(bytes[i++] != b) {
176 if(i == possibleStart.length) {
185 private String additionalHeaderToString(byte[] bytes) {
186 return Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
190 * @return Collection of NetconfMessages that were not hello, but were received during negotiation
192 public Iterable<NetconfMessage> getPostHelloNetconfMessages() {
193 return nonHelloMessages;