perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.64k stars 1.56k forks source link

Calling request.body() may result in a NullPointerException #1072

Closed rbordon-meli closed 4 years ago

rbordon-meli commented 5 years ago

As the title said, calling request.body() may result in a NullPointerException.

This may be caused because there is no response handle if an error occurred during readBodyAsBytes(). So the response of bodyAsBytes() is null, then invoking bytes.length in String class throws a NPE.

Request

public String body() {

    if (body == null) {
        body = StringUtils.toString(bodyAsBytes(), servletRequest.getCharacterEncoding());
    }

    return body;
}

public byte[] bodyAsBytes() {
    if (bodyAsBytes == null) {
        readBodyAsBytes();
    }
    return bodyAsBytes;
}

private void readBodyAsBytes() {
    try {
        bodyAsBytes = IOUtils.toByteArray(servletRequest.getInputStream());
    } catch (Exception e) {
        LOG.warn("Exception when reading body", e);
    }
}

StringUtils

public static String toString(byte[] bytes, String encoding) {
    String str;

    if (encoding != null && Charset.isSupported(encoding)) {
        try {
            str = new String(bytes, encoding);
        } catch (UnsupportedEncodingException e) {
            // Uses same func as Charset.isSupported (cannot happen)
            str = new String(bytes);
        }
    } else {
        str = new String(bytes);
    }

    return str;
}

String

public String(byte bytes[], String charsetName)
        throws UnsupportedEncodingException {
    this(bytes, 0, bytes.length, charsetName);
}

A way to reproduce the bug, is debugging the app with a breakpoint in the line bodyAsBytes = IOUtils.toByteArray(servletRequest.getInputStream()); Then cancel the request, in order to produce an IOException. This makes bodyAsBytes null. I´ve used a JSON request of 1.5 MB

emportella commented 5 years ago

I`m currently suffering intensive with this bug. about 10 times per sec in multiple endpoins for both PUT and POST

robax commented 4 years ago

+1 also running into a problem related to this.

sanket-sheth commented 4 years ago

Any update on this issue?

perwendel commented 4 years ago

Fixed in #1170

robax commented 3 years ago

It seems this patch isn't in 2.9.2. Can we get a quick build with this patch? @perwendel And thank you!