XMLLightweightParser.java 18.6 KB
Newer Older
1
/**
2
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
3
 *
4 5 6 7 8 9 10 11 12 13 14
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
15 16
 */

17
package org.jivesoftware.openfire.nio;
18 19 20

import java.nio.CharBuffer;
import java.nio.charset.Charset;
21 22
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
23 24
import java.util.ArrayList;
import java.util.List;
25
import java.util.Map;
26 27
import java.util.regex.Matcher;
import java.util.regex.Pattern;
28

29
import org.apache.mina.core.buffer.IoBuffer;
30
import org.apache.mina.filter.codec.ProtocolDecoderException;
31 32 33 34
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.PropertyEventDispatcher;
import org.jivesoftware.util.PropertyEventListener;

35 36 37 38 39 40 41 42 43
/**
 * This is a Light-Weight XML Parser.
 * It read data from a channel and collect data until data are available in
 * the channel.
 * When a message is complete you can retrieve messages invoking the method
 * getMsgs() and you can invoke the method areThereMsgs() to know if at least
 * an message is presents.
 *
 * @author Daniele Piras
44
 * @author Gaston Dombiak
45 46
 */
class XMLLightweightParser {
47 48

	private static final Pattern XML_HAS_CHARREF = Pattern.compile("&#(0*([0-9]+)|[xX]0*([0-9a-fA-F]+));");
49

50 51
    private static final String MAX_PROPERTY_NAME = "xmpp.parser.buffer.size";
    private static int maxBufferSize;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    // Chars that rappresent CDATA section start
    protected static char[] CDATA_START = {'<', '!', '[', 'C', 'D', 'A', 'T', 'A', '['};
    // Chars that rappresent CDATA section end
    protected static char[] CDATA_END = {']', ']', '>'};

    // Buffer with all data retrieved
    protected StringBuilder buffer = new StringBuilder();

    // ---- INTERNAL STATUS -------
    // Initial status
    protected static final int INIT = 0;
    // Status used when the first tag name is retrieved
    protected static final int HEAD = 2;
    // Status used when robot is inside the xml and it looking for the tag conclusion
    protected static final int INSIDE = 3;
    // Status used when a '<' is found and try to find the conclusion tag.
    protected static final int PRETAIL = 4;
    // Status used when the ending tag is equal to the head tag
    protected static final int TAIL = 5;
    // Status used when robot is inside the main tag and found an '/' to check '/>'.
    protected static final int VERIFY_CLOSE_TAG = 6;
    //  Status used when you are inside a parameter
    protected static final int INSIDE_PARAM_VALUE = 7;
    //  Status used when you are inside a cdata section
    protected static final int INSIDE_CDATA = 8;
77 78 79 80
    // Status used when you are outside a tag/reading text
    protected static final int OUTSIDE = 9;
    
    final String[] sstatus = {"INIT", "", "HEAD", "INSIDE", "PRETAIL", "TAIL", "VERIFY", "INSIDE_PARAM", "INSIDE_CDATA", "OUTSIDE"};
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98


    // Current robot status
    protected int status = XMLLightweightParser.INIT;

    // Index to looking for a CDATA section start or end.
    protected int cdataOffset = 0;

    // Number of chars that machs with the head tag. If the tailCount is equal to
    // the head length so a close tag is found.
    protected int tailCount = 0;
    // Indicate the starting point in the buffer for the next message.
    protected int startLastMsg = 0;
    // Flag used to discover tag in the form <tag />.
    protected boolean insideRootTag = false;
    // Object conteining the head tag
    protected StringBuilder head = new StringBuilder(5);
    // List with all finished messages found.
99
    protected List<String> msgs = new ArrayList<>();
100
    private int depth = 0;
101 102 103

    protected boolean insideChildrenTag = false;

104
    CharsetDecoder encoder;
105

106 107 108 109 110 111 112
    static {
        // Set default max buffer size to 1MB. If limit is reached then close connection
        maxBufferSize = JiveGlobals.getIntProperty(MAX_PROPERTY_NAME, 1048576);
        // Listen for changes to this property
        PropertyEventDispatcher.addListener(new PropertyListener());
    }

113 114
    public XMLLightweightParser(Charset charset) {
        encoder = charset.newDecoder()
115 116 117
			.onMalformedInput(CodingErrorAction.REPLACE)
			.onUnmappableCharacter(CodingErrorAction.REPLACE);
    }
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

    /*
    * true if the parser has found some complete xml message.
    */
    public boolean areThereMsgs() {
        return (msgs.size() > 0);
    }

    /*
    * @return an array with all messages found
    */
    public String[] getMsgs() {
        String[] res = new String[msgs.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = msgs.get(i);
        }
        msgs.clear();
        invalidateBuffer();
        return res;
    }

    /*
    * Method use to re-initialize the buffer
    */
    protected void invalidateBuffer() {
        if (buffer.length() > 0) {
            String str = buffer.substring(startLastMsg);
            buffer.delete(0, buffer.length());
            buffer.append(str);
            buffer.trimToSize();
        }
        startLastMsg = 0;
    }


    /*
    * Method that add a message to the list and reinit parser.
    */
156
    protected void foundMsg(String msg) throws XMLNotWellFormedException {
157 158
        // Add message to the complete message list
        if (msg != null) {
159
        	if (hasIllegalCharacterReferences(msg)) {
160
                buffer = null;
161
        		throw new XMLNotWellFormedException("Illegal character reference found in: " + msg);
162
        	}
163 164 165 166 167 168 169 170 171
            msgs.add(msg);
        }
        // Move the position into the buffer
        status = XMLLightweightParser.INIT;
        tailCount = 0;
        cdataOffset = 0;
        head.setLength(0);
        insideRootTag = false;
        insideChildrenTag = false;
172
        depth = 0;
173 174 175 176 177
    }

    /*
    * Main reading method
    */
178
    public void read(IoBuffer byteBuffer) throws Exception {
179 180 181 182 183 184
        if (buffer == null) {
            // exception was thrown before, avoid duplicate exception(s)
            // "read" and discard remaining data
            byteBuffer.position(byteBuffer.limit());
            return;
        }
185
        invalidateBuffer();
186 187
        // Check that the buffer is not bigger than 1 Megabyte. For security reasons
        // we will abort parsing when 1 Mega of queued chars was found.
188
        if (buffer.length() > maxBufferSize) {
189 190 191
            // purge the local buffer / free memory
            buffer = null;
            // processing the exception takes quite long
192 193 194
            final ProtocolDecoderException ex = new ProtocolDecoderException("Stopped parsing never ending stanza");
            ex.setHexdump("(redacted hex dump of never ending stanza)");
            throw ex;
195
        }
196 197
        CharBuffer charBuffer = CharBuffer.allocate(byteBuffer.capacity());
        encoder.reset();
198
        encoder.decode(byteBuffer.buf(), charBuffer, false);
199
        char[] buf = new char[charBuffer.position()];
200 201
        charBuffer.flip();
        charBuffer.get(buf);
202
        int readChar = buf.length;
203

204
        // Just return if nothing was read
205
        if (readChar == 0) {
206 207 208
            return;
        }

209
        buffer.append(buf);
210

211 212
        // Robot.
        char ch;
213
        boolean isHighSurrogate = false;
214
        for (int i = 0; i < readChar; i++) {
215
            ch = buf[i];
216 217 218
            if (ch < 0x20 && ch != 0x9 && ch != 0xA && ch != 0xD && ch != 0x0) {
                 //Unicode characters in the range 0x0000-0x001F other than 9, A, and D are not allowed in XML
                 //We need to allow the NULL character, however, for Flash XMLSocket clients to work.
219
                buffer = null;
220
                throw new XMLNotWellFormedException("Character is invalid in: " + ch);
221
            }
222 223 224 225 226 227 228
            if (isHighSurrogate) {
                if (Character.isLowSurrogate(ch)) {
                    // Everything is fine. Clean up traces for surrogates
                    isHighSurrogate = false;
                }
                else {
                    // Trigger error. Found high surrogate not followed by low surrogate
229
                    buffer = null;
230 231 232 233 234 235 236 237
                    throw new Exception("Found high surrogate not followed by low surrogate");
                }
            }
            else if (Character.isHighSurrogate(ch)) {
                isHighSurrogate = true;
            }
            else if (Character.isLowSurrogate(ch)) {
                // Trigger error. Found low surrogate char without a preceding high surrogate
238
                buffer = null;
239 240
                throw new Exception("Found low surrogate char without a preceding high surrogate");
            }
241 242
            if (status == XMLLightweightParser.TAIL) {
                // Looking for the close tag
243
                if (depth < 1 && ch == head.charAt(tailCount)) {
244 245
                    tailCount++;
                    if (tailCount == head.length()) {
246
                        // Close stanza found!
247
                        // Calculate the correct start,end position of the message into the buffer
248
                        int end = buffer.length() - readChar + (i + 1);
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
                        String msg = buffer.substring(startLastMsg, end);
                        // Add message to the list
                        foundMsg(msg);
                        startLastMsg = end;
                    }
                } else {
                    tailCount = 0;
                    status = XMLLightweightParser.INSIDE;
                }
            } else if (status == XMLLightweightParser.PRETAIL) {
                if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
                    cdataOffset++;
                    if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
                        status = XMLLightweightParser.INSIDE_CDATA;
                        cdataOffset = 0;
                        continue;
                    }
                } else {
                    cdataOffset = 0;
                    status = XMLLightweightParser.INSIDE;
                }
                if (ch == '/') {
                    status = XMLLightweightParser.TAIL;
272 273
                    depth--;
                }
274 275 276 277
                else if (ch == '!') {
                    // This is a <! (comment) so ignore it
                    status = XMLLightweightParser.INSIDE;
                }
278 279
                else {
                    depth++;
280 281 282
                }
            } else if (status == XMLLightweightParser.VERIFY_CLOSE_TAG) {
                if (ch == '>') {
283
                    depth--;
284
                    status = XMLLightweightParser.OUTSIDE;
285 286
                    if (depth < 1) {
                        // Found a tag in the form <tag />
287
                        int end = buffer.length() - readChar + (i + 1);
288 289 290 291
                        String msg = buffer.substring(startLastMsg, end);
                        // Add message to the list
                        foundMsg(msg);
                        startLastMsg = end;
292
                    } 
293 294 295
                } else if (ch == '<') {
                    status = XMLLightweightParser.PRETAIL;
                    insideChildrenTag = true;
296 297 298 299 300 301 302 303 304 305 306 307
                } else {
                    status = XMLLightweightParser.INSIDE;
                }
            } else if (status == XMLLightweightParser.INSIDE_PARAM_VALUE) {

                if (ch == '"') {
                    status = XMLLightweightParser.INSIDE;
                }
            } else if (status == XMLLightweightParser.INSIDE_CDATA) {
                if (ch == XMLLightweightParser.CDATA_END[cdataOffset]) {
                    cdataOffset++;
                    if (cdataOffset == XMLLightweightParser.CDATA_END.length) {
308
                        status = XMLLightweightParser.OUTSIDE;
309 310
                        cdataOffset = 0;
                    }
311 312 313 314
                } else if (cdataOffset == XMLLightweightParser.CDATA_END.length-1 && ch == XMLLightweightParser.CDATA_END[cdataOffset - 1]) {
                	// if we are looking for the last CDATA_END char, and we instead found an extra ']' 
                	// char, leave cdataOffset as is and proceed to the next char. This could be a case 
                	// where the XML character data ends with multiple square braces. For Example ]]]>
315 316 317 318 319 320 321 322 323 324 325 326 327
                } else {
                    cdataOffset = 0;
                }
            } else if (status == XMLLightweightParser.INSIDE) {
                if (ch == XMLLightweightParser.CDATA_START[cdataOffset]) {
                    cdataOffset++;
                    if (cdataOffset == XMLLightweightParser.CDATA_START.length) {
                        status = XMLLightweightParser.INSIDE_CDATA;
                        cdataOffset = 0;
                        continue;
                    }
                } else {
                    cdataOffset = 0;
328
                    status = XMLLightweightParser.INSIDE;
329 330 331 332
                }
                if (ch == '"') {
                    status = XMLLightweightParser.INSIDE_PARAM_VALUE;
                } else if (ch == '>') {
333
                    status = XMLLightweightParser.OUTSIDE;
334 335
                    if (insideRootTag && ("stream:stream>".equals(head.toString()) ||
                            ("?xml>".equals(head.toString())) || ("flash:stream>".equals(head.toString())))) {
336
                        // Found closing stream:stream
337
                        int end = buffer.length() - readChar + (i + 1);
338 339 340 341
                        // Skip LF, CR and other "weird" characters that could appear
                        while (startLastMsg < end && '<' != buffer.charAt(startLastMsg)) {
                            startLastMsg++;
                        }
342 343 344 345 346
                        String msg = buffer.substring(startLastMsg, end);
                        foundMsg(msg);
                        startLastMsg = end;
                    }
                    insideRootTag = false;
347
                } else if (ch == '/') {
348 349 350 351
                    status = XMLLightweightParser.VERIFY_CLOSE_TAG;
                }
            } else if (status == XMLLightweightParser.HEAD) {
                if (ch == ' ' || ch == '>') {
352
                    // Append > to head to allow searching </tag>
353
                    head.append('>');
354 355 356 357
                    if(ch == '>')
                        status = XMLLightweightParser.OUTSIDE;
                    else
                        status = XMLLightweightParser.INSIDE;
358 359 360 361
                    insideRootTag = true;
                    insideChildrenTag = false;
                    continue;
                }
362
                else if (ch == '/' && head.length() > 0) {
363
                    status = XMLLightweightParser.VERIFY_CLOSE_TAG;
364
                    depth--;
365
                }
366 367 368 369 370
                head.append(ch);

            } else if (status == XMLLightweightParser.INIT) {
                if (ch == '<') {
                    status = XMLLightweightParser.HEAD;
371
                    depth = 1;
372
                }
373 374 375
                else {
                    startLastMsg++;
                }
376 377 378 379 380 381
            } else if (status == XMLLightweightParser.OUTSIDE) {
                if (ch == '<') {
                    status = XMLLightweightParser.PRETAIL;
                    cdataOffset = 1;
                    insideChildrenTag = true;
                }
382 383
            }
        }
384 385
        if (head.length() > 0 &&
                ("/stream:stream>".equals(head.toString()) || ("/flash:stream>".equals(head.toString())))) {
386 387 388 389
            // Found closing stream:stream
            foundMsg("</stream:stream>");
        }
    }
390

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
	/**
	 * This method verifies if the provided argument contains at least one numeric character reference (
	 * <code>CharRef	   ::=   	'&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';</code>) for which the decimal or hexidecimal
	 * character value refers to an invalid XML 1.0 character.
	 * 
	 * @param string
	 *            The input string
	 * @return <tt>true</tt> if the input string contains an invalid numeric character reference, <tt>false</tt>
	 *         otherwise.
	 * @see http://www.w3.org/TR/2008/REC-xml-20081126/#dt-charref
	 */
	public static boolean hasIllegalCharacterReferences(String string) {
		// If there's no character reference, don't bother to do more specific checking.
		final Matcher matcher = XML_HAS_CHARREF.matcher(string);

		while (matcher.find()) {
			final String decValue = matcher.group(2);
			if (decValue != null) {
				final int value = Integer.parseInt(decValue);
				if (!isLegalXmlCharacter(value)) {
					return true;
				} else {
					continue;
				}
			}

			final String hexValue = matcher.group(3);
			if (hexValue != null) {
				final int value = Integer.parseInt(hexValue, 16);
				if (!isLegalXmlCharacter(value)) {
					return true;
				} else {
					continue;
				}
			}

			// This is bad. The XML_HAS_CHARREF expression should have a hit for either the decimal
			// or the heximal notation.
			throw new IllegalStateException(
					"An error occurred while searching for illegal character references in the value [" + string + "].");
		}

		return false;
	}

	/**
	 * Verifies if the codepoint value represents a valid character as defined in paragraph 2.2 of
	 * "Extensible Markup Language (XML) 1.0 (Fifth Edition)"
	 * 
	 * @param value
	 *            the codepoint
	 * @return <tt>true</tt> if the codepoint is a valid charater per XML 1.0 definition, <tt>false</tt> otherwise.
	 * @see http://www.w3.org/TR/2008/REC-xml-20081126/#NT-Char
	 */
	public static boolean isLegalXmlCharacter(int value) {
		return value == 0x9 || value == 0xA || value == 0xD || (value >= 0x20 && value <= 0xD7FF)
				|| (value >= 0xE000 && value <= 0xFFFD) || (value >= 0x10000 && value <= 0x10FFFF);
	}
	
450
    private static class PropertyListener implements PropertyEventListener {
451
        @Override
452 453 454 455 456 457 458 459 460
        public void propertySet(String property, Map<String, Object> params) {
            if (MAX_PROPERTY_NAME.equals(property)) {
                String value = (String) params.get("value");
                if (value != null) {
                    maxBufferSize = Integer.parseInt(value);
                }
            }
        }

461
        @Override
462 463 464 465 466 467 468
        public void propertyDeleted(String property, Map<String, Object> params) {
            if (MAX_PROPERTY_NAME.equals(property)) {
                // Use default value when none was specified
                maxBufferSize = 1048576;
            }
        }

469
        @Override
470 471 472 473
        public void xmlPropertySet(String property, Map<String, Object> params) {
            // Do nothing
        }

474
        @Override
475 476 477 478
        public void xmlPropertyDeleted(String property, Map<String, Object> params) {
            // Do nothing
        }
    }
479
}