Update buffer readerIndex after XML parsing error
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / NetconfXMLToMessageDecoder.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.netconf.nettyutil.handler;
9
10 import io.netty.buffer.ByteBuf;
11 import io.netty.buffer.ByteBufInputStream;
12 import io.netty.buffer.ByteBufUtil;
13 import io.netty.buffer.Unpooled;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.handler.codec.ByteToMessageDecoder;
16 import java.io.IOException;
17 import java.util.List;
18 import org.opendaylight.netconf.api.messages.NetconfMessage;
19 import org.opendaylight.netconf.api.xml.XmlUtil;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.xml.sax.SAXException;
23 import org.xml.sax.SAXParseException;
24
25 public final class NetconfXMLToMessageDecoder extends ByteToMessageDecoder {
26     private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToMessageDecoder.class);
27
28     @Override
29     public void decode(final ChannelHandlerContext ctx, final ByteBuf in,
30                        final List<Object> out) throws IOException, SAXException {
31         if (in.isReadable()) {
32             if (LOG.isTraceEnabled()) {
33                 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
34             }
35
36             /* According to the XML 1.0 specifications, when there is an XML declaration
37              * at the beginning of an XML document, it is invalid to have
38              * white spaces before that declaration (reminder: a XML declaration looks like:
39              * <?xml version="1.0" encoding="UTF-8"?>). In contrast, when there is no XML declaration,
40              * it is valid to have white spaces at the beginning of the document.
41              *
42              * When they send a NETCONF message, several NETCONF servers start with a new line (either
43              * LF or CRLF), presumably to improve readability in interactive sessions with a human being.
44              * Some NETCONF servers send an XML declaration, some others do not.
45              *
46              * If a server starts a NETCONF message with white spaces and follows with an XML
47              * declaration, XmlUtil.readXmlToDocument() will fail because this is invalid XML.
48              * But in the spirit of the "NETCONF over SSH" RFC 4742 and to improve interoperability, we want
49              * to accept those messages.
50              *
51              * To do this, the following code strips the leading bytes before the start of the XML messages.
52              */
53
54             // Skip all leading whitespaces by moving the reader index to the first non whitespace character
55             while (in.isReadable()) {
56                 if (!isWhitespace(in.readByte())) {
57                     // return reader index to the first non whitespace character
58                     in.readerIndex(in.readerIndex() - 1);
59                     break;
60                 }
61             }
62
63             // Warn about leading whitespaces
64             if (in.readerIndex() != 0 && LOG.isWarnEnabled()) {
65                 final byte[] strippedBytes = new byte[in.readerIndex()];
66                 in.getBytes(0, strippedBytes, 0, in.readerIndex());
67                 LOG.warn("XML message with unwanted leading bytes detected. Discarded the {} leading byte(s): '{}'",
68                         in.readerIndex(), ByteBufUtil.hexDump(Unpooled.wrappedBuffer(strippedBytes)));
69             }
70         }
71         if (in.isReadable()) {
72             try {
73                 out.add(new NetconfMessage(XmlUtil.readXmlToDocument(new ByteBufInputStream(in))));
74             } catch (SAXParseException e) {
75                 LOG.error("Failed to parse received message", e);
76                 out.add(e);
77                 in.skipBytes(in.readableBytes());
78             }
79         } else {
80             LOG.debug("No more content in incoming buffer.");
81         }
82     }
83
84     /**
85      * Check whether a byte is whitespace/control character. Considered whitespace characters: <br/>
86      * SPACE, \t, \n, \v, \r, \f
87      *
88      * @param byteToCheck byte to check
89      * @return true if the byte is a whitespace/control character
90      */
91     private static boolean isWhitespace(final byte byteToCheck) {
92         return byteToCheck <= 0x0d && byteToCheck >= 0x09 || byteToCheck == 0x20;
93     }
94 }