jdk/test/java/net/httpclient/ProxyTest.java
changeset 46138 5982afcbf9dc
child 46157 f3c2dcb8d8fe
equal deleted inserted replaced
46111:14df107500cc 46138:5982afcbf9dc
       
     1 /*
       
     2  * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.
       
     8  *
       
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    12  * version 2 for more details (a copy is included in the LICENSE file that
       
    13  * accompanied this code).
       
    14  *
       
    15  * You should have received a copy of the GNU General Public License version
       
    16  * 2 along with this work; if not, write to the Free Software Foundation,
       
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    18  *
       
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    20  * or visit www.oracle.com if you need additional information or have any
       
    21  * questions.
       
    22  */
       
    23 
       
    24 import com.sun.net.httpserver.HttpContext;
       
    25 import com.sun.net.httpserver.HttpExchange;
       
    26 import com.sun.net.httpserver.HttpHandler;
       
    27 import com.sun.net.httpserver.HttpServer;
       
    28 import com.sun.net.httpserver.HttpsConfigurator;
       
    29 import com.sun.net.httpserver.HttpsParameters;
       
    30 import com.sun.net.httpserver.HttpsServer;
       
    31 import java.io.IOException;
       
    32 import java.io.InputStream;
       
    33 import java.io.OutputStream;
       
    34 import java.io.OutputStreamWriter;
       
    35 import java.io.PrintWriter;
       
    36 import java.io.Writer;
       
    37 import java.net.HttpURLConnection;
       
    38 import java.net.InetAddress;
       
    39 import java.net.InetSocketAddress;
       
    40 import java.net.Proxy;
       
    41 import java.net.ProxySelector;
       
    42 import java.net.ServerSocket;
       
    43 import java.net.Socket;
       
    44 import java.net.URI;
       
    45 import java.net.URISyntaxException;
       
    46 import java.nio.charset.StandardCharsets;
       
    47 import java.security.NoSuchAlgorithmException;
       
    48 import javax.net.ssl.HostnameVerifier;
       
    49 import javax.net.ssl.HttpsURLConnection;
       
    50 import javax.net.ssl.SSLContext;
       
    51 import javax.net.ssl.SSLSession;
       
    52 import jdk.incubator.http.HttpClient;
       
    53 import jdk.incubator.http.HttpRequest;
       
    54 import jdk.incubator.http.HttpResponse;
       
    55 import jdk.testlibrary.SimpleSSLContext;
       
    56 
       
    57 /**
       
    58  * @test
       
    59  * @bug 8185852
       
    60  * @summary verifies that passing a proxy with an unresolved address does
       
    61  *          not cause  java.nio.channels.UnresolvedAddressException
       
    62  * @modules jdk.incubator.httpclient
       
    63  * @library /lib/testlibrary/
       
    64  * @build jdk.testlibrary.SimpleSSLContext ProxyTest
       
    65  * @run main/othervm ProxyTest
       
    66  * @author danielfuchs
       
    67  */
       
    68 public class ProxyTest {
       
    69 
       
    70     static {
       
    71         try {
       
    72             HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
       
    73                     public boolean verify(String hostname, SSLSession session) {
       
    74                         return true;
       
    75                     }
       
    76                 });
       
    77             SSLContext.setDefault(new SimpleSSLContext().get());
       
    78         } catch (IOException ex) {
       
    79             throw new ExceptionInInitializerError(ex);
       
    80         }
       
    81     }
       
    82 
       
    83     static final String RESPONSE = "<html><body><p>Hello World!</body></html>";
       
    84     static final String PATH = "/foo/";
       
    85 
       
    86     static HttpServer createHttpsServer() throws IOException, NoSuchAlgorithmException {
       
    87         HttpsServer server = com.sun.net.httpserver.HttpsServer.create();
       
    88         HttpContext context = server.createContext(PATH);
       
    89         context.setHandler(new HttpHandler() {
       
    90             @Override
       
    91             public void handle(HttpExchange he) throws IOException {
       
    92                 he.getResponseHeaders().add("encoding", "UTF-8");
       
    93                 he.sendResponseHeaders(200, RESPONSE.length());
       
    94                 he.getResponseBody().write(RESPONSE.getBytes(StandardCharsets.UTF_8));
       
    95                 he.close();
       
    96             }
       
    97         });
       
    98 
       
    99         server.setHttpsConfigurator(new Configurator(SSLContext.getDefault()));
       
   100         server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
       
   101         return server;
       
   102     }
       
   103 
       
   104     public static void main(String[] args)
       
   105             throws IOException,
       
   106             URISyntaxException,
       
   107             NoSuchAlgorithmException,
       
   108             InterruptedException
       
   109     {
       
   110         HttpServer server = createHttpsServer();
       
   111         server.start();
       
   112         try {
       
   113             test(server, HttpClient.Version.HTTP_1_1);
       
   114             // test(server, HttpClient.Version.HTTP_2);
       
   115         } finally {
       
   116             server.stop(0);
       
   117             System.out.println("Server stopped");
       
   118         }
       
   119     }
       
   120 
       
   121     public static void test(HttpServer server, HttpClient.Version version)
       
   122             throws IOException,
       
   123             URISyntaxException,
       
   124             NoSuchAlgorithmException,
       
   125             InterruptedException
       
   126     {
       
   127         System.out.println("Server is: " + server.getAddress().toString());
       
   128         System.out.println("Verifying communication with server");
       
   129         URI uri = new URI("https:/" + server.getAddress().toString() + PATH + "x");
       
   130         try (InputStream is = uri.toURL().openConnection().getInputStream()) {
       
   131             String resp = new String(is.readAllBytes(), StandardCharsets.UTF_8);
       
   132             System.out.println(resp);
       
   133             if (!RESPONSE.equals(resp)) {
       
   134                 throw new AssertionError("Unexpected response from server");
       
   135             }
       
   136         }
       
   137         System.out.println("Communication with server OK");
       
   138 
       
   139         TunnelingProxy proxy = new TunnelingProxy(server);
       
   140         proxy.start();
       
   141         try {
       
   142             System.out.println("Proxy started");
       
   143             Proxy p = new Proxy(Proxy.Type.HTTP,
       
   144                     InetSocketAddress.createUnresolved("localhost", proxy.getAddress().getPort()));
       
   145             System.out.println("Verifying communication with proxy");
       
   146             HttpURLConnection conn = (HttpURLConnection)uri.toURL().openConnection(p);
       
   147             try (InputStream is = conn.getInputStream()) {
       
   148                 String resp = new String(is.readAllBytes(), StandardCharsets.UTF_8);
       
   149                 System.out.println(resp);
       
   150                 if (!RESPONSE.equals(resp)) {
       
   151                     throw new AssertionError("Unexpected response from proxy");
       
   152                 }
       
   153             }
       
   154             System.out.println("Communication with proxy OK");
       
   155             System.out.println("\nReal test begins here.");
       
   156             System.out.println("Setting up request with HttpClient for version: "
       
   157                     + version.name());
       
   158             ProxySelector ps = ProxySelector.of(
       
   159                     InetSocketAddress.createUnresolved("localhost", proxy.getAddress().getPort()));
       
   160             HttpClient client = HttpClient.newBuilder()
       
   161                 .version(version)
       
   162                 .proxy(ps)
       
   163                 .build();
       
   164             HttpRequest request = HttpRequest.newBuilder()
       
   165                 .uri(uri)
       
   166                 .GET()
       
   167                 .build();
       
   168 
       
   169             System.out.println("Sending request with HttpClient");
       
   170             HttpResponse<String> response
       
   171                 = client.send(request, HttpResponse.BodyHandler.asString());
       
   172             System.out.println("Got response");
       
   173             String resp = response.body();
       
   174             System.out.println("Received: " + resp);
       
   175             if (!RESPONSE.equals(resp)) {
       
   176                 throw new AssertionError("Unexpected response");
       
   177             }
       
   178         } finally {
       
   179             System.out.println("Stopping proxy");
       
   180             proxy.stop();
       
   181             System.out.println("Proxy stopped");
       
   182         }
       
   183     }
       
   184 
       
   185     static class TunnelingProxy {
       
   186         final Thread accept;
       
   187         final ServerSocket ss;
       
   188         final boolean DEBUG = false;
       
   189         final HttpServer serverImpl;
       
   190         TunnelingProxy(HttpServer serverImpl) throws IOException {
       
   191             this.serverImpl = serverImpl;
       
   192             ss = new ServerSocket();
       
   193             accept = new Thread(this::accept);
       
   194         }
       
   195 
       
   196         void start() throws IOException {
       
   197             ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
       
   198             accept.start();
       
   199         }
       
   200 
       
   201         // Pipe the input stream to the output stream.
       
   202         private synchronized Thread pipe(InputStream is, OutputStream os, char tag) {
       
   203             return new Thread("TunnelPipe("+tag+")") {
       
   204                 @Override
       
   205                 public void run() {
       
   206                     try {
       
   207                         try {
       
   208                             int c;
       
   209                             while ((c = is.read()) != -1) {
       
   210                                 os.write(c);
       
   211                                 os.flush();
       
   212                                 // if DEBUG prints a + or a - for each transferred
       
   213                                 // character.
       
   214                                 if (DEBUG) System.out.print(tag);
       
   215                             }
       
   216                             is.close();
       
   217                         } finally {
       
   218                             os.close();
       
   219                         }
       
   220                     } catch (IOException ex) {
       
   221                         if (DEBUG) ex.printStackTrace(System.out);
       
   222                     }
       
   223                 }
       
   224             };
       
   225         }
       
   226 
       
   227         public InetSocketAddress getAddress() {
       
   228             return new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort());
       
   229         }
       
   230 
       
   231         // This is a bit shaky. It doesn't handle continuation
       
   232         // lines, but our client shouldn't send any.
       
   233         // Read a line from the input stream, swallowing the final
       
   234         // \r\n sequence. Stops at the first \n, doesn't complain
       
   235         // if it wasn't preceded by '\r'.
       
   236         //
       
   237         String readLine(InputStream r) throws IOException {
       
   238             StringBuilder b = new StringBuilder();
       
   239             int c;
       
   240             while ((c = r.read()) != -1) {
       
   241                 if (c == '\n') break;
       
   242                 b.appendCodePoint(c);
       
   243             }
       
   244             if (b.codePointAt(b.length() -1) == '\r') {
       
   245                 b.delete(b.length() -1, b.length());
       
   246             }
       
   247             return b.toString();
       
   248         }
       
   249 
       
   250         public void accept() {
       
   251             Socket clientConnection = null;
       
   252             try {
       
   253                 while (true) {
       
   254                     System.out.println("Tunnel: Waiting for client");
       
   255                     Socket previous = clientConnection;
       
   256                     try {
       
   257                         clientConnection = ss.accept();
       
   258                     } catch (IOException io) {
       
   259                         if (DEBUG) io.printStackTrace(System.out);
       
   260                         break;
       
   261                     } finally {
       
   262                         // we have only 1 client at a time, so it is safe
       
   263                         // to close the previous connection here
       
   264                         if (previous != null) previous.close();
       
   265                     }
       
   266                     System.out.println("Tunnel: Client accepted");
       
   267                     Socket targetConnection = null;
       
   268                     InputStream  ccis = clientConnection.getInputStream();
       
   269                     OutputStream ccos = clientConnection.getOutputStream();
       
   270                     Writer w = new OutputStreamWriter(ccos, "UTF-8");
       
   271                     PrintWriter pw = new PrintWriter(w);
       
   272                     System.out.println("Tunnel: Reading request line");
       
   273                     String requestLine = readLine(ccis);
       
   274                     System.out.println("Tunnel: Request status line: " + requestLine);
       
   275                     if (requestLine.startsWith("CONNECT ")) {
       
   276                         // We should probably check that the next word following
       
   277                         // CONNECT is the host:port of our HTTPS serverImpl.
       
   278                         // Some improvement for a followup!
       
   279 
       
   280                         // Read all headers until we find the empty line that
       
   281                         // signals the end of all headers.
       
   282                         while(!requestLine.equals("")) {
       
   283                             System.out.println("Tunnel: Reading header: "
       
   284                                                + (requestLine = readLine(ccis)));
       
   285                         }
       
   286 
       
   287                         // Open target connection
       
   288                         targetConnection = new Socket(
       
   289                                 serverImpl.getAddress().getAddress(),
       
   290                                 serverImpl.getAddress().getPort());
       
   291 
       
   292                         // Then send the 200 OK response to the client
       
   293                         System.out.println("Tunnel: Sending "
       
   294                                            + "HTTP/1.1 200 OK\r\n\r\n");
       
   295                         pw.print("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
       
   296                         pw.flush();
       
   297                     } else {
       
   298                         // This should not happen.
       
   299                         throw new IOException("Tunnel: Unexpected status line: "
       
   300                                            + requestLine);
       
   301                     }
       
   302 
       
   303                     // Pipe the input stream of the client connection to the
       
   304                     // output stream of the target connection and conversely.
       
   305                     // Now the client and target will just talk to each other.
       
   306                     System.out.println("Tunnel: Starting tunnel pipes");
       
   307                     Thread t1 = pipe(ccis, targetConnection.getOutputStream(), '+');
       
   308                     Thread t2 = pipe(targetConnection.getInputStream(), ccos, '-');
       
   309                     t1.start();
       
   310                     t2.start();
       
   311 
       
   312                     // We have only 1 client... wait until it has finished before
       
   313                     // accepting a new connection request.
       
   314                     // System.out.println("Tunnel: Waiting for pipes to close");
       
   315                     // t1.join();
       
   316                     // t2.join();
       
   317                     System.out.println("Tunnel: Done - waiting for next client");
       
   318                 }
       
   319             } catch (Throwable ex) {
       
   320                 try {
       
   321                     ss.close();
       
   322                 } catch (IOException ex1) {
       
   323                     ex.addSuppressed(ex1);
       
   324                 }
       
   325                 ex.printStackTrace(System.err);
       
   326             }
       
   327         }
       
   328 
       
   329         void stop() throws IOException {
       
   330             ss.close();
       
   331         }
       
   332 
       
   333     }
       
   334 
       
   335     static class Configurator extends HttpsConfigurator {
       
   336         public Configurator(SSLContext ctx) {
       
   337             super(ctx);
       
   338         }
       
   339 
       
   340         @Override
       
   341         public void configure (HttpsParameters params) {
       
   342             params.setSSLParameters (getSSLContext().getSupportedSSLParameters());
       
   343         }
       
   344     }
       
   345 
       
   346 }