Untangle the XML/Hello message decoders
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / 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.util.handler;
9
10 import io.netty.buffer.ByteBuf;
11 import io.netty.buffer.ByteBufUtil;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.handler.codec.ByteToMessageDecoder;
14
15 import java.io.ByteArrayInputStream;
16 import java.nio.ByteBuffer;
17 import java.util.Arrays;
18 import java.util.List;
19
20 import org.opendaylight.controller.netconf.api.NetconfMessage;
21 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
22 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
23 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.w3c.dom.Document;
27
28 import com.google.common.annotations.VisibleForTesting;
29 import com.google.common.base.Charsets;
30 import com.google.common.collect.ImmutableList;
31
32 /**
33  * Customized NetconfXMLToMessageDecoder that reads additional header with
34  * session metadata from
35  * {@link org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage}
36  * . Used by netconf server to retrieve information about session metadata.
37  */
38 public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder {
39     private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToHelloMessageDecoder.class);
40
41     private static final List<byte[]> POSSIBLE_ENDS = ImmutableList.of(
42             new byte[] { ']', '\n' },
43             new byte[] { ']', '\r', '\n' });
44     private static final List<byte[]> POSSIBLE_STARTS = ImmutableList.of(
45             new byte[] { '[' },
46             new byte[] { '\r', '\n', '[' },
47             new byte[] { '\n', '[' });
48
49     @Override
50     @VisibleForTesting
51     public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
52         if (in.readableBytes() == 0) {
53             LOG.debug("No more content in incoming buffer.");
54             return;
55         }
56
57         in.markReaderIndex();
58         try {
59             LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
60             byte[] bytes = new byte[in.readableBytes()];
61             in.readBytes(bytes);
62
63             logMessage(bytes);
64
65             // Extract bytes containing header with additional metadata
66             String additionalHeader = null;
67             if (startsWithAdditionalHeader(bytes)) {
68                 // Auth information containing username, ip address... extracted for monitoring
69                 int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes);
70                 if (endOfAuthHeader > -1) {
71                     byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2);
72                     additionalHeader = additionalHeaderToString(additionalHeaderBytes);
73                     bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length);
74                 }
75             }
76
77             Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes));
78
79             final NetconfMessage message;
80             if (additionalHeader != null) {
81                 message = new NetconfHelloMessage(doc, NetconfHelloMessageAdditionalHeader.fromString(additionalHeader));
82             } else {
83                 message = new NetconfHelloMessage(doc);
84             }
85             out.add(message);
86         } finally {
87             in.discardReadBytes();
88         }
89     }
90
91     private int getAdditionalHeaderEndIndex(byte[] bytes) {
92         for (byte[] possibleEnd : POSSIBLE_ENDS) {
93             int idx = findByteSequence(bytes, possibleEnd);
94
95             if (idx != -1) {
96                 return idx;
97             }
98         }
99
100         return -1;
101     }
102
103     private static int findByteSequence(final byte[] bytes, final byte[] sequence) {
104         if (bytes.length < sequence.length) {
105             throw new IllegalArgumentException("Sequence to be found is longer than the given byte array.");
106         }
107         if (bytes.length == sequence.length) {
108             if (Arrays.equals(bytes, sequence)) {
109                 return 0;
110             } else {
111                 return -1;
112             }
113         }
114         int j = 0;
115         for (int i = 0; i < bytes.length; i++) {
116             if (bytes[i] == sequence[j]) {
117                 j++;
118                 if (j == sequence.length) {
119                     return i - j + 1;
120                 }
121             } else {
122                 j = 0;
123             }
124         }
125         return -1;
126     }
127
128
129     private void logMessage(byte[] bytes) {
130         String s = Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
131         LOG.debug("Parsing message \n{}", s);
132     }
133
134     private boolean startsWithAdditionalHeader(byte[] bytes) {
135         for (byte[] possibleStart : POSSIBLE_STARTS) {
136             int i = 0;
137             for (byte b : possibleStart) {
138                 if(bytes[i++] != b)
139                     break;
140
141                 if(i == possibleStart.length)
142                     return true;
143             }
144         }
145
146         return false;
147     }
148
149     private String additionalHeaderToString(byte[] bytes) {
150         return Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
151     }
152
153 }