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