1 /*
   2  * Copyright (c) 2015, 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.  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.internal.common.MinimalFuture;
  29 
  30 import java.io.IOException;
  31 import java.net.InetSocketAddress;
  32 import java.net.Proxy;
  33 import java.net.ProxySelector;
  34 import java.net.URI;
  35 import java.net.URISyntaxException;
  36 import jdk.incubator.http.HttpClient;
  37 import jdk.incubator.http.HttpClient.Version;
  38 import jdk.incubator.http.HttpHeaders;
  39 import jdk.incubator.http.HttpRequest;
  40 import jdk.incubator.http.HttpResponse;
  41 import jdk.incubator.http.HttpResponse.BodyHandler;
  42 import jdk.incubator.http.WebSocketHandshakeException;
  43 import jdk.incubator.http.internal.common.Pair;
  44 import jdk.incubator.http.internal.common.Utils;
  45 
  46 import java.net.URLPermission;
  47 import java.nio.charset.StandardCharsets;
  48 import java.security.AccessController;
  49 import java.security.MessageDigest;
  50 import java.security.NoSuchAlgorithmException;
  51 import java.security.PrivilegedAction;
  52 import java.security.SecureRandom;
  53 import java.time.Duration;
  54 import java.util.Base64;
  55 import java.util.Collection;
  56 import java.util.Collections;
  57 import java.util.LinkedHashSet;
  58 import java.util.List;
  59 import java.util.Optional;
  60 import java.util.Set;
  61 import java.util.TreeSet;
  62 import java.util.concurrent.CompletableFuture;
  63 import java.util.stream.Collectors;
  64 import java.util.stream.Stream;
  65 
  66 import static java.lang.String.format;
  67 import static jdk.incubator.http.internal.common.Utils.isValidName;
  68 import static jdk.incubator.http.internal.common.Utils.permissionForProxy;
  69 import static jdk.incubator.http.internal.common.Utils.stringOf;
  70 
  71 public class OpeningHandshake {
  72 
  73     private static final String HEADER_CONNECTION = "Connection";
  74     private static final String HEADER_UPGRADE    = "Upgrade";
  75     private static final String HEADER_ACCEPT     = "Sec-WebSocket-Accept";
  76     private static final String HEADER_EXTENSIONS = "Sec-WebSocket-Extensions";
  77     private static final String HEADER_KEY        = "Sec-WebSocket-Key";
  78     private static final String HEADER_PROTOCOL   = "Sec-WebSocket-Protocol";
  79     private static final String HEADER_VERSION    = "Sec-WebSocket-Version";
  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, "13"); // WebSocket's lucky number
 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.<Void>discard(null))
 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 TransportSupplier transport;
 201 
 202         private Result(String subprotocol, TransportSupplier 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         requireAbsent(headers, HEADER_VERSION);
 253         requireAbsent(headers, HEADER_EXTENSIONS);
 254         String x = this.nonce + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
 255         this.sha1.update(x.getBytes(StandardCharsets.ISO_8859_1));
 256         String expected = Base64.getEncoder().encodeToString(this.sha1.digest());
 257         String actual = requireSingle(headers, HEADER_ACCEPT);
 258         if (!actual.trim().equals(expected)) {
 259             throw checkFailed("Bad " + HEADER_ACCEPT);
 260         }
 261         String subprotocol = checkAndReturnSubprotocol(headers);
 262         RawChannel channel = ((RawChannel.Provider) response).rawChannel();
 263         return new Result(subprotocol, new TransportSupplier(channel));
 264     }
 265 
 266     private String checkAndReturnSubprotocol(HttpHeaders responseHeaders)
 267             throws CheckFailedException
 268     {
 269         Optional<String> opt = responseHeaders.firstValue(HEADER_PROTOCOL);
 270         if (!opt.isPresent()) {
 271             // If there is no such header in the response, then the server
 272             // doesn't want to use any subprotocol
 273             return "";
 274         }
 275         String s = requireSingle(responseHeaders, HEADER_PROTOCOL);
 276         // An empty string as a subprotocol's name is not allowed by the spec
 277         // and the check below will detect such responses too
 278         if (this.subprotocols.contains(s)) {
 279             return s;
 280         } else {
 281             throw checkFailed("Unexpected subprotocol: " + s);
 282         }
 283     }
 284 
 285     private static void requireAbsent(HttpHeaders responseHeaders,
 286                                       String headerName)
 287     {
 288         List<String> values = responseHeaders.allValues(headerName);
 289         if (!values.isEmpty()) {
 290             throw checkFailed(format("Response field '%s' present: %s",
 291                                      headerName,
 292                                      stringOf(values)));
 293         }
 294     }
 295 
 296     private static String requireSingle(HttpHeaders responseHeaders,
 297                                         String headerName)
 298     {
 299         List<String> values = responseHeaders.allValues(headerName);
 300         if (values.isEmpty()) {
 301             throw checkFailed("Response field missing: " + headerName);
 302         } else if (values.size() > 1) {
 303             throw checkFailed(format("Response field '%s' multivalued: %s",
 304                                      headerName,
 305                                      stringOf(values)));
 306         }
 307         return values.get(0);
 308     }
 309 
 310     private static String createNonce() {
 311         byte[] bytes = new byte[16];
 312         OpeningHandshake.random.nextBytes(bytes);
 313         return Base64.getEncoder().encodeToString(bytes);
 314     }
 315 
 316     private static CheckFailedException checkFailed(String message) {
 317         throw new CheckFailedException(message);
 318     }
 319 
 320     private static URI checkURI(URI uri) {
 321         String scheme = uri.getScheme();
 322         if (!("ws".equalsIgnoreCase(scheme) || "wss".equalsIgnoreCase(scheme)))
 323             throw illegal("invalid URI scheme: " + scheme);
 324         if (uri.getHost() == null)
 325             throw illegal("URI must contain a host: " + uri);
 326         if (uri.getFragment() != null)
 327             throw illegal("URI must not contain a fragment: " + uri);
 328         return uri;
 329     }
 330 
 331     private static IllegalArgumentException illegal(String message) {
 332         return new IllegalArgumentException(message);
 333     }
 334 
 335     /**
 336      * Returns the proxy for the given URI when sent through the given client,
 337      * or {@code null} if none is required or applicable.
 338      */
 339     private static Proxy proxyFor(Optional<ProxySelector> selector, URI uri) {
 340         if (!selector.isPresent()) {
 341             return null;
 342         }
 343         URI requestURI = createRequestURI(uri); // Based on the HTTP scheme
 344         List<Proxy> pl = selector.get().select(requestURI);
 345         if (pl.isEmpty()) {
 346             return null;
 347         }
 348         Proxy proxy = pl.get(0);
 349         if (proxy.type() != Proxy.Type.HTTP) {
 350             return null;
 351         }
 352         return proxy;
 353     }
 354 
 355     /**
 356      * Performs the necessary security permissions checks to connect ( possibly
 357      * through a proxy ) to the builders WebSocket URI.
 358      *
 359      * @throws SecurityException if the security manager denies access
 360      */
 361     static void checkPermissions(BuilderImpl b, Proxy proxy) {
 362         SecurityManager sm = System.getSecurityManager();
 363         if (sm == null) {
 364             return;
 365         }
 366         Stream<String> headers = b.getHeaders().stream().map(p -> p.first).distinct();
 367         URLPermission perm1 = Utils.permissionForServer(b.getUri(), "", headers);
 368         sm.checkPermission(perm1);
 369         if (proxy == null) {
 370             return;
 371         }
 372         URLPermission perm2 = permissionForProxy((InetSocketAddress) proxy.address());
 373         if (perm2 != null) {
 374             sm.checkPermission(perm2);
 375         }
 376     }
 377 }