|
1 /* |
|
2 * Copyright (c) 2015, 2016, 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 package java.net.http; |
|
26 |
|
27 import java.net.URI; |
|
28 import java.net.URISyntaxException; |
|
29 import java.nio.charset.StandardCharsets; |
|
30 import java.security.MessageDigest; |
|
31 import java.security.NoSuchAlgorithmException; |
|
32 import java.security.SecureRandom; |
|
33 import java.util.Arrays; |
|
34 import java.util.Base64; |
|
35 import java.util.Collection; |
|
36 import java.util.List; |
|
37 import java.util.concurrent.CompletableFuture; |
|
38 import java.util.function.Predicate; |
|
39 import java.util.stream.Collectors; |
|
40 |
|
41 import static java.lang.String.format; |
|
42 import static java.lang.System.Logger.Level.TRACE; |
|
43 import static java.net.http.WSUtils.logger; |
|
44 import static java.net.http.WSUtils.webSocketSpecViolation; |
|
45 |
|
46 final class WSOpeningHandshake { |
|
47 |
|
48 private static final String HEADER_CONNECTION = "Connection"; |
|
49 private static final String HEADER_UPGRADE = "Upgrade"; |
|
50 private static final String HEADER_ACCEPT = "Sec-WebSocket-Accept"; |
|
51 private static final String HEADER_EXTENSIONS = "Sec-WebSocket-Extensions"; |
|
52 private static final String HEADER_KEY = "Sec-WebSocket-Key"; |
|
53 private static final String HEADER_PROTOCOL = "Sec-WebSocket-Protocol"; |
|
54 private static final String HEADER_VERSION = "Sec-WebSocket-Version"; |
|
55 private static final String VALUE_VERSION = "13"; // WebSocket's lucky number |
|
56 |
|
57 private static final SecureRandom srandom = new SecureRandom(); |
|
58 |
|
59 private final MessageDigest sha1; |
|
60 |
|
61 { |
|
62 try { |
|
63 sha1 = MessageDigest.getInstance("SHA-1"); |
|
64 } catch (NoSuchAlgorithmException e) { |
|
65 // Shouldn't happen: |
|
66 // SHA-1 must be available in every Java platform implementation |
|
67 throw new InternalError("Minimum platform requirements are not met", e); |
|
68 } |
|
69 } |
|
70 |
|
71 private final HttpRequest request; |
|
72 private final Collection<String> subprotocols; |
|
73 private final String nonce; |
|
74 |
|
75 WSOpeningHandshake(WSBuilder b) { |
|
76 URI httpURI = createHttpUri(b.getUri()); |
|
77 HttpRequest.Builder requestBuilder = b.getClient().request(httpURI); |
|
78 if (b.getTimeUnit() != null) { |
|
79 requestBuilder.timeout(b.getTimeUnit(), b.getTimeout()); |
|
80 } |
|
81 Collection<String> s = b.getSubprotocols(); |
|
82 if (!s.isEmpty()) { |
|
83 String p = s.stream().collect(Collectors.joining(", ")); |
|
84 requestBuilder.header(HEADER_PROTOCOL, p); |
|
85 } |
|
86 requestBuilder.header(HEADER_VERSION, VALUE_VERSION); |
|
87 this.nonce = createNonce(); |
|
88 requestBuilder.header(HEADER_KEY, this.nonce); |
|
89 this.request = requestBuilder.GET(); |
|
90 HttpRequestImpl r = (HttpRequestImpl) this.request; |
|
91 r.isWebSocket(true); |
|
92 r.setSystemHeader(HEADER_UPGRADE, "websocket"); |
|
93 r.setSystemHeader(HEADER_CONNECTION, "Upgrade"); |
|
94 this.subprotocols = s; |
|
95 } |
|
96 |
|
97 private URI createHttpUri(URI webSocketUri) { |
|
98 // FIXME: check permission for WebSocket URI and translate it into http/https permission |
|
99 logger.log(TRACE, "->createHttpUri(''{0}'')", webSocketUri); |
|
100 String httpScheme = webSocketUri.getScheme().equalsIgnoreCase("ws") |
|
101 ? "http" |
|
102 : "https"; |
|
103 try { |
|
104 URI uri = new URI(httpScheme, |
|
105 webSocketUri.getUserInfo(), |
|
106 webSocketUri.getHost(), |
|
107 webSocketUri.getPort(), |
|
108 webSocketUri.getPath(), |
|
109 webSocketUri.getQuery(), |
|
110 null); |
|
111 logger.log(TRACE, "<-createHttpUri: ''{0}''", uri); |
|
112 return uri; |
|
113 } catch (URISyntaxException e) { |
|
114 // Shouldn't happen: URI invariant |
|
115 throw new InternalError("Error translating WebSocket URI to HTTP URI", e); |
|
116 } |
|
117 } |
|
118 |
|
119 CompletableFuture<Result> performAsync() { |
|
120 // The whole dancing with thenCompose instead of thenApply is because |
|
121 // WebSocketHandshakeException is a checked exception |
|
122 return request.responseAsync() |
|
123 .thenCompose(response -> { |
|
124 try { |
|
125 Result result = handleResponse(response); |
|
126 return CompletableFuture.completedFuture(result); |
|
127 } catch (WebSocketHandshakeException e) { |
|
128 return CompletableFuture.failedFuture(e); |
|
129 } |
|
130 }); |
|
131 } |
|
132 |
|
133 private Result handleResponse(HttpResponse response) throws WebSocketHandshakeException { |
|
134 // By this point all redirects, authentications, etc. (if any) must have |
|
135 // been done by the httpClient used by the WebSocket; so only 101 is |
|
136 // expected |
|
137 int statusCode = response.statusCode(); |
|
138 if (statusCode != 101) { |
|
139 String m = webSocketSpecViolation("1.3.", |
|
140 "Unable to complete handshake; HTTP response status code " |
|
141 + statusCode |
|
142 ); |
|
143 throw new WebSocketHandshakeException(m, response); |
|
144 } |
|
145 HttpHeaders h = response.headers(); |
|
146 checkHeader(h, response, HEADER_UPGRADE, v -> v.equalsIgnoreCase("websocket")); |
|
147 checkHeader(h, response, HEADER_CONNECTION, v -> v.equalsIgnoreCase("Upgrade")); |
|
148 checkVersion(response, h); |
|
149 checkAccept(response, h); |
|
150 checkExtensions(response, h); |
|
151 String subprotocol = checkAndReturnSubprotocol(response, h); |
|
152 RawChannel channel = ((HttpResponseImpl) response).rawChannel(); |
|
153 return new Result(subprotocol, channel); |
|
154 } |
|
155 |
|
156 private void checkExtensions(HttpResponse response, HttpHeaders headers) |
|
157 throws WebSocketHandshakeException { |
|
158 List<String> ext = headers.allValues(HEADER_EXTENSIONS); |
|
159 if (!ext.isEmpty()) { |
|
160 String m = webSocketSpecViolation("4.1.", |
|
161 "Server responded with extension(s) though none were requested " |
|
162 + Arrays.toString(ext.toArray()) |
|
163 ); |
|
164 throw new WebSocketHandshakeException(m, response); |
|
165 } |
|
166 } |
|
167 |
|
168 private String checkAndReturnSubprotocol(HttpResponse response, HttpHeaders headers) |
|
169 throws WebSocketHandshakeException { |
|
170 assert response.statusCode() == 101 : response.statusCode(); |
|
171 List<String> sp = headers.allValues(HEADER_PROTOCOL); |
|
172 int size = sp.size(); |
|
173 if (size == 0) { |
|
174 // In this case the subprotocol requested (if any) by the client |
|
175 // doesn't matter. If there is no such header in the response, then |
|
176 // the server doesn't want to use any subprotocol |
|
177 return null; |
|
178 } else if (size > 1) { |
|
179 // We don't know anything about toString implementation of this |
|
180 // list, so let's create an array |
|
181 String m = webSocketSpecViolation("4.1.", |
|
182 "Server responded with multiple subprotocols: " |
|
183 + Arrays.toString(sp.toArray()) |
|
184 ); |
|
185 throw new WebSocketHandshakeException(m, response); |
|
186 } else { |
|
187 String selectedSubprotocol = sp.get(0); |
|
188 if (this.subprotocols.contains(selectedSubprotocol)) { |
|
189 return selectedSubprotocol; |
|
190 } else { |
|
191 String m = webSocketSpecViolation("4.1.", |
|
192 format("Server responded with a subprotocol " + |
|
193 "not among those requested: '%s'", |
|
194 selectedSubprotocol)); |
|
195 throw new WebSocketHandshakeException(m, response); |
|
196 } |
|
197 } |
|
198 } |
|
199 |
|
200 private void checkAccept(HttpResponse response, HttpHeaders headers) |
|
201 throws WebSocketHandshakeException { |
|
202 assert response.statusCode() == 101 : response.statusCode(); |
|
203 String x = nonce + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; |
|
204 sha1.update(x.getBytes(StandardCharsets.ISO_8859_1)); |
|
205 String expected = Base64.getEncoder().encodeToString(sha1.digest()); |
|
206 checkHeader(headers, response, HEADER_ACCEPT, actual -> actual.trim().equals(expected)); |
|
207 } |
|
208 |
|
209 private void checkVersion(HttpResponse response, HttpHeaders headers) |
|
210 throws WebSocketHandshakeException { |
|
211 assert response.statusCode() == 101 : response.statusCode(); |
|
212 List<String> versions = headers.allValues(HEADER_VERSION); |
|
213 if (versions.isEmpty()) { // That's normal and expected |
|
214 return; |
|
215 } |
|
216 String m = webSocketSpecViolation("4.4.", |
|
217 "Server responded with version(s) " |
|
218 + Arrays.toString(versions.toArray())); |
|
219 throw new WebSocketHandshakeException(m, response); |
|
220 } |
|
221 |
|
222 // |
|
223 // Checks whether there's only one value for the header with the given name |
|
224 // and the value satisfies the predicate. |
|
225 // |
|
226 private static void checkHeader(HttpHeaders headers, |
|
227 HttpResponse response, |
|
228 String headerName, |
|
229 Predicate<? super String> valuePredicate) |
|
230 throws WebSocketHandshakeException { |
|
231 assert response.statusCode() == 101 : response.statusCode(); |
|
232 List<String> values = headers.allValues(headerName); |
|
233 if (values.isEmpty()) { |
|
234 String m = webSocketSpecViolation("4.1.", |
|
235 format("Server response field '%s' is missing", headerName) |
|
236 ); |
|
237 throw new WebSocketHandshakeException(m, response); |
|
238 } else if (values.size() > 1) { |
|
239 String m = webSocketSpecViolation("4.1.", |
|
240 format("Server response field '%s' has multiple values", headerName) |
|
241 ); |
|
242 throw new WebSocketHandshakeException(m, response); |
|
243 } |
|
244 if (!valuePredicate.test(values.get(0))) { |
|
245 String m = webSocketSpecViolation("4.1.", |
|
246 format("Server response field '%s' is incorrect", headerName) |
|
247 ); |
|
248 throw new WebSocketHandshakeException(m, response); |
|
249 } |
|
250 } |
|
251 |
|
252 private static String createNonce() { |
|
253 byte[] bytes = new byte[16]; |
|
254 srandom.nextBytes(bytes); |
|
255 return Base64.getEncoder().encodeToString(bytes); |
|
256 } |
|
257 |
|
258 static final class Result { |
|
259 |
|
260 final String subprotocol; |
|
261 final RawChannel channel; |
|
262 |
|
263 private Result(String subprotocol, RawChannel channel) { |
|
264 this.subprotocol = subprotocol; |
|
265 this.channel = channel; |
|
266 } |
|
267 } |
|
268 } |