NanoHttpd / nanohttpd

Tiny, easily embeddable HTTP server in Java.
http://nanohttpd.org
BSD 3-Clause "New" or "Revised" License
6.92k stars 1.69k forks source link

Web server infinite loop #529

Open mlohbihler opened 5 years ago

mlohbihler commented 5 years ago

It is possible to get an instance of NanoHTTPD into an infinite loop by causing an exception in the send method which would write the "Could not send response to the client" log message. The following code will produce this when you have a webserver running locally on port 8080:

public static void main(final String[] args) throws IOException {
    final Socket socket = new Socket("localhost", 8080);
    write(socket.getOutputStream(), "GET / HTTP/1.1");
    socket.close();
}

Immediately closing the socket prevents the server from being able to write the response, producing the error. I have been consistently able to produce this condition in version 2.2.0.

levischuckeats commented 5 years ago

I have experienced this too, all I did was use a curl request.

RedShift1 commented 5 years ago

Does it still happen in 2.3.1?

rousea commented 5 years ago

I am seeing the same issue as well, even off of the current working tree. The issue stems from not being able to find a cut point between the headers and the body.

https://github.com/NanoHttpd/nanohttpd/blob/b04a342a4bcd0ff44be65138acffc73a29381c72/core/src/main/java/org/nanohttpd/protocols/http/HTTPSession.java#L380-L383

The InputStream is then reset and read again, since we are starting over at the beginning. I'm not sure if that request complies with the spec, but the implementation should handle this gracefully.

Adding either \r\n\r\n or \n\n to the end of that request should resolve the issue.