author | dfuchs |
Tue, 01 Oct 2019 12:10:33 +0100 | |
changeset 58423 | 54de0c861d32 |
parent 54579 | 270557b396eb |
permissions | -rw-r--r-- |
49765 | 1 |
/* |
53350
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
2 |
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. |
49765 | 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 |
|
52387 | 7 |
* published by the Free Software Foundation. |
49765 | 8 |
* |
9 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
10 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
11 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
12 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
13 |
* accompanied this code). |
|
14 |
* |
|
15 |
* You should have received a copy of the GNU General Public License version |
|
16 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
17 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
18 |
* |
|
19 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
20 |
* or visit www.oracle.com if you need additional information or have any |
|
21 |
* questions. |
|
22 |
*/ |
|
23 |
||
24 |
import com.sun.net.httpserver.BasicAuthenticator; |
|
25 |
import com.sun.net.httpserver.HttpServer; |
|
26 |
import com.sun.net.httpserver.HttpsConfigurator; |
|
27 |
import com.sun.net.httpserver.HttpsParameters; |
|
28 |
import com.sun.net.httpserver.HttpsServer; |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
29 |
|
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
30 |
import java.io.Closeable; |
49765 | 31 |
import java.io.IOException; |
32 |
import java.io.InputStream; |
|
33 |
import java.io.OutputStream; |
|
34 |
import java.io.OutputStreamWriter; |
|
35 |
import java.io.PrintWriter; |
|
36 |
import java.io.Writer; |
|
37 |
import java.math.BigInteger; |
|
38 |
import java.net.Authenticator; |
|
39 |
import java.net.HttpURLConnection; |
|
40 |
import java.net.InetAddress; |
|
41 |
import java.net.InetSocketAddress; |
|
42 |
import java.net.MalformedURLException; |
|
43 |
import java.net.PasswordAuthentication; |
|
44 |
import java.net.ServerSocket; |
|
45 |
import java.net.Socket; |
|
53350
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
46 |
import java.net.StandardSocketOptions; |
49765 | 47 |
import java.net.URI; |
48 |
import java.net.URISyntaxException; |
|
49 |
import java.net.URL; |
|
50 |
import java.nio.charset.StandardCharsets; |
|
51 |
import java.security.MessageDigest; |
|
52 |
import java.security.NoSuchAlgorithmException; |
|
53 |
import java.time.Instant; |
|
54 |
import java.util.ArrayList; |
|
55 |
import java.util.Arrays; |
|
56 |
import java.util.Base64; |
|
57 |
import java.util.List; |
|
58 |
import java.util.Locale; |
|
59 |
import java.util.Objects; |
|
60 |
import java.util.Optional; |
|
61 |
import java.util.Random; |
|
62 |
import java.util.StringTokenizer; |
|
63 |
import java.util.concurrent.CompletableFuture; |
|
64 |
import java.util.concurrent.CopyOnWriteArrayList; |
|
65 |
import java.util.concurrent.atomic.AtomicInteger; |
|
66 |
import java.util.stream.Collectors; |
|
67 |
import java.util.stream.Stream; |
|
68 |
import javax.net.ssl.SSLContext; |
|
69 |
import sun.net.www.HeaderParser; |
|
70 |
import java.net.http.HttpClient.Version; |
|
71 |
||
72 |
/** |
|
73 |
* A simple HTTP server that supports Basic or Digest authentication. |
|
74 |
* By default this server will echo back whatever is present |
|
75 |
* in the request body. Note that the Digest authentication is |
|
76 |
* a test implementation implemented only for tests purposes. |
|
77 |
* @author danielfuchs |
|
78 |
*/ |
|
79 |
public abstract class DigestEchoServer implements HttpServerAdapters { |
|
80 |
||
81 |
public static final boolean DEBUG = |
|
82 |
Boolean.parseBoolean(System.getProperty("test.debug", "false")); |
|
53350
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
83 |
public static final boolean NO_LINGER = |
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
84 |
Boolean.parseBoolean(System.getProperty("test.nolinger", "false")); |
54579
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
85 |
public static final boolean TUNNEL_REQUIRES_HOST = |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
86 |
Boolean.parseBoolean(System.getProperty("test.requiresHost", "false")); |
49765 | 87 |
public enum HttpAuthType { |
88 |
SERVER, PROXY, SERVER307, PROXY305 |
|
89 |
/* add PROXY_AND_SERVER and SERVER_PROXY_NONE */ |
|
90 |
}; |
|
91 |
public enum HttpAuthSchemeType { NONE, BASICSERVER, BASIC, DIGEST }; |
|
92 |
public static final HttpAuthType DEFAULT_HTTP_AUTH_TYPE = HttpAuthType.SERVER; |
|
93 |
public static final String DEFAULT_PROTOCOL_TYPE = "https"; |
|
94 |
public static final HttpAuthSchemeType DEFAULT_SCHEME_TYPE = HttpAuthSchemeType.DIGEST; |
|
95 |
||
96 |
public static class HttpTestAuthenticator extends Authenticator { |
|
97 |
private final String realm; |
|
98 |
private final String username; |
|
99 |
// Used to prevent incrementation of 'count' when calling the |
|
100 |
// authenticator from the server side. |
|
101 |
private final ThreadLocal<Boolean> skipCount = new ThreadLocal<>(); |
|
102 |
// count will be incremented every time getPasswordAuthentication() |
|
103 |
// is called from the client side. |
|
104 |
final AtomicInteger count = new AtomicInteger(); |
|
105 |
||
106 |
public HttpTestAuthenticator(String realm, String username) { |
|
107 |
this.realm = realm; |
|
108 |
this.username = username; |
|
109 |
} |
|
110 |
@Override |
|
111 |
protected PasswordAuthentication getPasswordAuthentication() { |
|
112 |
if (skipCount.get() == null || skipCount.get().booleanValue() == false) { |
|
113 |
System.out.println("Authenticator called: " + count.incrementAndGet()); |
|
114 |
} |
|
115 |
return new PasswordAuthentication(getUserName(), |
|
116 |
new char[] {'d','e','n', 't'}); |
|
117 |
} |
|
118 |
// Called by the server side to get the password of the user |
|
119 |
// being authentified. |
|
120 |
public final char[] getPassword(String user) { |
|
121 |
if (user.equals(username)) { |
|
122 |
skipCount.set(Boolean.TRUE); |
|
123 |
try { |
|
124 |
return getPasswordAuthentication().getPassword(); |
|
125 |
} finally { |
|
126 |
skipCount.set(Boolean.FALSE); |
|
127 |
} |
|
128 |
} |
|
129 |
throw new SecurityException("User unknown: " + user); |
|
130 |
} |
|
131 |
public final String getUserName() { |
|
132 |
return username; |
|
133 |
} |
|
134 |
public final String getRealm() { |
|
135 |
return realm; |
|
136 |
} |
|
137 |
} |
|
138 |
||
139 |
public static final HttpTestAuthenticator AUTHENTICATOR; |
|
140 |
static { |
|
141 |
AUTHENTICATOR = new HttpTestAuthenticator("earth", "arthur"); |
|
142 |
} |
|
143 |
||
144 |
||
145 |
final HttpTestServer serverImpl; // this server endpoint |
|
146 |
final DigestEchoServer redirect; // the target server where to redirect 3xx |
|
147 |
final HttpTestHandler delegate; // unused |
|
148 |
final String key; |
|
149 |
||
150 |
DigestEchoServer(String key, |
|
151 |
HttpTestServer server, |
|
152 |
DigestEchoServer target, |
|
153 |
HttpTestHandler delegate) { |
|
154 |
this.key = key; |
|
155 |
this.serverImpl = server; |
|
156 |
this.redirect = target; |
|
157 |
this.delegate = delegate; |
|
158 |
} |
|
159 |
||
160 |
public static void main(String[] args) |
|
161 |
throws IOException { |
|
162 |
||
163 |
DigestEchoServer server = create(Version.HTTP_1_1, |
|
164 |
DEFAULT_PROTOCOL_TYPE, |
|
165 |
DEFAULT_HTTP_AUTH_TYPE, |
|
166 |
AUTHENTICATOR, |
|
167 |
DEFAULT_SCHEME_TYPE); |
|
168 |
try { |
|
169 |
System.out.println("Server created at " + server.getAddress()); |
|
170 |
System.out.println("Strike <Return> to exit"); |
|
171 |
System.in.read(); |
|
172 |
} finally { |
|
173 |
System.out.println("stopping server"); |
|
174 |
server.stop(); |
|
175 |
} |
|
176 |
} |
|
177 |
||
50681 | 178 |
private static String toString(HttpTestRequestHeaders headers) { |
49765 | 179 |
return headers.entrySet().stream() |
180 |
.map((e) -> e.getKey() + ": " + e.getValue()) |
|
181 |
.collect(Collectors.joining("\n")); |
|
182 |
} |
|
183 |
||
184 |
public static DigestEchoServer create(Version version, |
|
185 |
String protocol, |
|
186 |
HttpAuthType authType, |
|
187 |
HttpAuthSchemeType schemeType) |
|
188 |
throws IOException { |
|
189 |
return create(version, protocol, authType, AUTHENTICATOR, schemeType); |
|
190 |
} |
|
191 |
||
192 |
public static DigestEchoServer create(Version version, |
|
193 |
String protocol, |
|
194 |
HttpAuthType authType, |
|
195 |
HttpTestAuthenticator auth, |
|
196 |
HttpAuthSchemeType schemeType) |
|
197 |
throws IOException { |
|
198 |
return create(version, protocol, authType, auth, schemeType, null); |
|
199 |
} |
|
200 |
||
201 |
public static DigestEchoServer create(Version version, |
|
202 |
String protocol, |
|
203 |
HttpAuthType authType, |
|
204 |
HttpTestAuthenticator auth, |
|
205 |
HttpAuthSchemeType schemeType, |
|
206 |
HttpTestHandler delegate) |
|
207 |
throws IOException { |
|
208 |
Objects.requireNonNull(authType); |
|
209 |
Objects.requireNonNull(auth); |
|
210 |
switch(authType) { |
|
211 |
// A server that performs Server Digest authentication. |
|
212 |
case SERVER: return createServer(version, protocol, authType, auth, |
|
213 |
schemeType, delegate, "/"); |
|
214 |
// A server that pretends to be a Proxy and performs |
|
215 |
// Proxy Digest authentication. If protocol is HTTPS, |
|
216 |
// then this will create a HttpsProxyTunnel that will |
|
217 |
// handle the CONNECT request for tunneling. |
|
218 |
case PROXY: return createProxy(version, protocol, authType, auth, |
|
219 |
schemeType, delegate, "/"); |
|
220 |
// A server that sends 307 redirect to a server that performs |
|
221 |
// Digest authentication. |
|
222 |
// Note: 301 doesn't work here because it transforms POST into GET. |
|
223 |
case SERVER307: return createServerAndRedirect(version, |
|
224 |
protocol, |
|
225 |
HttpAuthType.SERVER, |
|
226 |
auth, schemeType, |
|
227 |
delegate, 307); |
|
228 |
// A server that sends 305 redirect to a proxy that performs |
|
229 |
// Digest authentication. |
|
230 |
// Note: this is not correctly stubbed/implemented in this test. |
|
231 |
case PROXY305: return createServerAndRedirect(version, |
|
232 |
protocol, |
|
233 |
HttpAuthType.PROXY, |
|
234 |
auth, schemeType, |
|
235 |
delegate, 305); |
|
236 |
default: |
|
237 |
throw new InternalError("Unknown server type: " + authType); |
|
238 |
} |
|
239 |
} |
|
240 |
||
241 |
||
242 |
/** |
|
243 |
* The SocketBindableFactory ensures that the local port used by an HttpServer |
|
244 |
* or a proxy ServerSocket previously created by the current test/VM will not |
|
245 |
* get reused by a subsequent test in the same VM. |
|
246 |
* This is to avoid having the test client trying to reuse cached connections. |
|
247 |
*/ |
|
248 |
private static abstract class SocketBindableFactory<B> { |
|
249 |
private static final int MAX = 10; |
|
250 |
private static final CopyOnWriteArrayList<String> addresses = |
|
251 |
new CopyOnWriteArrayList<>(); |
|
252 |
protected B createInternal() throws IOException { |
|
253 |
final int max = addresses.size() + MAX; |
|
254 |
final List<B> toClose = new ArrayList<>(); |
|
255 |
try { |
|
256 |
for (int i = 1; i <= max; i++) { |
|
257 |
B bindable = createBindable(); |
|
258 |
InetSocketAddress address = getAddress(bindable); |
|
259 |
String key = "localhost:" + address.getPort(); |
|
260 |
if (addresses.addIfAbsent(key)) { |
|
261 |
System.out.println("Socket bound to: " + key |
|
262 |
+ " after " + i + " attempt(s)"); |
|
263 |
return bindable; |
|
264 |
} |
|
265 |
System.out.println("warning: address " + key |
|
266 |
+ " already used. Retrying bind."); |
|
267 |
// keep the port bound until we get a port that we haven't |
|
268 |
// used already |
|
269 |
toClose.add(bindable); |
|
270 |
} |
|
271 |
} finally { |
|
272 |
// if we had to retry, then close the socket we're not |
|
273 |
// going to use. |
|
274 |
for (B b : toClose) { |
|
275 |
try { close(b); } catch (Exception x) { /* ignore */ } |
|
276 |
} |
|
277 |
} |
|
278 |
throw new IOException("Couldn't bind socket after " + max + " attempts: " |
|
279 |
+ "addresses used before: " + addresses); |
|
280 |
} |
|
281 |
||
282 |
protected abstract B createBindable() throws IOException; |
|
283 |
||
284 |
protected abstract InetSocketAddress getAddress(B bindable); |
|
285 |
||
286 |
protected abstract void close(B bindable) throws IOException; |
|
287 |
} |
|
288 |
||
289 |
/* |
|
290 |
* Used to create ServerSocket for a proxy. |
|
291 |
*/ |
|
292 |
private static final class ServerSocketFactory |
|
293 |
extends SocketBindableFactory<ServerSocket> { |
|
294 |
private static final ServerSocketFactory instance = new ServerSocketFactory(); |
|
295 |
||
296 |
static ServerSocket create() throws IOException { |
|
297 |
return instance.createInternal(); |
|
298 |
} |
|
299 |
||
300 |
@Override |
|
301 |
protected ServerSocket createBindable() throws IOException { |
|
302 |
ServerSocket ss = new ServerSocket(); |
|
303 |
ss.setReuseAddress(false); |
|
304 |
ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); |
|
305 |
return ss; |
|
306 |
} |
|
307 |
||
308 |
@Override |
|
309 |
protected InetSocketAddress getAddress(ServerSocket socket) { |
|
310 |
return new InetSocketAddress(socket.getInetAddress(), socket.getLocalPort()); |
|
311 |
} |
|
312 |
||
313 |
@Override |
|
314 |
protected void close(ServerSocket socket) throws IOException { |
|
315 |
socket.close(); |
|
316 |
} |
|
317 |
} |
|
318 |
||
319 |
/* |
|
320 |
* Used to create HttpServer |
|
321 |
*/ |
|
322 |
private static abstract class H1ServerFactory<S extends HttpServer> |
|
323 |
extends SocketBindableFactory<S> { |
|
324 |
@Override |
|
325 |
protected S createBindable() throws IOException { |
|
326 |
S server = newHttpServer(); |
|
327 |
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); |
|
328 |
return server; |
|
329 |
} |
|
330 |
||
331 |
@Override |
|
332 |
protected InetSocketAddress getAddress(S server) { |
|
333 |
return server.getAddress(); |
|
334 |
} |
|
335 |
||
336 |
@Override |
|
337 |
protected void close(S server) throws IOException { |
|
338 |
server.stop(1); |
|
339 |
} |
|
340 |
||
341 |
/* |
|
342 |
* Returns a HttpServer or a HttpsServer in different subclasses. |
|
343 |
*/ |
|
344 |
protected abstract S newHttpServer() throws IOException; |
|
345 |
} |
|
346 |
||
347 |
/* |
|
348 |
* Used to create Http2TestServer |
|
349 |
*/ |
|
350 |
private static abstract class H2ServerFactory<S extends Http2TestServer> |
|
351 |
extends SocketBindableFactory<S> { |
|
352 |
@Override |
|
353 |
protected S createBindable() throws IOException { |
|
354 |
final S server; |
|
355 |
try { |
|
356 |
server = newHttpServer(); |
|
357 |
} catch (IOException io) { |
|
358 |
throw io; |
|
359 |
} catch (Exception x) { |
|
360 |
throw new IOException(x); |
|
361 |
} |
|
362 |
return server; |
|
363 |
} |
|
364 |
||
365 |
@Override |
|
366 |
protected InetSocketAddress getAddress(S server) { |
|
367 |
return server.getAddress(); |
|
368 |
} |
|
369 |
||
370 |
@Override |
|
371 |
protected void close(S server) throws IOException { |
|
372 |
server.stop(); |
|
373 |
} |
|
374 |
||
375 |
/* |
|
376 |
* Returns a HttpServer or a HttpsServer in different subclasses. |
|
377 |
*/ |
|
378 |
protected abstract S newHttpServer() throws Exception; |
|
379 |
} |
|
380 |
||
381 |
private static final class Http2ServerFactory extends H2ServerFactory<Http2TestServer> { |
|
382 |
private static final Http2ServerFactory instance = new Http2ServerFactory(); |
|
383 |
||
384 |
static Http2TestServer create() throws IOException { |
|
385 |
return instance.createInternal(); |
|
386 |
} |
|
387 |
||
388 |
@Override |
|
389 |
protected Http2TestServer newHttpServer() throws Exception { |
|
390 |
return new Http2TestServer("localhost", false, 0); |
|
391 |
} |
|
392 |
} |
|
393 |
||
394 |
private static final class Https2ServerFactory extends H2ServerFactory<Http2TestServer> { |
|
395 |
private static final Https2ServerFactory instance = new Https2ServerFactory(); |
|
396 |
||
397 |
static Http2TestServer create() throws IOException { |
|
398 |
return instance.createInternal(); |
|
399 |
} |
|
400 |
||
401 |
@Override |
|
402 |
protected Http2TestServer newHttpServer() throws Exception { |
|
403 |
return new Http2TestServer("localhost", true, 0); |
|
404 |
} |
|
405 |
} |
|
406 |
||
407 |
private static final class Http1ServerFactory extends H1ServerFactory<HttpServer> { |
|
408 |
private static final Http1ServerFactory instance = new Http1ServerFactory(); |
|
409 |
||
410 |
static HttpServer create() throws IOException { |
|
411 |
return instance.createInternal(); |
|
412 |
} |
|
413 |
||
414 |
@Override |
|
415 |
protected HttpServer newHttpServer() throws IOException { |
|
416 |
return HttpServer.create(); |
|
417 |
} |
|
418 |
} |
|
419 |
||
420 |
private static final class Https1ServerFactory extends H1ServerFactory<HttpsServer> { |
|
421 |
private static final Https1ServerFactory instance = new Https1ServerFactory(); |
|
422 |
||
423 |
static HttpsServer create() throws IOException { |
|
424 |
return instance.createInternal(); |
|
425 |
} |
|
426 |
||
427 |
@Override |
|
428 |
protected HttpsServer newHttpServer() throws IOException { |
|
429 |
return HttpsServer.create(); |
|
430 |
} |
|
431 |
} |
|
432 |
||
433 |
static Http2TestServer createHttp2Server(String protocol) throws IOException { |
|
434 |
final Http2TestServer server; |
|
435 |
if ("http".equalsIgnoreCase(protocol)) { |
|
436 |
server = Http2ServerFactory.create(); |
|
437 |
} else if ("https".equalsIgnoreCase(protocol)) { |
|
438 |
server = Https2ServerFactory.create(); |
|
439 |
} else { |
|
440 |
throw new InternalError("unsupported protocol: " + protocol); |
|
441 |
} |
|
442 |
return server; |
|
443 |
} |
|
444 |
||
445 |
static HttpTestServer createHttpServer(Version version, String protocol) |
|
446 |
throws IOException |
|
447 |
{ |
|
448 |
switch(version) { |
|
449 |
case HTTP_1_1: |
|
450 |
return HttpTestServer.of(createHttp1Server(protocol)); |
|
451 |
case HTTP_2: |
|
452 |
return HttpTestServer.of(createHttp2Server(protocol)); |
|
453 |
default: |
|
454 |
throw new InternalError("Unexpected version: " + version); |
|
455 |
} |
|
456 |
} |
|
457 |
||
458 |
static HttpServer createHttp1Server(String protocol) throws IOException { |
|
459 |
final HttpServer server; |
|
460 |
if ("http".equalsIgnoreCase(protocol)) { |
|
461 |
server = Http1ServerFactory.create(); |
|
462 |
} else if ("https".equalsIgnoreCase(protocol)) { |
|
463 |
server = configure(Https1ServerFactory.create()); |
|
464 |
} else { |
|
465 |
throw new InternalError("unsupported protocol: " + protocol); |
|
466 |
} |
|
467 |
return server; |
|
468 |
} |
|
469 |
||
470 |
static HttpsServer configure(HttpsServer server) throws IOException { |
|
471 |
try { |
|
472 |
SSLContext ctx = SSLContext.getDefault(); |
|
473 |
server.setHttpsConfigurator(new Configurator(ctx)); |
|
474 |
} catch (NoSuchAlgorithmException ex) { |
|
475 |
throw new IOException(ex); |
|
476 |
} |
|
477 |
return server; |
|
478 |
} |
|
479 |
||
480 |
||
481 |
static void setContextAuthenticator(HttpTestContext ctxt, |
|
482 |
HttpTestAuthenticator auth) { |
|
483 |
final String realm = auth.getRealm(); |
|
484 |
com.sun.net.httpserver.Authenticator authenticator = |
|
485 |
new BasicAuthenticator(realm) { |
|
486 |
@Override |
|
487 |
public boolean checkCredentials(String username, String pwd) { |
|
488 |
return auth.getUserName().equals(username) |
|
489 |
&& new String(auth.getPassword(username)).equals(pwd); |
|
490 |
} |
|
491 |
}; |
|
492 |
ctxt.setAuthenticator(authenticator); |
|
493 |
} |
|
494 |
||
495 |
public static DigestEchoServer createServer(Version version, |
|
496 |
String protocol, |
|
497 |
HttpAuthType authType, |
|
498 |
HttpTestAuthenticator auth, |
|
499 |
HttpAuthSchemeType schemeType, |
|
500 |
HttpTestHandler delegate, |
|
501 |
String path) |
|
502 |
throws IOException { |
|
503 |
Objects.requireNonNull(authType); |
|
504 |
Objects.requireNonNull(auth); |
|
505 |
||
506 |
HttpTestServer impl = createHttpServer(version, protocol); |
|
507 |
String key = String.format("DigestEchoServer[PID=%s,PORT=%s]:%s:%s:%s:%s", |
|
508 |
ProcessHandle.current().pid(), |
|
509 |
impl.getAddress().getPort(), |
|
510 |
version, protocol, authType, schemeType); |
|
511 |
final DigestEchoServer server = new DigestEchoServerImpl(key, impl, null, delegate); |
|
512 |
final HttpTestHandler handler = |
|
513 |
server.createHandler(schemeType, auth, authType, false); |
|
514 |
HttpTestContext context = impl.addHandler(handler, path); |
|
515 |
server.configureAuthentication(context, schemeType, auth, authType); |
|
516 |
impl.start(); |
|
517 |
return server; |
|
518 |
} |
|
519 |
||
520 |
public static DigestEchoServer createProxy(Version version, |
|
521 |
String protocol, |
|
522 |
HttpAuthType authType, |
|
523 |
HttpTestAuthenticator auth, |
|
524 |
HttpAuthSchemeType schemeType, |
|
525 |
HttpTestHandler delegate, |
|
526 |
String path) |
|
527 |
throws IOException { |
|
528 |
Objects.requireNonNull(authType); |
|
529 |
Objects.requireNonNull(auth); |
|
530 |
||
531 |
if (version == Version.HTTP_2 && protocol.equalsIgnoreCase("http")) { |
|
532 |
System.out.println("WARNING: can't use HTTP/1.1 proxy with unsecure HTTP/2 server"); |
|
533 |
version = Version.HTTP_1_1; |
|
534 |
} |
|
535 |
HttpTestServer impl = createHttpServer(version, protocol); |
|
536 |
String key = String.format("DigestEchoServer[PID=%s,PORT=%s]:%s:%s:%s:%s", |
|
537 |
ProcessHandle.current().pid(), |
|
538 |
impl.getAddress().getPort(), |
|
539 |
version, protocol, authType, schemeType); |
|
540 |
final DigestEchoServer server = "https".equalsIgnoreCase(protocol) |
|
541 |
? new HttpsProxyTunnel(key, impl, null, delegate) |
|
542 |
: new DigestEchoServerImpl(key, impl, null, delegate); |
|
543 |
||
544 |
final HttpTestHandler hh = server.createHandler(HttpAuthSchemeType.NONE, |
|
545 |
null, HttpAuthType.SERVER, |
|
546 |
server instanceof HttpsProxyTunnel); |
|
547 |
HttpTestContext ctxt = impl.addHandler(hh, path); |
|
548 |
server.configureAuthentication(ctxt, schemeType, auth, authType); |
|
549 |
impl.start(); |
|
550 |
||
551 |
return server; |
|
552 |
} |
|
553 |
||
554 |
public static DigestEchoServer createServerAndRedirect( |
|
555 |
Version version, |
|
556 |
String protocol, |
|
557 |
HttpAuthType targetAuthType, |
|
558 |
HttpTestAuthenticator auth, |
|
559 |
HttpAuthSchemeType schemeType, |
|
560 |
HttpTestHandler targetDelegate, |
|
561 |
int code300) |
|
562 |
throws IOException { |
|
563 |
Objects.requireNonNull(targetAuthType); |
|
564 |
Objects.requireNonNull(auth); |
|
565 |
||
566 |
// The connection between client and proxy can only |
|
567 |
// be a plain connection: SSL connection to proxy |
|
568 |
// is not supported by our client connection. |
|
569 |
String targetProtocol = targetAuthType == HttpAuthType.PROXY |
|
570 |
? "http" |
|
571 |
: protocol; |
|
572 |
DigestEchoServer redirectTarget = |
|
573 |
(targetAuthType == HttpAuthType.PROXY) |
|
574 |
? createProxy(version, protocol, targetAuthType, |
|
575 |
auth, schemeType, targetDelegate, "/") |
|
576 |
: createServer(version, targetProtocol, targetAuthType, |
|
577 |
auth, schemeType, targetDelegate, "/"); |
|
578 |
HttpTestServer impl = createHttpServer(version, protocol); |
|
579 |
String key = String.format("RedirectingServer[PID=%s,PORT=%s]:%s:%s:%s:%s", |
|
580 |
ProcessHandle.current().pid(), |
|
581 |
impl.getAddress().getPort(), |
|
582 |
version, protocol, |
|
583 |
HttpAuthType.SERVER, code300) |
|
584 |
+ "->" + redirectTarget.key; |
|
585 |
final DigestEchoServer redirectingServer = |
|
586 |
new DigestEchoServerImpl(key, impl, redirectTarget, null); |
|
587 |
InetSocketAddress redirectAddr = redirectTarget.getAddress(); |
|
588 |
URL locationURL = url(targetProtocol, redirectAddr, "/"); |
|
589 |
final HttpTestHandler hh = redirectingServer.create300Handler(key, locationURL, |
|
590 |
HttpAuthType.SERVER, code300); |
|
591 |
impl.addHandler(hh,"/"); |
|
592 |
impl.start(); |
|
593 |
return redirectingServer; |
|
594 |
} |
|
595 |
||
596 |
public abstract InetSocketAddress getServerAddress(); |
|
597 |
public abstract InetSocketAddress getProxyAddress(); |
|
598 |
public abstract InetSocketAddress getAddress(); |
|
599 |
public abstract void stop(); |
|
600 |
public abstract Version getServerVersion(); |
|
601 |
||
602 |
private static class DigestEchoServerImpl extends DigestEchoServer { |
|
603 |
DigestEchoServerImpl(String key, |
|
604 |
HttpTestServer server, |
|
605 |
DigestEchoServer target, |
|
606 |
HttpTestHandler delegate) { |
|
607 |
super(key, Objects.requireNonNull(server), target, delegate); |
|
608 |
} |
|
609 |
||
610 |
public InetSocketAddress getAddress() { |
|
611 |
return new InetSocketAddress(InetAddress.getLoopbackAddress(), |
|
612 |
serverImpl.getAddress().getPort()); |
|
613 |
} |
|
614 |
||
615 |
public InetSocketAddress getServerAddress() { |
|
616 |
return new InetSocketAddress(InetAddress.getLoopbackAddress(), |
|
617 |
serverImpl.getAddress().getPort()); |
|
618 |
} |
|
619 |
||
620 |
public InetSocketAddress getProxyAddress() { |
|
621 |
return new InetSocketAddress(InetAddress.getLoopbackAddress(), |
|
622 |
serverImpl.getAddress().getPort()); |
|
623 |
} |
|
624 |
||
625 |
public Version getServerVersion() { |
|
626 |
return serverImpl.getVersion(); |
|
627 |
} |
|
628 |
||
629 |
public void stop() { |
|
630 |
serverImpl.stop(); |
|
631 |
if (redirect != null) { |
|
632 |
redirect.stop(); |
|
633 |
} |
|
634 |
} |
|
635 |
} |
|
636 |
||
637 |
protected void writeResponse(HttpTestExchange he) throws IOException { |
|
638 |
if (delegate == null) { |
|
639 |
he.sendResponseHeaders(HttpURLConnection.HTTP_OK, -1); |
|
640 |
he.getResponseBody().write(he.getRequestBody().readAllBytes()); |
|
641 |
} else { |
|
642 |
delegate.handle(he); |
|
643 |
} |
|
644 |
} |
|
645 |
||
646 |
private HttpTestHandler createHandler(HttpAuthSchemeType schemeType, |
|
647 |
HttpTestAuthenticator auth, |
|
648 |
HttpAuthType authType, |
|
649 |
boolean tunelled) { |
|
650 |
return new HttpNoAuthHandler(key, authType, tunelled); |
|
651 |
} |
|
652 |
||
653 |
void configureAuthentication(HttpTestContext ctxt, |
|
654 |
HttpAuthSchemeType schemeType, |
|
655 |
HttpTestAuthenticator auth, |
|
656 |
HttpAuthType authType) { |
|
657 |
switch(schemeType) { |
|
658 |
case DIGEST: |
|
659 |
// DIGEST authentication is handled by the handler. |
|
660 |
ctxt.addFilter(new HttpDigestFilter(key, auth, authType)); |
|
661 |
break; |
|
662 |
case BASIC: |
|
663 |
// BASIC authentication is handled by the filter. |
|
664 |
ctxt.addFilter(new HttpBasicFilter(key, auth, authType)); |
|
665 |
break; |
|
666 |
case BASICSERVER: |
|
667 |
switch(authType) { |
|
668 |
case PROXY: case PROXY305: |
|
669 |
// HttpServer can't support Proxy-type authentication |
|
670 |
// => we do as if BASIC had been specified, and we will |
|
671 |
// handle authentication in the handler. |
|
672 |
ctxt.addFilter(new HttpBasicFilter(key, auth, authType)); |
|
673 |
break; |
|
674 |
case SERVER: case SERVER307: |
|
675 |
if (ctxt.getVersion() == Version.HTTP_1_1) { |
|
676 |
// Basic authentication is handled by HttpServer |
|
677 |
// directly => the filter should not perform |
|
678 |
// authentication again. |
|
679 |
setContextAuthenticator(ctxt, auth); |
|
680 |
ctxt.addFilter(new HttpNoAuthFilter(key, authType)); |
|
681 |
} else { |
|
682 |
ctxt.addFilter(new HttpBasicFilter(key, auth, authType)); |
|
683 |
} |
|
684 |
break; |
|
685 |
default: |
|
686 |
throw new InternalError(key + ": Invalid combination scheme=" |
|
687 |
+ schemeType + " authType=" + authType); |
|
688 |
} |
|
689 |
case NONE: |
|
690 |
// No authentication at all. |
|
691 |
ctxt.addFilter(new HttpNoAuthFilter(key, authType)); |
|
692 |
break; |
|
693 |
default: |
|
694 |
throw new InternalError(key + ": No such scheme: " + schemeType); |
|
695 |
} |
|
696 |
} |
|
697 |
||
698 |
private HttpTestHandler create300Handler(String key, URL proxyURL, |
|
699 |
HttpAuthType type, int code300) |
|
700 |
throws MalformedURLException |
|
701 |
{ |
|
702 |
return new Http3xxHandler(key, proxyURL, type, code300); |
|
703 |
} |
|
704 |
||
705 |
// Abstract HTTP filter class. |
|
706 |
private abstract static class AbstractHttpFilter extends HttpTestFilter { |
|
707 |
||
708 |
final HttpAuthType authType; |
|
709 |
final String type; |
|
710 |
public AbstractHttpFilter(HttpAuthType authType, String type) { |
|
711 |
this.authType = authType; |
|
712 |
this.type = type; |
|
713 |
} |
|
714 |
||
715 |
String getLocation() { |
|
716 |
return "Location"; |
|
717 |
} |
|
718 |
String getAuthenticate() { |
|
719 |
return authType == HttpAuthType.PROXY |
|
720 |
? "Proxy-Authenticate" : "WWW-Authenticate"; |
|
721 |
} |
|
722 |
String getAuthorization() { |
|
723 |
return authType == HttpAuthType.PROXY |
|
724 |
? "Proxy-Authorization" : "Authorization"; |
|
725 |
} |
|
726 |
int getUnauthorizedCode() { |
|
727 |
return authType == HttpAuthType.PROXY |
|
728 |
? HttpURLConnection.HTTP_PROXY_AUTH |
|
729 |
: HttpURLConnection.HTTP_UNAUTHORIZED; |
|
730 |
} |
|
731 |
String getKeepAlive() { |
|
732 |
return "keep-alive"; |
|
733 |
} |
|
734 |
String getConnection() { |
|
735 |
return authType == HttpAuthType.PROXY |
|
736 |
? "Proxy-Connection" : "Connection"; |
|
737 |
} |
|
738 |
protected abstract boolean isAuthentified(HttpTestExchange he) throws IOException; |
|
739 |
protected abstract void requestAuthentication(HttpTestExchange he) throws IOException; |
|
740 |
protected void accept(HttpTestExchange he, HttpChain chain) throws IOException { |
|
741 |
chain.doFilter(he); |
|
742 |
} |
|
743 |
||
744 |
@Override |
|
745 |
public String description() { |
|
746 |
return "Filter for " + type; |
|
747 |
} |
|
748 |
@Override |
|
749 |
public void doFilter(HttpTestExchange he, HttpChain chain) throws IOException { |
|
750 |
try { |
|
751 |
System.out.println(type + ": Got " + he.getRequestMethod() |
|
752 |
+ ": " + he.getRequestURI() |
|
753 |
+ "\n" + DigestEchoServer.toString(he.getRequestHeaders())); |
|
754 |
||
755 |
// Assert only a single value for Expect. Not directly related |
|
756 |
// to digest authentication, but verifies good client behaviour. |
|
757 |
List<String> expectValues = he.getRequestHeaders().get("Expect"); |
|
758 |
if (expectValues != null && expectValues.size() > 1) { |
|
759 |
throw new IOException("Expect: " + expectValues); |
|
760 |
} |
|
761 |
||
762 |
if (!isAuthentified(he)) { |
|
763 |
try { |
|
764 |
requestAuthentication(he); |
|
765 |
he.sendResponseHeaders(getUnauthorizedCode(), -1); |
|
766 |
System.out.println(type |
|
767 |
+ ": Sent back " + getUnauthorizedCode()); |
|
768 |
} finally { |
|
769 |
he.close(); |
|
770 |
} |
|
771 |
} else { |
|
772 |
accept(he, chain); |
|
773 |
} |
|
774 |
} catch (RuntimeException | Error | IOException t) { |
|
775 |
System.err.println(type |
|
776 |
+ ": Unexpected exception while handling request: " + t); |
|
777 |
t.printStackTrace(System.err); |
|
778 |
he.close(); |
|
779 |
throw t; |
|
780 |
} |
|
781 |
} |
|
782 |
||
783 |
} |
|
784 |
||
785 |
// WARNING: This is not a full fledged implementation of DIGEST. |
|
786 |
// It does contain bugs and inaccuracy. |
|
787 |
final static class DigestResponse { |
|
788 |
final String realm; |
|
789 |
final String username; |
|
790 |
final String nonce; |
|
791 |
final String cnonce; |
|
792 |
final String nc; |
|
793 |
final String uri; |
|
794 |
final String algorithm; |
|
795 |
final String response; |
|
796 |
final String qop; |
|
797 |
final String opaque; |
|
798 |
||
799 |
public DigestResponse(String realm, String username, String nonce, |
|
800 |
String cnonce, String nc, String uri, |
|
801 |
String algorithm, String qop, String opaque, |
|
802 |
String response) { |
|
803 |
this.realm = realm; |
|
804 |
this.username = username; |
|
805 |
this.nonce = nonce; |
|
806 |
this.cnonce = cnonce; |
|
807 |
this.nc = nc; |
|
808 |
this.uri = uri; |
|
809 |
this.algorithm = algorithm; |
|
810 |
this.qop = qop; |
|
811 |
this.opaque = opaque; |
|
812 |
this.response = response; |
|
813 |
} |
|
814 |
||
815 |
String getAlgorithm(String defval) { |
|
816 |
return algorithm == null ? defval : algorithm; |
|
817 |
} |
|
818 |
String getQoP(String defval) { |
|
819 |
return qop == null ? defval : qop; |
|
820 |
} |
|
821 |
||
822 |
// Code stolen from DigestAuthentication: |
|
823 |
||
824 |
private static final char charArray[] = { |
|
825 |
'0', '1', '2', '3', '4', '5', '6', '7', |
|
826 |
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' |
|
827 |
}; |
|
828 |
||
829 |
private static String encode(String src, char[] passwd, MessageDigest md) { |
|
830 |
try { |
|
831 |
md.update(src.getBytes("ISO-8859-1")); |
|
832 |
} catch (java.io.UnsupportedEncodingException uee) { |
|
833 |
assert false; |
|
834 |
} |
|
835 |
if (passwd != null) { |
|
836 |
byte[] passwdBytes = new byte[passwd.length]; |
|
837 |
for (int i=0; i<passwd.length; i++) |
|
838 |
passwdBytes[i] = (byte)passwd[i]; |
|
839 |
md.update(passwdBytes); |
|
840 |
Arrays.fill(passwdBytes, (byte)0x00); |
|
841 |
} |
|
842 |
byte[] digest = md.digest(); |
|
843 |
||
844 |
StringBuilder res = new StringBuilder(digest.length * 2); |
|
845 |
for (int i = 0; i < digest.length; i++) { |
|
846 |
int hashchar = ((digest[i] >>> 4) & 0xf); |
|
847 |
res.append(charArray[hashchar]); |
|
848 |
hashchar = (digest[i] & 0xf); |
|
849 |
res.append(charArray[hashchar]); |
|
850 |
} |
|
851 |
return res.toString(); |
|
852 |
} |
|
853 |
||
854 |
public static String computeDigest(boolean isRequest, |
|
50681 | 855 |
String reqMethod, |
856 |
char[] password, |
|
857 |
DigestResponse params) |
|
49765 | 858 |
throws NoSuchAlgorithmException |
859 |
{ |
|
860 |
||
861 |
String A1, HashA1; |
|
862 |
String algorithm = params.getAlgorithm("MD5"); |
|
863 |
boolean md5sess = algorithm.equalsIgnoreCase ("MD5-sess"); |
|
864 |
||
865 |
MessageDigest md = MessageDigest.getInstance(md5sess?"MD5":algorithm); |
|
866 |
||
867 |
if (params.username == null) { |
|
868 |
throw new IllegalArgumentException("missing username"); |
|
869 |
} |
|
870 |
if (params.realm == null) { |
|
871 |
throw new IllegalArgumentException("missing realm"); |
|
872 |
} |
|
873 |
if (params.uri == null) { |
|
874 |
throw new IllegalArgumentException("missing uri"); |
|
875 |
} |
|
876 |
if (params.nonce == null) { |
|
877 |
throw new IllegalArgumentException("missing nonce"); |
|
878 |
} |
|
879 |
||
880 |
A1 = params.username + ":" + params.realm + ":"; |
|
881 |
HashA1 = encode(A1, password, md); |
|
882 |
||
883 |
String A2; |
|
884 |
if (isRequest) { |
|
885 |
A2 = reqMethod + ":" + params.uri; |
|
886 |
} else { |
|
887 |
A2 = ":" + params.uri; |
|
888 |
} |
|
889 |
String HashA2 = encode(A2, null, md); |
|
890 |
String combo, finalHash; |
|
891 |
||
892 |
if ("auth".equals(params.qop)) { /* RRC2617 when qop=auth */ |
|
893 |
if (params.cnonce == null) { |
|
894 |
throw new IllegalArgumentException("missing nonce"); |
|
895 |
} |
|
896 |
if (params.nc == null) { |
|
897 |
throw new IllegalArgumentException("missing nonce"); |
|
898 |
} |
|
899 |
combo = HashA1+ ":" + params.nonce + ":" + params.nc + ":" + |
|
900 |
params.cnonce + ":auth:" +HashA2; |
|
901 |
||
902 |
} else { /* for compatibility with RFC2069 */ |
|
903 |
combo = HashA1 + ":" + |
|
904 |
params.nonce + ":" + |
|
905 |
HashA2; |
|
906 |
} |
|
907 |
finalHash = encode(combo, null, md); |
|
908 |
return finalHash; |
|
909 |
} |
|
910 |
||
911 |
public static DigestResponse create(String raw) { |
|
912 |
String username, realm, nonce, nc, uri, response, cnonce, |
|
913 |
algorithm, qop, opaque; |
|
914 |
HeaderParser parser = new HeaderParser(raw); |
|
915 |
username = parser.findValue("username"); |
|
916 |
realm = parser.findValue("realm"); |
|
917 |
nonce = parser.findValue("nonce"); |
|
918 |
nc = parser.findValue("nc"); |
|
919 |
uri = parser.findValue("uri"); |
|
920 |
cnonce = parser.findValue("cnonce"); |
|
921 |
response = parser.findValue("response"); |
|
922 |
algorithm = parser.findValue("algorithm"); |
|
923 |
qop = parser.findValue("qop"); |
|
924 |
opaque = parser.findValue("opaque"); |
|
925 |
return new DigestResponse(realm, username, nonce, cnonce, nc, uri, |
|
926 |
algorithm, qop, opaque, response); |
|
927 |
} |
|
928 |
||
929 |
} |
|
930 |
||
931 |
private static class HttpNoAuthFilter extends AbstractHttpFilter { |
|
932 |
||
933 |
static String type(String key, HttpAuthType authType) { |
|
934 |
String type = authType == HttpAuthType.SERVER |
|
935 |
? "NoAuth Server Filter" : "NoAuth Proxy Filter"; |
|
936 |
return "["+type+"]:"+key; |
|
937 |
} |
|
938 |
||
939 |
public HttpNoAuthFilter(String key, HttpAuthType authType) { |
|
940 |
super(authType, type(key, authType)); |
|
941 |
} |
|
942 |
||
943 |
@Override |
|
944 |
protected boolean isAuthentified(HttpTestExchange he) throws IOException { |
|
945 |
return true; |
|
946 |
} |
|
947 |
||
948 |
@Override |
|
949 |
protected void requestAuthentication(HttpTestExchange he) throws IOException { |
|
950 |
throw new InternalError("Should not com here"); |
|
951 |
} |
|
952 |
||
953 |
@Override |
|
954 |
public String description() { |
|
955 |
return "Passthrough Filter"; |
|
956 |
} |
|
957 |
||
958 |
} |
|
959 |
||
960 |
// An HTTP Filter that performs Basic authentication |
|
961 |
private static class HttpBasicFilter extends AbstractHttpFilter { |
|
962 |
||
963 |
static String type(String key, HttpAuthType authType) { |
|
964 |
String type = authType == HttpAuthType.SERVER |
|
965 |
? "Basic Server Filter" : "Basic Proxy Filter"; |
|
966 |
return "["+type+"]:"+key; |
|
967 |
} |
|
968 |
||
969 |
private final HttpTestAuthenticator auth; |
|
970 |
public HttpBasicFilter(String key, HttpTestAuthenticator auth, |
|
971 |
HttpAuthType authType) { |
|
972 |
super(authType, type(key, authType)); |
|
973 |
this.auth = auth; |
|
974 |
} |
|
975 |
||
976 |
@Override |
|
977 |
protected void requestAuthentication(HttpTestExchange he) |
|
50681 | 978 |
throws IOException |
979 |
{ |
|
980 |
String headerName = getAuthenticate(); |
|
981 |
String headerValue = "Basic realm=\"" + auth.getRealm() + "\""; |
|
982 |
he.getResponseHeaders().addHeader(headerName, headerValue); |
|
983 |
System.out.println(type + ": Requesting Basic Authentication, " |
|
984 |
+ headerName + " : "+ headerValue); |
|
49765 | 985 |
} |
986 |
||
987 |
@Override |
|
988 |
protected boolean isAuthentified(HttpTestExchange he) { |
|
989 |
if (he.getRequestHeaders().containsKey(getAuthorization())) { |
|
990 |
List<String> authorization = |
|
991 |
he.getRequestHeaders().get(getAuthorization()); |
|
992 |
for (String a : authorization) { |
|
993 |
System.out.println(type + ": processing " + a); |
|
994 |
int sp = a.indexOf(' '); |
|
995 |
if (sp < 0) return false; |
|
996 |
String scheme = a.substring(0, sp); |
|
997 |
if (!"Basic".equalsIgnoreCase(scheme)) { |
|
998 |
System.out.println(type + ": Unsupported scheme '" |
|
999 |
+ scheme +"'"); |
|
1000 |
return false; |
|
1001 |
} |
|
1002 |
if (a.length() <= sp+1) { |
|
1003 |
System.out.println(type + ": value too short for '" |
|
1004 |
+ scheme +"'"); |
|
1005 |
return false; |
|
1006 |
} |
|
1007 |
a = a.substring(sp+1); |
|
1008 |
return validate(a); |
|
1009 |
} |
|
1010 |
return false; |
|
1011 |
} |
|
1012 |
return false; |
|
1013 |
} |
|
1014 |
||
1015 |
boolean validate(String a) { |
|
1016 |
byte[] b = Base64.getDecoder().decode(a); |
|
1017 |
String userpass = new String (b); |
|
1018 |
int colon = userpass.indexOf (':'); |
|
1019 |
String uname = userpass.substring (0, colon); |
|
1020 |
String pass = userpass.substring (colon+1); |
|
1021 |
return auth.getUserName().equals(uname) && |
|
1022 |
new String(auth.getPassword(uname)).equals(pass); |
|
1023 |
} |
|
1024 |
||
1025 |
@Override |
|
1026 |
public String description() { |
|
1027 |
return "Filter for BASIC authentication: " + type; |
|
1028 |
} |
|
1029 |
||
1030 |
} |
|
1031 |
||
1032 |
||
1033 |
// An HTTP Filter that performs Digest authentication |
|
1034 |
// WARNING: This is not a full fledged implementation of DIGEST. |
|
1035 |
// It does contain bugs and inaccuracy. |
|
1036 |
private static class HttpDigestFilter extends AbstractHttpFilter { |
|
1037 |
||
1038 |
static String type(String key, HttpAuthType authType) { |
|
1039 |
String type = authType == HttpAuthType.SERVER |
|
1040 |
? "Digest Server Filter" : "Digest Proxy Filter"; |
|
1041 |
return "["+type+"]:"+key; |
|
1042 |
} |
|
1043 |
||
1044 |
// This is a very basic DIGEST - used only for the purpose of testing |
|
1045 |
// the client implementation. Therefore we can get away with never |
|
1046 |
// updating the server nonce as it makes the implementation of the |
|
1047 |
// server side digest simpler. |
|
1048 |
private final HttpTestAuthenticator auth; |
|
1049 |
private final byte[] nonce; |
|
1050 |
private final String ns; |
|
1051 |
public HttpDigestFilter(String key, HttpTestAuthenticator auth, HttpAuthType authType) { |
|
1052 |
super(authType, type(key, authType)); |
|
1053 |
this.auth = auth; |
|
1054 |
nonce = new byte[16]; |
|
1055 |
new Random(Instant.now().toEpochMilli()).nextBytes(nonce); |
|
1056 |
ns = new BigInteger(1, nonce).toString(16); |
|
1057 |
} |
|
1058 |
||
1059 |
@Override |
|
1060 |
protected void requestAuthentication(HttpTestExchange he) |
|
1061 |
throws IOException { |
|
1062 |
String separator; |
|
1063 |
Version v = he.getExchangeVersion(); |
|
1064 |
if (v == Version.HTTP_1_1) { |
|
1065 |
separator = "\r\n "; |
|
1066 |
} else if (v == Version.HTTP_2) { |
|
1067 |
separator = " "; |
|
1068 |
} else { |
|
1069 |
throw new InternalError(String.valueOf(v)); |
|
1070 |
} |
|
50681 | 1071 |
String headerName = getAuthenticate(); |
1072 |
String headerValue = "Digest realm=\"" + auth.getRealm() + "\"," |
|
1073 |
+ separator + "qop=\"auth\"," |
|
1074 |
+ separator + "nonce=\"" + ns +"\""; |
|
1075 |
he.getResponseHeaders().addHeader(headerName, headerValue); |
|
1076 |
System.out.println(type + ": Requesting Digest Authentication, " |
|
1077 |
+ headerName + " : " + headerValue); |
|
49765 | 1078 |
} |
1079 |
||
1080 |
@Override |
|
1081 |
protected boolean isAuthentified(HttpTestExchange he) { |
|
1082 |
if (he.getRequestHeaders().containsKey(getAuthorization())) { |
|
1083 |
List<String> authorization = he.getRequestHeaders().get(getAuthorization()); |
|
1084 |
for (String a : authorization) { |
|
1085 |
System.out.println(type + ": processing " + a); |
|
1086 |
int sp = a.indexOf(' '); |
|
1087 |
if (sp < 0) return false; |
|
1088 |
String scheme = a.substring(0, sp); |
|
1089 |
if (!"Digest".equalsIgnoreCase(scheme)) { |
|
1090 |
System.out.println(type + ": Unsupported scheme '" + scheme +"'"); |
|
1091 |
return false; |
|
1092 |
} |
|
1093 |
if (a.length() <= sp+1) { |
|
1094 |
System.out.println(type + ": value too short for '" + scheme +"'"); |
|
1095 |
return false; |
|
1096 |
} |
|
1097 |
a = a.substring(sp+1); |
|
1098 |
DigestResponse dgr = DigestResponse.create(a); |
|
1099 |
return validate(he.getRequestURI(), he.getRequestMethod(), dgr); |
|
1100 |
} |
|
1101 |
return false; |
|
1102 |
} |
|
1103 |
return false; |
|
1104 |
} |
|
1105 |
||
1106 |
boolean validate(URI uri, String reqMethod, DigestResponse dg) { |
|
1107 |
if (!"MD5".equalsIgnoreCase(dg.getAlgorithm("MD5"))) { |
|
1108 |
System.out.println(type + ": Unsupported algorithm " |
|
1109 |
+ dg.algorithm); |
|
1110 |
return false; |
|
1111 |
} |
|
1112 |
if (!"auth".equalsIgnoreCase(dg.getQoP("auth"))) { |
|
1113 |
System.out.println(type + ": Unsupported qop " |
|
1114 |
+ dg.qop); |
|
1115 |
return false; |
|
1116 |
} |
|
1117 |
try { |
|
1118 |
if (!dg.nonce.equals(ns)) { |
|
1119 |
System.out.println(type + ": bad nonce returned by client: " |
|
1120 |
+ nonce + " expected " + ns); |
|
1121 |
return false; |
|
1122 |
} |
|
1123 |
if (dg.response == null) { |
|
1124 |
System.out.println(type + ": missing digest response."); |
|
1125 |
return false; |
|
1126 |
} |
|
1127 |
char[] pa = auth.getPassword(dg.username); |
|
1128 |
return verify(uri, reqMethod, dg, pa); |
|
1129 |
} catch(IllegalArgumentException | SecurityException |
|
1130 |
| NoSuchAlgorithmException e) { |
|
1131 |
System.out.println(type + ": " + e.getMessage()); |
|
1132 |
return false; |
|
1133 |
} |
|
1134 |
} |
|
1135 |
||
1136 |
||
1137 |
boolean verify(URI uri, String reqMethod, DigestResponse dg, char[] pw) |
|
1138 |
throws NoSuchAlgorithmException { |
|
1139 |
String response = DigestResponse.computeDigest(true, reqMethod, pw, dg); |
|
1140 |
if (!dg.response.equals(response)) { |
|
1141 |
System.out.println(type + ": bad response returned by client: " |
|
1142 |
+ dg.response + " expected " + response); |
|
1143 |
return false; |
|
1144 |
} else { |
|
1145 |
// A real server would also verify the uri=<request-uri> |
|
1146 |
// parameter - but this is just a test... |
|
1147 |
System.out.println(type + ": verified response " + response); |
|
1148 |
} |
|
1149 |
return true; |
|
1150 |
} |
|
1151 |
||
1152 |
||
1153 |
@Override |
|
1154 |
public String description() { |
|
1155 |
return "Filter for DIGEST authentication: " + type; |
|
1156 |
} |
|
1157 |
} |
|
1158 |
||
1159 |
// Abstract HTTP handler class. |
|
1160 |
private abstract static class AbstractHttpHandler implements HttpTestHandler { |
|
1161 |
||
1162 |
final HttpAuthType authType; |
|
1163 |
final String type; |
|
1164 |
public AbstractHttpHandler(HttpAuthType authType, String type) { |
|
1165 |
this.authType = authType; |
|
1166 |
this.type = type; |
|
1167 |
} |
|
1168 |
||
1169 |
String getLocation() { |
|
1170 |
return "Location"; |
|
1171 |
} |
|
1172 |
||
1173 |
@Override |
|
1174 |
public void handle(HttpTestExchange he) throws IOException { |
|
1175 |
try { |
|
1176 |
sendResponse(he); |
|
1177 |
} catch (RuntimeException | Error | IOException t) { |
|
1178 |
System.err.println(type |
|
1179 |
+ ": Unexpected exception while handling request: " + t); |
|
1180 |
t.printStackTrace(System.err); |
|
1181 |
throw t; |
|
1182 |
} finally { |
|
1183 |
he.close(); |
|
1184 |
} |
|
1185 |
} |
|
1186 |
||
1187 |
protected abstract void sendResponse(HttpTestExchange he) throws IOException; |
|
1188 |
||
1189 |
} |
|
1190 |
||
1191 |
static String stype(String type, String key, HttpAuthType authType, boolean tunnelled) { |
|
1192 |
type = type + (authType == HttpAuthType.SERVER |
|
1193 |
? " Server" : " Proxy") |
|
1194 |
+ (tunnelled ? " Tunnelled" : ""); |
|
1195 |
return "["+type+"]:"+key; |
|
1196 |
} |
|
1197 |
||
1198 |
private class HttpNoAuthHandler extends AbstractHttpHandler { |
|
1199 |
||
1200 |
// true if this server is behind a proxy tunnel. |
|
1201 |
final boolean tunnelled; |
|
1202 |
public HttpNoAuthHandler(String key, HttpAuthType authType, boolean tunnelled) { |
|
1203 |
super(authType, stype("NoAuth", key, authType, tunnelled)); |
|
1204 |
this.tunnelled = tunnelled; |
|
1205 |
} |
|
1206 |
||
1207 |
@Override |
|
1208 |
protected void sendResponse(HttpTestExchange he) throws IOException { |
|
1209 |
if (DEBUG) { |
|
1210 |
System.out.println(type + ": headers are: " |
|
1211 |
+ DigestEchoServer.toString(he.getRequestHeaders())); |
|
1212 |
} |
|
1213 |
if (authType == HttpAuthType.SERVER && tunnelled) { |
|
1214 |
// Verify that the client doesn't send us proxy-* headers |
|
1215 |
// used to establish the proxy tunnel |
|
1216 |
Optional<String> proxyAuth = he.getRequestHeaders() |
|
1217 |
.keySet().stream() |
|
1218 |
.filter("proxy-authorization"::equalsIgnoreCase) |
|
1219 |
.findAny(); |
|
1220 |
if (proxyAuth.isPresent()) { |
|
1221 |
System.out.println(type + " found " |
|
1222 |
+ proxyAuth.get() + ": failing!"); |
|
1223 |
throw new IOException(proxyAuth.get() |
|
1224 |
+ " found by " + type + " for " |
|
1225 |
+ he.getRequestURI()); |
|
1226 |
} |
|
1227 |
} |
|
1228 |
DigestEchoServer.this.writeResponse(he); |
|
1229 |
} |
|
1230 |
||
1231 |
} |
|
1232 |
||
1233 |
// A dummy HTTP Handler that redirects all incoming requests |
|
1234 |
// by sending a back 3xx response code (301, 305, 307 etc..) |
|
1235 |
private class Http3xxHandler extends AbstractHttpHandler { |
|
1236 |
||
1237 |
private final URL redirectTargetURL; |
|
1238 |
private final int code3XX; |
|
1239 |
public Http3xxHandler(String key, URL proxyURL, HttpAuthType authType, int code300) { |
|
1240 |
super(authType, stype("Server" + code300, key, authType, false)); |
|
1241 |
this.redirectTargetURL = proxyURL; |
|
1242 |
this.code3XX = code300; |
|
1243 |
} |
|
1244 |
||
1245 |
int get3XX() { |
|
1246 |
return code3XX; |
|
1247 |
} |
|
1248 |
||
1249 |
@Override |
|
1250 |
public void sendResponse(HttpTestExchange he) throws IOException { |
|
1251 |
System.out.println(type + ": Got " + he.getRequestMethod() |
|
1252 |
+ ": " + he.getRequestURI() |
|
1253 |
+ "\n" + DigestEchoServer.toString(he.getRequestHeaders())); |
|
1254 |
System.out.println(type + ": Redirecting to " |
|
1255 |
+ (authType == HttpAuthType.PROXY305 |
|
1256 |
? "proxy" : "server")); |
|
1257 |
he.getResponseHeaders().addHeader(getLocation(), |
|
1258 |
redirectTargetURL.toExternalForm().toString()); |
|
1259 |
he.sendResponseHeaders(get3XX(), -1); |
|
1260 |
System.out.println(type + ": Sent back " + get3XX() + " " |
|
1261 |
+ getLocation() + ": " + redirectTargetURL.toExternalForm().toString()); |
|
1262 |
} |
|
1263 |
} |
|
1264 |
||
1265 |
static class Configurator extends HttpsConfigurator { |
|
1266 |
public Configurator(SSLContext ctx) { |
|
1267 |
super(ctx); |
|
1268 |
} |
|
1269 |
||
1270 |
@Override |
|
1271 |
public void configure (HttpsParameters params) { |
|
1272 |
params.setSSLParameters (getSSLContext().getSupportedSSLParameters()); |
|
1273 |
} |
|
1274 |
} |
|
1275 |
||
1276 |
static final long start = System.nanoTime(); |
|
1277 |
public static String now() { |
|
1278 |
long now = System.nanoTime() - start; |
|
1279 |
long secs = now / 1000_000_000; |
|
1280 |
long mill = (now % 1000_000_000) / 1000_000; |
|
1281 |
long nan = now % 1000_000; |
|
1282 |
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan); |
|
1283 |
} |
|
1284 |
||
1285 |
static class ProxyAuthorization { |
|
1286 |
final HttpAuthSchemeType schemeType; |
|
1287 |
final HttpTestAuthenticator authenticator; |
|
1288 |
private final byte[] nonce; |
|
1289 |
private final String ns; |
|
1290 |
private final String key; |
|
1291 |
||
1292 |
ProxyAuthorization(String key, HttpAuthSchemeType schemeType, HttpTestAuthenticator auth) { |
|
1293 |
this.key = key; |
|
1294 |
this.schemeType = schemeType; |
|
1295 |
this.authenticator = auth; |
|
1296 |
nonce = new byte[16]; |
|
1297 |
new Random(Instant.now().toEpochMilli()).nextBytes(nonce); |
|
1298 |
ns = new BigInteger(1, nonce).toString(16); |
|
1299 |
} |
|
1300 |
||
1301 |
String doBasic(Optional<String> authorization) { |
|
1302 |
String offset = "proxy-authorization: basic "; |
|
1303 |
String authstring = authorization.orElse(""); |
|
1304 |
if (!authstring.toLowerCase(Locale.US).startsWith(offset)) { |
|
1305 |
return "Proxy-Authenticate: BASIC " + "realm=\"" |
|
1306 |
+ authenticator.getRealm() +"\""; |
|
1307 |
} |
|
1308 |
authstring = authstring |
|
1309 |
.substring(offset.length()) |
|
1310 |
.trim(); |
|
1311 |
byte[] base64 = Base64.getDecoder().decode(authstring); |
|
1312 |
String up = new String(base64, StandardCharsets.UTF_8); |
|
1313 |
int colon = up.indexOf(':'); |
|
1314 |
if (colon < 1) { |
|
1315 |
return "Proxy-Authenticate: BASIC " + "realm=\"" |
|
1316 |
+ authenticator.getRealm() +"\""; |
|
1317 |
} |
|
1318 |
String u = up.substring(0, colon); |
|
1319 |
String p = up.substring(colon+1); |
|
1320 |
char[] pw = authenticator.getPassword(u); |
|
1321 |
if (!p.equals(new String(pw))) { |
|
1322 |
return "Proxy-Authenticate: BASIC " + "realm=\"" |
|
1323 |
+ authenticator.getRealm() +"\""; |
|
1324 |
} |
|
1325 |
System.out.println(now() + key + " Proxy basic authentication success"); |
|
1326 |
return null; |
|
1327 |
} |
|
1328 |
||
1329 |
String doDigest(Optional<String> authorization) { |
|
1330 |
String offset = "proxy-authorization: digest "; |
|
1331 |
String authstring = authorization.orElse(""); |
|
1332 |
if (!authstring.toLowerCase(Locale.US).startsWith(offset)) { |
|
1333 |
return "Proxy-Authenticate: " + |
|
1334 |
"Digest realm=\"" + authenticator.getRealm() + "\"," |
|
1335 |
+ "\r\n qop=\"auth\"," |
|
1336 |
+ "\r\n nonce=\"" + ns +"\""; |
|
1337 |
} |
|
1338 |
authstring = authstring |
|
1339 |
.substring(offset.length()) |
|
1340 |
.trim(); |
|
1341 |
boolean validated = false; |
|
1342 |
try { |
|
1343 |
DigestResponse dgr = DigestResponse.create(authstring); |
|
1344 |
validated = validate("CONNECT", dgr); |
|
1345 |
} catch (Throwable t) { |
|
1346 |
t.printStackTrace(); |
|
1347 |
} |
|
1348 |
if (!validated) { |
|
1349 |
return "Proxy-Authenticate: " + |
|
1350 |
"Digest realm=\"" + authenticator.getRealm() + "\"," |
|
1351 |
+ "\r\n qop=\"auth\"," |
|
1352 |
+ "\r\n nonce=\"" + ns +"\""; |
|
1353 |
} |
|
1354 |
return null; |
|
1355 |
} |
|
1356 |
||
1357 |
||
1358 |
||
1359 |
||
1360 |
boolean validate(String reqMethod, DigestResponse dg) { |
|
1361 |
String type = now() + this.getClass().getSimpleName() + ":" + key; |
|
1362 |
if (!"MD5".equalsIgnoreCase(dg.getAlgorithm("MD5"))) { |
|
1363 |
System.out.println(type + ": Unsupported algorithm " |
|
1364 |
+ dg.algorithm); |
|
1365 |
return false; |
|
1366 |
} |
|
1367 |
if (!"auth".equalsIgnoreCase(dg.getQoP("auth"))) { |
|
1368 |
System.out.println(type + ": Unsupported qop " |
|
1369 |
+ dg.qop); |
|
1370 |
return false; |
|
1371 |
} |
|
1372 |
try { |
|
1373 |
if (!dg.nonce.equals(ns)) { |
|
1374 |
System.out.println(type + ": bad nonce returned by client: " |
|
1375 |
+ nonce + " expected " + ns); |
|
1376 |
return false; |
|
1377 |
} |
|
1378 |
if (dg.response == null) { |
|
1379 |
System.out.println(type + ": missing digest response."); |
|
1380 |
return false; |
|
1381 |
} |
|
1382 |
char[] pa = authenticator.getPassword(dg.username); |
|
1383 |
return verify(type, reqMethod, dg, pa); |
|
1384 |
} catch(IllegalArgumentException | SecurityException |
|
1385 |
| NoSuchAlgorithmException e) { |
|
1386 |
System.out.println(type + ": " + e.getMessage()); |
|
1387 |
return false; |
|
1388 |
} |
|
1389 |
} |
|
1390 |
||
1391 |
||
1392 |
boolean verify(String type, String reqMethod, DigestResponse dg, char[] pw) |
|
1393 |
throws NoSuchAlgorithmException { |
|
1394 |
String response = DigestResponse.computeDigest(true, reqMethod, pw, dg); |
|
1395 |
if (!dg.response.equals(response)) { |
|
1396 |
System.out.println(type + ": bad response returned by client: " |
|
1397 |
+ dg.response + " expected " + response); |
|
1398 |
return false; |
|
1399 |
} else { |
|
1400 |
// A real server would also verify the uri=<request-uri> |
|
1401 |
// parameter - but this is just a test... |
|
1402 |
System.out.println(type + ": verified response " + response); |
|
1403 |
} |
|
1404 |
return true; |
|
1405 |
} |
|
1406 |
||
1407 |
public boolean authorize(StringBuilder response, String requestLine, String headers) { |
|
1408 |
String message = "<html><body><p>Authorization Failed%s</p></body></html>\r\n"; |
|
1409 |
if (authenticator == null && schemeType != HttpAuthSchemeType.NONE) { |
|
1410 |
message = String.format(message, " No Authenticator Set"); |
|
1411 |
response.append("HTTP/1.1 407 Proxy Authentication Failed\r\n"); |
|
1412 |
response.append("Content-Length: ") |
|
1413 |
.append(message.getBytes(StandardCharsets.UTF_8).length) |
|
1414 |
.append("\r\n\r\n"); |
|
1415 |
response.append(message); |
|
1416 |
return false; |
|
1417 |
} |
|
1418 |
Optional<String> authorization = Stream.of(headers.split("\r\n")) |
|
1419 |
.filter((k) -> k.toLowerCase(Locale.US).startsWith("proxy-authorization:")) |
|
1420 |
.findFirst(); |
|
1421 |
String authenticate = null; |
|
1422 |
switch(schemeType) { |
|
1423 |
case BASIC: |
|
1424 |
case BASICSERVER: |
|
1425 |
authenticate = doBasic(authorization); |
|
1426 |
break; |
|
1427 |
case DIGEST: |
|
1428 |
authenticate = doDigest(authorization); |
|
1429 |
break; |
|
1430 |
case NONE: |
|
1431 |
response.append("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); |
|
1432 |
return true; |
|
1433 |
default: |
|
1434 |
throw new InternalError("Unknown scheme type: " + schemeType); |
|
1435 |
} |
|
1436 |
if (authenticate != null) { |
|
1437 |
message = String.format(message, ""); |
|
1438 |
response.append("HTTP/1.1 407 Proxy Authentication Required\r\n"); |
|
1439 |
response.append("Content-Length: ") |
|
1440 |
.append(message.getBytes(StandardCharsets.UTF_8).length) |
|
1441 |
.append("\r\n") |
|
1442 |
.append(authenticate) |
|
1443 |
.append("\r\n\r\n"); |
|
1444 |
response.append(message); |
|
1445 |
return false; |
|
1446 |
} |
|
1447 |
response.append("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); |
|
1448 |
return true; |
|
1449 |
} |
|
1450 |
} |
|
1451 |
||
1452 |
public interface TunnelingProxy { |
|
1453 |
InetSocketAddress getProxyAddress(); |
|
1454 |
void stop(); |
|
1455 |
} |
|
1456 |
||
1457 |
// This is a bit hacky: HttpsProxyTunnel is an HTTPTestServer hidden |
|
1458 |
// behind a fake proxy that only understands CONNECT requests. |
|
1459 |
// The fake proxy is just a server socket that intercept the |
|
1460 |
// CONNECT and then redirect streams to the real server. |
|
1461 |
static class HttpsProxyTunnel extends DigestEchoServer |
|
1462 |
implements Runnable, TunnelingProxy { |
|
1463 |
||
1464 |
final ServerSocket ss; |
|
1465 |
final CopyOnWriteArrayList<CompletableFuture<Void>> connectionCFs |
|
1466 |
= new CopyOnWriteArrayList<>(); |
|
1467 |
volatile ProxyAuthorization authorization; |
|
1468 |
volatile boolean stopped; |
|
1469 |
public HttpsProxyTunnel(String key, HttpTestServer server, DigestEchoServer target, |
|
1470 |
HttpTestHandler delegate) |
|
1471 |
throws IOException { |
|
1472 |
this(key, server, target, delegate, ServerSocketFactory.create()); |
|
1473 |
} |
|
1474 |
private HttpsProxyTunnel(String key, HttpTestServer server, DigestEchoServer target, |
|
1475 |
HttpTestHandler delegate, ServerSocket ss) |
|
1476 |
throws IOException { |
|
1477 |
super("HttpsProxyTunnel:" + ss.getLocalPort() + ":" + key, |
|
1478 |
server, target, delegate); |
|
1479 |
System.out.flush(); |
|
1480 |
System.err.println("WARNING: HttpsProxyTunnel is an experimental test class"); |
|
1481 |
this.ss = ss; |
|
1482 |
start(); |
|
1483 |
} |
|
1484 |
||
1485 |
final void start() throws IOException { |
|
1486 |
Thread t = new Thread(this, "ProxyThread"); |
|
1487 |
t.setDaemon(true); |
|
1488 |
t.start(); |
|
1489 |
} |
|
1490 |
||
1491 |
@Override |
|
1492 |
public Version getServerVersion() { |
|
1493 |
// serverImpl is not null when this proxy |
|
1494 |
// serves a single server. It will be null |
|
1495 |
// if this proxy can serve multiple servers. |
|
1496 |
if (serverImpl != null) return serverImpl.getVersion(); |
|
1497 |
return null; |
|
1498 |
} |
|
1499 |
||
1500 |
@Override |
|
1501 |
public void stop() { |
|
1502 |
stopped = true; |
|
1503 |
if (serverImpl != null) { |
|
1504 |
serverImpl.stop(); |
|
1505 |
} |
|
1506 |
if (redirect != null) { |
|
1507 |
redirect.stop(); |
|
1508 |
} |
|
1509 |
try { |
|
1510 |
ss.close(); |
|
1511 |
} catch (IOException ex) { |
|
1512 |
if (DEBUG) ex.printStackTrace(System.out); |
|
1513 |
} |
|
1514 |
} |
|
1515 |
||
1516 |
||
1517 |
@Override |
|
1518 |
void configureAuthentication(HttpTestContext ctxt, |
|
1519 |
HttpAuthSchemeType schemeType, |
|
1520 |
HttpTestAuthenticator auth, |
|
1521 |
HttpAuthType authType) { |
|
1522 |
if (authType == HttpAuthType.PROXY || authType == HttpAuthType.PROXY305) { |
|
1523 |
authorization = new ProxyAuthorization(key, schemeType, auth); |
|
1524 |
} else { |
|
1525 |
super.configureAuthentication(ctxt, schemeType, auth, authType); |
|
1526 |
} |
|
1527 |
} |
|
1528 |
||
54579
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1529 |
boolean badRequest(StringBuilder response, String hostport, List<String> hosts) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1530 |
String message = null; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1531 |
if (hosts.isEmpty()) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1532 |
message = "No host header provided\r\n"; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1533 |
} else if (hosts.size() > 1) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1534 |
message = "Multiple host headers provided\r\n"; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1535 |
for (String h : hosts) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1536 |
message = message + "host: " + h + "\r\n"; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1537 |
} |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1538 |
} else { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1539 |
String h = hosts.get(0); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1540 |
if (!hostport.equalsIgnoreCase(h) |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1541 |
&& !hostport.equalsIgnoreCase(h + ":80") |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1542 |
&& !hostport.equalsIgnoreCase(h + ":443")) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1543 |
message = "Bad host provided: [" + h |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1544 |
+ "] doesnot match [" + hostport + "]\r\n"; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1545 |
} |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1546 |
} |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1547 |
if (message != null) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1548 |
int length = message.getBytes(StandardCharsets.UTF_8).length; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1549 |
response.append("HTTP/1.1 400 BadRequest\r\n") |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1550 |
.append("Content-Length: " + length) |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1551 |
.append("\r\n\r\n") |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1552 |
.append(message); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1553 |
return true; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1554 |
} |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1555 |
|
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1556 |
return false; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1557 |
} |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1558 |
|
49765 | 1559 |
boolean authorize(StringBuilder response, String requestLine, String headers) { |
1560 |
if (authorization != null) { |
|
1561 |
return authorization.authorize(response, requestLine, headers); |
|
1562 |
} |
|
1563 |
response.append("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); |
|
1564 |
return true; |
|
1565 |
} |
|
1566 |
||
1567 |
// Pipe the input stream to the output stream. |
|
1568 |
private synchronized Thread pipe(InputStream is, OutputStream os, char tag, CompletableFuture<Void> end) { |
|
1569 |
return new Thread("TunnelPipe("+tag+")") { |
|
1570 |
@Override |
|
1571 |
public void run() { |
|
1572 |
try { |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1573 |
int c = 0; |
49765 | 1574 |
try { |
1575 |
while ((c = is.read()) != -1) { |
|
1576 |
os.write(c); |
|
1577 |
os.flush(); |
|
1578 |
// if DEBUG prints a + or a - for each transferred |
|
1579 |
// character. |
|
1580 |
if (DEBUG) System.out.print(tag); |
|
1581 |
} |
|
1582 |
is.close(); |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1583 |
} catch (IOException ex) { |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1584 |
if (DEBUG || !stopped && c > -1) |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1585 |
ex.printStackTrace(System.out); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1586 |
end.completeExceptionally(ex); |
49765 | 1587 |
} finally { |
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1588 |
try {os.close();} catch (Throwable t) {} |
49765 | 1589 |
} |
1590 |
} finally { |
|
1591 |
end.complete(null); |
|
1592 |
} |
|
1593 |
} |
|
1594 |
}; |
|
1595 |
} |
|
1596 |
||
1597 |
@Override |
|
1598 |
public InetSocketAddress getAddress() { |
|
1599 |
return new InetSocketAddress(InetAddress.getLoopbackAddress(), |
|
1600 |
ss.getLocalPort()); |
|
1601 |
} |
|
1602 |
@Override |
|
1603 |
public InetSocketAddress getProxyAddress() { |
|
1604 |
return getAddress(); |
|
1605 |
} |
|
1606 |
@Override |
|
1607 |
public InetSocketAddress getServerAddress() { |
|
1608 |
// serverImpl can be null if this proxy can serve |
|
1609 |
// multiple servers. |
|
1610 |
if (serverImpl != null) { |
|
1611 |
return serverImpl.getAddress(); |
|
1612 |
} |
|
1613 |
return null; |
|
1614 |
} |
|
1615 |
||
1616 |
||
1617 |
// This is a bit shaky. It doesn't handle continuation |
|
1618 |
// lines, but our client shouldn't send any. |
|
1619 |
// Read a line from the input stream, swallowing the final |
|
1620 |
// \r\n sequence. Stops at the first \n, doesn't complain |
|
1621 |
// if it wasn't preceded by '\r'. |
|
1622 |
// |
|
1623 |
String readLine(InputStream r) throws IOException { |
|
1624 |
StringBuilder b = new StringBuilder(); |
|
1625 |
int c; |
|
1626 |
while ((c = r.read()) != -1) { |
|
1627 |
if (c == '\n') break; |
|
1628 |
b.appendCodePoint(c); |
|
1629 |
} |
|
1630 |
if (b.codePointAt(b.length() -1) == '\r') { |
|
1631 |
b.delete(b.length() -1, b.length()); |
|
1632 |
} |
|
1633 |
return b.toString(); |
|
1634 |
} |
|
1635 |
||
1636 |
@Override |
|
1637 |
public void run() { |
|
1638 |
Socket clientConnection = null; |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1639 |
Socket targetConnection = null; |
49765 | 1640 |
try { |
1641 |
while (!stopped) { |
|
1642 |
System.out.println(now() + "Tunnel: Waiting for client"); |
|
1643 |
Socket toClose; |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1644 |
targetConnection = clientConnection = null; |
49765 | 1645 |
try { |
1646 |
toClose = clientConnection = ss.accept(); |
|
53350
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
1647 |
if (NO_LINGER) { |
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
1648 |
// can be useful to trigger "Connection reset by peer" |
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
1649 |
// errors on the client side. |
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
1650 |
clientConnection.setOption(StandardSocketOptions.SO_LINGER, 0); |
a47b8125b7cc
8217094: HttpClient SSL race if a socket IOException is raised before ALPN is available
dfuchs
parents:
52387
diff
changeset
|
1651 |
} |
49765 | 1652 |
} catch (IOException io) { |
1653 |
if (DEBUG || !stopped) io.printStackTrace(System.out); |
|
1654 |
break; |
|
1655 |
} |
|
1656 |
System.out.println(now() + "Tunnel: Client accepted"); |
|
1657 |
StringBuilder headers = new StringBuilder(); |
|
1658 |
InputStream ccis = clientConnection.getInputStream(); |
|
1659 |
OutputStream ccos = clientConnection.getOutputStream(); |
|
1660 |
Writer w = new OutputStreamWriter( |
|
1661 |
clientConnection.getOutputStream(), "UTF-8"); |
|
1662 |
PrintWriter pw = new PrintWriter(w); |
|
1663 |
System.out.println(now() + "Tunnel: Reading request line"); |
|
1664 |
String requestLine = readLine(ccis); |
|
1665 |
System.out.println(now() + "Tunnel: Request line: " + requestLine); |
|
1666 |
if (requestLine.startsWith("CONNECT ")) { |
|
1667 |
// We should probably check that the next word following |
|
1668 |
// CONNECT is the host:port of our HTTPS serverImpl. |
|
1669 |
// Some improvement for a followup! |
|
1670 |
StringTokenizer tokenizer = new StringTokenizer(requestLine); |
|
1671 |
String connect = tokenizer.nextToken(); |
|
1672 |
assert connect.equalsIgnoreCase("connect"); |
|
1673 |
String hostport = tokenizer.nextToken(); |
|
1674 |
InetSocketAddress targetAddress; |
|
54579
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1675 |
List<String> hosts = new ArrayList<>(); |
49765 | 1676 |
try { |
1677 |
URI uri = new URI("https", hostport, "/", null, null); |
|
1678 |
int port = uri.getPort(); |
|
1679 |
port = port == -1 ? 443 : port; |
|
1680 |
targetAddress = new InetSocketAddress(uri.getHost(), port); |
|
1681 |
if (serverImpl != null) { |
|
1682 |
assert targetAddress.getHostString() |
|
1683 |
.equalsIgnoreCase(serverImpl.getAddress().getHostString()); |
|
1684 |
assert targetAddress.getPort() == serverImpl.getAddress().getPort(); |
|
1685 |
} |
|
1686 |
} catch (Throwable x) { |
|
1687 |
System.err.printf("Bad target address: \"%s\" in \"%s\"%n", |
|
1688 |
hostport, requestLine); |
|
1689 |
toClose.close(); |
|
1690 |
continue; |
|
1691 |
} |
|
1692 |
||
1693 |
// Read all headers until we find the empty line that |
|
1694 |
// signals the end of all headers. |
|
1695 |
String line = requestLine; |
|
1696 |
while(!line.equals("")) { |
|
1697 |
System.out.println(now() + "Tunnel: Reading header: " |
|
1698 |
+ (line = readLine(ccis))); |
|
1699 |
headers.append(line).append("\r\n"); |
|
54579
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1700 |
int index = line.indexOf(':'); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1701 |
if (index >= 0) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1702 |
String key = line.substring(0, index).trim(); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1703 |
if (key.equalsIgnoreCase("host")) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1704 |
hosts.add(line.substring(index+1).trim()); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1705 |
} |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1706 |
} |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1707 |
} |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1708 |
StringBuilder response = new StringBuilder(); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1709 |
if (TUNNEL_REQUIRES_HOST) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1710 |
if (badRequest(response, hostport, hosts)) { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1711 |
System.out.println(now() + "Tunnel: Sending " + response); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1712 |
// send the 400 response |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1713 |
pw.print(response.toString()); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1714 |
pw.flush(); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1715 |
toClose.close(); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1716 |
continue; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1717 |
} else { |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1718 |
assert hosts.size() == 1; |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1719 |
System.out.println(now() |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1720 |
+ "Tunnel: Host header verified " + hosts); |
270557b396eb
8222527: HttpClient doesn't send HOST header when tunelling HTTP/1.1 through http proxy
dfuchs
parents:
53350
diff
changeset
|
1721 |
} |
49765 | 1722 |
} |
1723 |
||
1724 |
final boolean authorize = authorize(response, requestLine, headers.toString()); |
|
1725 |
if (!authorize) { |
|
1726 |
System.out.println(now() + "Tunnel: Sending " |
|
1727 |
+ response); |
|
1728 |
// send the 407 response |
|
1729 |
pw.print(response.toString()); |
|
1730 |
pw.flush(); |
|
1731 |
toClose.close(); |
|
1732 |
continue; |
|
1733 |
} |
|
1734 |
System.out.println(now() |
|
1735 |
+ "Tunnel connecting to target server at " |
|
1736 |
+ targetAddress.getAddress() + ":" + targetAddress.getPort()); |
|
1737 |
targetConnection = new Socket( |
|
1738 |
targetAddress.getAddress(), |
|
1739 |
targetAddress.getPort()); |
|
1740 |
||
1741 |
// Then send the 200 OK response to the client |
|
1742 |
System.out.println(now() + "Tunnel: Sending " |
|
1743 |
+ response); |
|
1744 |
pw.print(response); |
|
1745 |
pw.flush(); |
|
1746 |
} else { |
|
1747 |
// This should not happen. If it does then just print an |
|
1748 |
// error - both on out and err, and close the accepted |
|
1749 |
// socket |
|
1750 |
System.out.println("WARNING: Tunnel: Unexpected status line: " |
|
1751 |
+ requestLine + " received by " |
|
1752 |
+ ss.getLocalSocketAddress() |
|
1753 |
+ " from " |
|
1754 |
+ toClose.getRemoteSocketAddress() |
|
1755 |
+ " - closing accepted socket"); |
|
1756 |
// Print on err |
|
1757 |
System.err.println("WARNING: Tunnel: Unexpected status line: " |
|
1758 |
+ requestLine + " received by " |
|
1759 |
+ ss.getLocalSocketAddress() |
|
1760 |
+ " from " |
|
1761 |
+ toClose.getRemoteSocketAddress()); |
|
1762 |
// close accepted socket. |
|
1763 |
toClose.close(); |
|
1764 |
System.err.println("Tunnel: accepted socket closed."); |
|
1765 |
continue; |
|
1766 |
} |
|
1767 |
||
1768 |
// Pipe the input stream of the client connection to the |
|
1769 |
// output stream of the target connection and conversely. |
|
1770 |
// Now the client and target will just talk to each other. |
|
1771 |
System.out.println(now() + "Tunnel: Starting tunnel pipes"); |
|
1772 |
CompletableFuture<Void> end, end1, end2; |
|
1773 |
Thread t1 = pipe(ccis, targetConnection.getOutputStream(), '+', |
|
1774 |
end1 = new CompletableFuture<>()); |
|
1775 |
Thread t2 = pipe(targetConnection.getInputStream(), ccos, '-', |
|
1776 |
end2 = new CompletableFuture<>()); |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1777 |
var end11 = end1.whenComplete((r, t) -> exceptionally(end2, t)); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1778 |
var end22 = end2.whenComplete((r, t) -> exceptionally(end1, t)); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1779 |
end = CompletableFuture.allOf(end11, end22); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1780 |
Socket tc = targetConnection; |
49765 | 1781 |
end.whenComplete( |
1782 |
(r,t) -> { |
|
1783 |
try { toClose.close(); } catch (IOException x) { } |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1784 |
try { tc.close(); } catch (IOException x) { } |
49765 | 1785 |
finally {connectionCFs.remove(end);} |
1786 |
}); |
|
1787 |
connectionCFs.add(end); |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1788 |
targetConnection = clientConnection = null; |
49765 | 1789 |
t1.start(); |
1790 |
t2.start(); |
|
1791 |
} |
|
1792 |
} catch (Throwable ex) { |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1793 |
close(clientConnection, ex); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1794 |
close(targetConnection, ex); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1795 |
close(ss, ex); |
49765 | 1796 |
ex.printStackTrace(System.err); |
1797 |
} finally { |
|
1798 |
System.out.println(now() + "Tunnel: exiting (stopped=" + stopped + ")"); |
|
1799 |
connectionCFs.forEach(cf -> cf.complete(null)); |
|
1800 |
} |
|
1801 |
} |
|
58423
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1802 |
|
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1803 |
void exceptionally(CompletableFuture<?> cf, Throwable t) { |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1804 |
if (t != null) cf.completeExceptionally(t); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1805 |
} |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1806 |
|
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1807 |
void close(Closeable c, Throwable e) { |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1808 |
if (c == null) return; |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1809 |
try { |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1810 |
c.close(); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1811 |
} catch (IOException x) { |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1812 |
e.addSuppressed(x); |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1813 |
} |
54de0c861d32
8231506: Fix some instabilities in a few networking tests
dfuchs
parents:
54579
diff
changeset
|
1814 |
} |
49765 | 1815 |
} |
1816 |
||
1817 |
/** |
|
1818 |
* Creates a TunnelingProxy that can serve multiple servers. |
|
1819 |
* The server address is extracted from the CONNECT request line. |
|
1820 |
* @param authScheme The authentication scheme supported by the proxy. |
|
1821 |
* Typically one of DIGEST, BASIC, NONE. |
|
1822 |
* @return A new TunnelingProxy able to serve multiple servers. |
|
1823 |
* @throws IOException If the proxy could not be created. |
|
1824 |
*/ |
|
1825 |
public static TunnelingProxy createHttpsProxyTunnel(HttpAuthSchemeType authScheme) |
|
1826 |
throws IOException { |
|
1827 |
HttpsProxyTunnel result = new HttpsProxyTunnel("", null, null, null); |
|
1828 |
if (authScheme != HttpAuthSchemeType.NONE) { |
|
1829 |
result.configureAuthentication(null, |
|
1830 |
authScheme, |
|
1831 |
AUTHENTICATOR, |
|
1832 |
HttpAuthType.PROXY); |
|
1833 |
} |
|
1834 |
return result; |
|
1835 |
} |
|
1836 |
||
1837 |
private static String protocol(String protocol) { |
|
1838 |
if ("http".equalsIgnoreCase(protocol)) return "http"; |
|
1839 |
else if ("https".equalsIgnoreCase(protocol)) return "https"; |
|
1840 |
else throw new InternalError("Unsupported protocol: " + protocol); |
|
1841 |
} |
|
1842 |
||
1843 |
public static URL url(String protocol, InetSocketAddress address, |
|
1844 |
String path) throws MalformedURLException { |
|
1845 |
return new URL(protocol(protocol), |
|
1846 |
address.getHostString(), |
|
1847 |
address.getPort(), path); |
|
1848 |
} |
|
1849 |
||
1850 |
public static URI uri(String protocol, InetSocketAddress address, |
|
1851 |
String path) throws URISyntaxException { |
|
1852 |
return new URI(protocol(protocol) + "://" + |
|
1853 |
address.getHostString() + ":" + |
|
1854 |
address.getPort() + path); |
|
1855 |
} |
|
1856 |
} |