src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/websocket/OpeningHandshake.java
branchhttp-client-branch
changeset 56089 42208b2f224e
parent 56088 38fac6d0521d
child 56090 5c7fb702948a
equal deleted inserted replaced
56088:38fac6d0521d 56089:42208b2f224e
     1 /*
       
     2  * Copyright (c) 2015, 2018, 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.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package jdk.incubator.http.internal.websocket;
       
    27 
       
    28 import jdk.incubator.http.HttpClient;
       
    29 import jdk.incubator.http.HttpClient.Version;
       
    30 import jdk.incubator.http.HttpHeaders;
       
    31 import jdk.incubator.http.HttpRequest;
       
    32 import jdk.incubator.http.HttpResponse;
       
    33 import jdk.incubator.http.HttpResponse.BodyHandler;
       
    34 import jdk.incubator.http.WebSocketHandshakeException;
       
    35 import jdk.incubator.http.internal.common.MinimalFuture;
       
    36 import jdk.incubator.http.internal.common.Pair;
       
    37 import jdk.incubator.http.internal.common.Utils;
       
    38 
       
    39 import java.io.IOException;
       
    40 import java.net.InetSocketAddress;
       
    41 import java.net.Proxy;
       
    42 import java.net.ProxySelector;
       
    43 import java.net.URI;
       
    44 import java.net.URISyntaxException;
       
    45 import java.net.URLPermission;
       
    46 import java.nio.charset.StandardCharsets;
       
    47 import java.security.AccessController;
       
    48 import java.security.MessageDigest;
       
    49 import java.security.NoSuchAlgorithmException;
       
    50 import java.security.PrivilegedAction;
       
    51 import java.security.SecureRandom;
       
    52 import java.time.Duration;
       
    53 import java.util.Base64;
       
    54 import java.util.Collection;
       
    55 import java.util.Collections;
       
    56 import java.util.LinkedHashSet;
       
    57 import java.util.List;
       
    58 import java.util.Optional;
       
    59 import java.util.Set;
       
    60 import java.util.TreeSet;
       
    61 import java.util.concurrent.CompletableFuture;
       
    62 import java.util.stream.Collectors;
       
    63 import java.util.stream.Stream;
       
    64 
       
    65 import static java.lang.String.format;
       
    66 import static jdk.incubator.http.internal.common.Utils.isValidName;
       
    67 import static jdk.incubator.http.internal.common.Utils.permissionForProxy;
       
    68 import static jdk.incubator.http.internal.common.Utils.stringOf;
       
    69 
       
    70 public class OpeningHandshake {
       
    71 
       
    72     private static final String HEADER_CONNECTION = "Connection";
       
    73     private static final String HEADER_UPGRADE    = "Upgrade";
       
    74     private static final String HEADER_ACCEPT     = "Sec-WebSocket-Accept";
       
    75     private static final String HEADER_EXTENSIONS = "Sec-WebSocket-Extensions";
       
    76     private static final String HEADER_KEY        = "Sec-WebSocket-Key";
       
    77     private static final String HEADER_PROTOCOL   = "Sec-WebSocket-Protocol";
       
    78     private static final String HEADER_VERSION    = "Sec-WebSocket-Version";
       
    79     private static final String VERSION           = "13";  // WebSocket's lucky number
       
    80 
       
    81     private static final Set<String> ILLEGAL_HEADERS;
       
    82 
       
    83     static {
       
    84         ILLEGAL_HEADERS = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
       
    85         ILLEGAL_HEADERS.addAll(List.of(HEADER_ACCEPT,
       
    86                                        HEADER_EXTENSIONS,
       
    87                                        HEADER_KEY,
       
    88                                        HEADER_PROTOCOL,
       
    89                                        HEADER_VERSION));
       
    90     }
       
    91 
       
    92     private static final SecureRandom random = new SecureRandom();
       
    93 
       
    94     private final MessageDigest sha1;
       
    95     private final HttpClient client;
       
    96 
       
    97     {
       
    98         try {
       
    99             sha1 = MessageDigest.getInstance("SHA-1");
       
   100         } catch (NoSuchAlgorithmException e) {
       
   101             // Shouldn't happen: SHA-1 must be available in every Java platform
       
   102             // implementation
       
   103             throw new InternalError("Minimum requirements", e);
       
   104         }
       
   105     }
       
   106 
       
   107     private final HttpRequest request;
       
   108     private final Collection<String> subprotocols;
       
   109     private final String nonce;
       
   110 
       
   111     public OpeningHandshake(BuilderImpl b) {
       
   112         checkURI(b.getUri());
       
   113         Proxy proxy = proxyFor(b.getProxySelector(), b.getUri());
       
   114         checkPermissions(b, proxy);
       
   115         this.client = b.getClient();
       
   116         URI httpURI = createRequestURI(b.getUri());
       
   117         HttpRequest.Builder requestBuilder = HttpRequest.newBuilder(httpURI);
       
   118         Duration connectTimeout = b.getConnectTimeout();
       
   119         if (connectTimeout != null) {
       
   120             requestBuilder.timeout(connectTimeout);
       
   121         }
       
   122         for (Pair<String, String> p : b.getHeaders()) {
       
   123             if (ILLEGAL_HEADERS.contains(p.first)) {
       
   124                 throw illegal("Illegal header: " + p.first);
       
   125             }
       
   126             requestBuilder.header(p.first, p.second);
       
   127         }
       
   128         this.subprotocols = createRequestSubprotocols(b.getSubprotocols());
       
   129         if (!this.subprotocols.isEmpty()) {
       
   130             String p = this.subprotocols.stream().collect(Collectors.joining(", "));
       
   131             requestBuilder.header(HEADER_PROTOCOL, p);
       
   132         }
       
   133         requestBuilder.header(HEADER_VERSION, VERSION);
       
   134         this.nonce = createNonce();
       
   135         requestBuilder.header(HEADER_KEY, this.nonce);
       
   136         // Setting request version to HTTP/1.1 forcibly, since it's not possible
       
   137         // to upgrade from HTTP/2 to WebSocket (as of August 2016):
       
   138         //
       
   139         //     https://tools.ietf.org/html/draft-hirano-httpbis-websocket-over-http2-00
       
   140         this.request = requestBuilder.version(Version.HTTP_1_1).GET().build();
       
   141         WebSocketRequest r = (WebSocketRequest) this.request;
       
   142         r.isWebSocket(true);
       
   143         r.setSystemHeader(HEADER_UPGRADE, "websocket");
       
   144         r.setSystemHeader(HEADER_CONNECTION, "Upgrade");
       
   145         r.setProxy(proxy);
       
   146     }
       
   147 
       
   148     private static Collection<String> createRequestSubprotocols(
       
   149             Collection<String> subprotocols)
       
   150     {
       
   151         LinkedHashSet<String> sp = new LinkedHashSet<>(subprotocols.size(), 1);
       
   152         for (String s : subprotocols) {
       
   153             if (s.trim().isEmpty() || !isValidName(s)) {
       
   154                 throw illegal("Bad subprotocol syntax: " + s);
       
   155             }
       
   156             if (!sp.add(s)) {
       
   157                 throw illegal("Duplicating subprotocol: " + s);
       
   158             }
       
   159         }
       
   160         return Collections.unmodifiableCollection(sp);
       
   161     }
       
   162 
       
   163     /*
       
   164      * Checks the given URI for being a WebSocket URI and translates it into a
       
   165      * target HTTP URI for the Opening Handshake.
       
   166      *
       
   167      * https://tools.ietf.org/html/rfc6455#section-3
       
   168      */
       
   169     static URI createRequestURI(URI uri) {
       
   170         String s = uri.getScheme();
       
   171         assert "ws".equalsIgnoreCase(s) || "wss".equalsIgnoreCase(s);
       
   172         String scheme = "ws".equalsIgnoreCase(s) ? "http" : "https";
       
   173         try {
       
   174             return new URI(scheme,
       
   175                            uri.getUserInfo(),
       
   176                            uri.getHost(),
       
   177                            uri.getPort(),
       
   178                            uri.getPath(),
       
   179                            uri.getQuery(),
       
   180                            null); // No fragment
       
   181         } catch (URISyntaxException e) {
       
   182             // Shouldn't happen: URI invariant
       
   183             throw new InternalError(e);
       
   184         }
       
   185     }
       
   186 
       
   187     public CompletableFuture<Result> send() {
       
   188         PrivilegedAction<CompletableFuture<Result>> pa = () ->
       
   189                 client.sendAsync(this.request, BodyHandler.discard())
       
   190                       .thenCompose(this::resultFrom);
       
   191         return AccessController.doPrivileged(pa);
       
   192     }
       
   193 
       
   194     /*
       
   195      * The result of the opening handshake.
       
   196      */
       
   197     static final class Result {
       
   198 
       
   199         final String subprotocol;
       
   200         final TransportFactory transport;
       
   201 
       
   202         private Result(String subprotocol, TransportFactory transport) {
       
   203             this.subprotocol = subprotocol;
       
   204             this.transport = transport;
       
   205         }
       
   206     }
       
   207 
       
   208     private CompletableFuture<Result> resultFrom(HttpResponse<?> response) {
       
   209         // Do we need a special treatment for SSLHandshakeException?
       
   210         // Namely, invoking
       
   211         //
       
   212         //     Listener.onClose(StatusCodes.TLS_HANDSHAKE_FAILURE, "")
       
   213         //
       
   214         // See https://tools.ietf.org/html/rfc6455#section-7.4.1
       
   215         Result result = null;
       
   216         Exception exception = null;
       
   217         try {
       
   218             result = handleResponse(response);
       
   219         } catch (IOException e) {
       
   220             exception = e;
       
   221         } catch (Exception e) {
       
   222             exception = new WebSocketHandshakeException(response).initCause(e);
       
   223         }
       
   224         if (exception == null) {
       
   225             return MinimalFuture.completedFuture(result);
       
   226         }
       
   227         try {
       
   228             ((RawChannel.Provider) response).rawChannel().close();
       
   229         } catch (IOException e) {
       
   230             exception.addSuppressed(e);
       
   231         }
       
   232         return MinimalFuture.failedFuture(exception);
       
   233     }
       
   234 
       
   235     private Result handleResponse(HttpResponse<?> response) throws IOException {
       
   236         // By this point all redirects, authentications, etc. (if any) MUST have
       
   237         // been done by the HttpClient used by the WebSocket; so only 101 is
       
   238         // expected
       
   239         int c = response.statusCode();
       
   240         if (c != 101) {
       
   241             throw checkFailed("Unexpected HTTP response status code " + c);
       
   242         }
       
   243         HttpHeaders headers = response.headers();
       
   244         String upgrade = requireSingle(headers, HEADER_UPGRADE);
       
   245         if (!upgrade.equalsIgnoreCase("websocket")) {
       
   246             throw checkFailed("Bad response field: " + HEADER_UPGRADE);
       
   247         }
       
   248         String connection = requireSingle(headers, HEADER_CONNECTION);
       
   249         if (!connection.equalsIgnoreCase("Upgrade")) {
       
   250             throw checkFailed("Bad response field: " + HEADER_CONNECTION);
       
   251         }
       
   252         Optional<String> version = requireAtMostOne(headers, HEADER_VERSION);
       
   253         if (version.isPresent() && !version.get().equals(VERSION)) {
       
   254             throw checkFailed("Bad response field: " + HEADER_VERSION);
       
   255         }
       
   256         requireAbsent(headers, HEADER_EXTENSIONS);
       
   257         String x = this.nonce + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
       
   258         this.sha1.update(x.getBytes(StandardCharsets.ISO_8859_1));
       
   259         String expected = Base64.getEncoder().encodeToString(this.sha1.digest());
       
   260         String actual = requireSingle(headers, HEADER_ACCEPT);
       
   261         if (!actual.trim().equals(expected)) {
       
   262             throw checkFailed("Bad " + HEADER_ACCEPT);
       
   263         }
       
   264         String subprotocol = checkAndReturnSubprotocol(headers);
       
   265         RawChannel channel = ((RawChannel.Provider) response).rawChannel();
       
   266         return new Result(subprotocol, new TransportFactoryImpl(channel));
       
   267     }
       
   268 
       
   269     private String checkAndReturnSubprotocol(HttpHeaders responseHeaders)
       
   270             throws CheckFailedException
       
   271     {
       
   272         Optional<String> opt = responseHeaders.firstValue(HEADER_PROTOCOL);
       
   273         if (!opt.isPresent()) {
       
   274             // If there is no such header in the response, then the server
       
   275             // doesn't want to use any subprotocol
       
   276             return "";
       
   277         }
       
   278         String s = requireSingle(responseHeaders, HEADER_PROTOCOL);
       
   279         // An empty string as a subprotocol's name is not allowed by the spec
       
   280         // and the check below will detect such responses too
       
   281         if (this.subprotocols.contains(s)) {
       
   282             return s;
       
   283         } else {
       
   284             throw checkFailed("Unexpected subprotocol: " + s);
       
   285         }
       
   286     }
       
   287 
       
   288     private static void requireAbsent(HttpHeaders responseHeaders,
       
   289                                       String headerName)
       
   290     {
       
   291         List<String> values = responseHeaders.allValues(headerName);
       
   292         if (!values.isEmpty()) {
       
   293             throw checkFailed(format("Response field '%s' present: %s",
       
   294                                      headerName,
       
   295                                      stringOf(values)));
       
   296         }
       
   297     }
       
   298 
       
   299     private static Optional<String> requireAtMostOne(HttpHeaders responseHeaders,
       
   300                                                      String headerName)
       
   301     {
       
   302         List<String> values = responseHeaders.allValues(headerName);
       
   303         if (values.size() > 1) {
       
   304             throw checkFailed(format("Response field '%s' multivalued: %s",
       
   305                                      headerName,
       
   306                                      stringOf(values)));
       
   307         }
       
   308         return values.stream().findFirst();
       
   309     }
       
   310 
       
   311     private static String requireSingle(HttpHeaders responseHeaders,
       
   312                                         String headerName)
       
   313     {
       
   314         List<String> values = responseHeaders.allValues(headerName);
       
   315         if (values.isEmpty()) {
       
   316             throw checkFailed("Response field missing: " + headerName);
       
   317         } else if (values.size() > 1) {
       
   318             throw checkFailed(format("Response field '%s' multivalued: %s",
       
   319                                      headerName,
       
   320                                      stringOf(values)));
       
   321         }
       
   322         return values.get(0);
       
   323     }
       
   324 
       
   325     private static String createNonce() {
       
   326         byte[] bytes = new byte[16];
       
   327         OpeningHandshake.random.nextBytes(bytes);
       
   328         return Base64.getEncoder().encodeToString(bytes);
       
   329     }
       
   330 
       
   331     private static CheckFailedException checkFailed(String message) {
       
   332         throw new CheckFailedException(message);
       
   333     }
       
   334 
       
   335     private static URI checkURI(URI uri) {
       
   336         String scheme = uri.getScheme();
       
   337         if (!("ws".equalsIgnoreCase(scheme) || "wss".equalsIgnoreCase(scheme)))
       
   338             throw illegal("invalid URI scheme: " + scheme);
       
   339         if (uri.getHost() == null)
       
   340             throw illegal("URI must contain a host: " + uri);
       
   341         if (uri.getFragment() != null)
       
   342             throw illegal("URI must not contain a fragment: " + uri);
       
   343         return uri;
       
   344     }
       
   345 
       
   346     private static IllegalArgumentException illegal(String message) {
       
   347         return new IllegalArgumentException(message);
       
   348     }
       
   349 
       
   350     /**
       
   351      * Returns the proxy for the given URI when sent through the given client,
       
   352      * or {@code null} if none is required or applicable.
       
   353      */
       
   354     private static Proxy proxyFor(Optional<ProxySelector> selector, URI uri) {
       
   355         if (!selector.isPresent()) {
       
   356             return null;
       
   357         }
       
   358         URI requestURI = createRequestURI(uri); // Based on the HTTP scheme
       
   359         List<Proxy> pl = selector.get().select(requestURI);
       
   360         if (pl.isEmpty()) {
       
   361             return null;
       
   362         }
       
   363         Proxy proxy = pl.get(0);
       
   364         if (proxy.type() != Proxy.Type.HTTP) {
       
   365             return null;
       
   366         }
       
   367         return proxy;
       
   368     }
       
   369 
       
   370     /**
       
   371      * Performs the necessary security permissions checks to connect ( possibly
       
   372      * through a proxy ) to the builders WebSocket URI.
       
   373      *
       
   374      * @throws SecurityException if the security manager denies access
       
   375      */
       
   376     static void checkPermissions(BuilderImpl b, Proxy proxy) {
       
   377         SecurityManager sm = System.getSecurityManager();
       
   378         if (sm == null) {
       
   379             return;
       
   380         }
       
   381         Stream<String> headers = b.getHeaders().stream().map(p -> p.first).distinct();
       
   382         URLPermission perm1 = Utils.permissionForServer(b.getUri(), "", headers);
       
   383         sm.checkPermission(perm1);
       
   384         if (proxy == null) {
       
   385             return;
       
   386         }
       
   387         URLPermission perm2 = permissionForProxy((InetSocketAddress) proxy.address());
       
   388         if (perm2 != null) {
       
   389             sm.checkPermission(perm2);
       
   390         }
       
   391     }
       
   392 }