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