Path: blob/master/test/jdk/com/sun/net/httpserver/InputNotRead.java
41152 views
/*1* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 826676126* @summary HttpServer can fail with an assertion error when a handler doesn't fully27* read the request body and sends back a reply with no content, or when28* the client closes its outputstream while the server tries to drains29* its content.30* @run testng/othervm InputNotRead31* @run testng/othervm -Djava.net.preferIPv6Addresses=true InputNotRead32*/3334import java.io.BufferedReader;35import java.io.IOException;36import java.io.InputStreamReader;37import java.io.OutputStreamWriter;38import java.io.PrintWriter;39import java.net.InetAddress;40import java.net.InetSocketAddress;41import java.net.Socket;42import java.util.concurrent.ExecutorService;43import java.util.concurrent.Executors;44import java.util.concurrent.ThreadFactory;45import java.util.concurrent.atomic.AtomicLong;46import java.util.logging.Level;47import java.util.logging.Logger;4849import com.sun.net.httpserver.HttpExchange;50import com.sun.net.httpserver.HttpHandler;51import com.sun.net.httpserver.HttpServer;5253import org.testng.annotations.Test;5455import static java.nio.charset.StandardCharsets.*;5657public class InputNotRead {5859private static final int msgCode = 200;60private static final String someContext = "/context";6162static class ServerThreadFactory implements ThreadFactory {63static final AtomicLong tokens = new AtomicLong();64@Override65public Thread newThread(Runnable r) {66var thread = new Thread(r, "Server-" + tokens.incrementAndGet());67thread.setDaemon(true);68return thread;69}70}7172static {73Logger.getLogger("").setLevel(Level.ALL);74Logger.getLogger("").getHandlers()[0].setLevel(Level.ALL);75}7677@Test78public void testSendResponse() throws Exception {79System.out.println("testSendResponse()");80InetAddress loopback = InetAddress.getLoopbackAddress();81HttpServer server = HttpServer.create(new InetSocketAddress(loopback, 0), 0);82ExecutorService executor = Executors.newCachedThreadPool(new ServerThreadFactory());83server.setExecutor(executor);84try {85server.createContext(someContext, new HttpHandler() {86@Override87public void handle(HttpExchange msg) throws IOException {88System.err.println("Handling request: " + msg.getRequestURI());89byte[] reply = new byte[0];90try {91msg.getRequestBody().read();92try {93msg.sendResponseHeaders(msgCode, reply.length == 0 ? -1 : reply.length);94} catch(IOException ioe) {95ioe.printStackTrace();96}97} finally {98// don't close the exchange and don't close any stream99// to trigger the assertion.100System.err.println("Request handled: " + msg.getRequestURI());101}102}103});104server.start();105System.out.println("Server started at port "106+ server.getAddress().getPort());107108runRawSocketHttpClient(loopback, server.getAddress().getPort(), -1);109} finally {110System.out.println("shutting server down");111executor.shutdown();112server.stop(0);113}114System.out.println("Server finished.");115}116117@Test118public void testCloseOutputStream() throws Exception {119System.out.println("testCloseOutputStream()");120InetAddress loopback = InetAddress.getLoopbackAddress();121HttpServer server = HttpServer.create(new InetSocketAddress(loopback, 0), 0);122ExecutorService executor = Executors.newCachedThreadPool(new ServerThreadFactory());123server.setExecutor(executor);124try {125server.createContext(someContext, new HttpHandler() {126@Override127public void handle(HttpExchange msg) throws IOException {128System.err.println("Handling request: " + msg.getRequestURI());129byte[] reply = "Here is my reply!".getBytes(UTF_8);130try {131BufferedReader r = new BufferedReader(new InputStreamReader(msg.getRequestBody()));132r.read();133try {134msg.sendResponseHeaders(msgCode, reply.length == 0 ? -1 : reply.length);135msg.getResponseBody().write(reply);136msg.getResponseBody().close();137Thread.sleep(50);138} catch(IOException | InterruptedException ie) {139ie.printStackTrace();140}141} finally {142System.err.println("Request handled: " + msg.getRequestURI());143}144}145});146server.start();147System.out.println("Server started at port "148+ server.getAddress().getPort());149150runRawSocketHttpClient(loopback, server.getAddress().getPort(), 64 * 1024 + 16);151} finally {152System.out.println("shutting server down");153executor.shutdown();154server.stop(0);155}156System.out.println("Server finished.");157}158159static void runRawSocketHttpClient(InetAddress address, int port, int contentLength)160throws Exception161{162Socket socket = null;163PrintWriter writer = null;164BufferedReader reader = null;165final String CRLF = "\r\n";166try {167socket = new Socket(address, port);168writer = new PrintWriter(new OutputStreamWriter(169socket.getOutputStream()));170System.out.println("Client connected by socket: " + socket);171String body = "I will send all the data.";172if (contentLength <= 0)173contentLength = body.getBytes(UTF_8).length;174175writer.print("GET " + someContext + "/ HTTP/1.1" + CRLF);176writer.print("User-Agent: Java/"177+ System.getProperty("java.version")178+ CRLF);179writer.print("Host: " + address.getHostName() + CRLF);180writer.print("Accept: */*" + CRLF);181writer.print("Content-Length: " + contentLength + CRLF);182writer.print("Connection: keep-alive" + CRLF);183writer.print(CRLF); // Important, else the server will expect that184// there's more into the request.185writer.flush();186System.out.println("Client wrote request to socket: " + socket);187writer.print(body);188writer.flush();189190reader = new BufferedReader(new InputStreamReader(191socket.getInputStream()));192System.out.println("Client start reading from server:" );193String line = reader.readLine();194for (; line != null; line = reader.readLine()) {195if (line.isEmpty()) {196break;197}198System.out.println("\"" + line + "\"");199}200System.out.println("Client finished reading from server" );201} finally {202// give time to the server to try & drain its input stream203Thread.sleep(500);204// closes the client outputstream while the server is draining205// it206if (writer != null) {207writer.close();208}209// give time to the server to trigger its assertion210// error before closing the connection211Thread.sleep(500);212if (reader != null)213try {214reader.close();215} catch (IOException logOrIgnore) {216logOrIgnore.printStackTrace();217}218if (socket != null) {219try {220socket.close();221} catch (IOException logOrIgnore) {222logOrIgnore.printStackTrace();223}224}225}226System.out.println("Client finished." );227}228229}230231232