49765
|
1 |
/*
|
|
2 |
* Copyright (c) 2018, 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.
|
|
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 |
/*
|
|
25 |
* @test
|
|
26 |
* @summary Tests that our client deals correctly with servers that
|
|
27 |
* close the connection right after sending the last byte.
|
|
28 |
* @library /lib/testlibrary http2/server
|
|
29 |
* @build jdk.testlibrary.SimpleSSLContext HttpServerAdapters EncodedCharsInURI
|
|
30 |
* @modules java.base/sun.net.www.http
|
|
31 |
* java.net.http/jdk.internal.net.http.common
|
|
32 |
* java.net.http/jdk.internal.net.http.frame
|
|
33 |
* java.net.http/jdk.internal.net.http.hpack
|
|
34 |
* @run testng/othervm ServerCloseTest
|
|
35 |
*/
|
|
36 |
//* -Djdk.internal.httpclient.debug=true
|
|
37 |
|
|
38 |
import jdk.testlibrary.SimpleSSLContext;
|
|
39 |
import org.testng.annotations.AfterClass;
|
|
40 |
import org.testng.annotations.AfterTest;
|
|
41 |
import org.testng.annotations.BeforeTest;
|
|
42 |
import org.testng.annotations.DataProvider;
|
|
43 |
import org.testng.annotations.Test;
|
|
44 |
|
|
45 |
import javax.net.ServerSocketFactory;
|
|
46 |
import javax.net.ssl.SSLContext;
|
|
47 |
import java.io.IOException;
|
|
48 |
import java.io.InputStream;
|
|
49 |
import java.io.OutputStream;
|
|
50 |
import java.io.OutputStreamWriter;
|
|
51 |
import java.io.PrintWriter;
|
|
52 |
import java.io.Writer;
|
|
53 |
import java.net.InetAddress;
|
|
54 |
import java.net.InetSocketAddress;
|
|
55 |
import java.net.ServerSocket;
|
|
56 |
import java.net.Socket;
|
|
57 |
import java.net.URI;
|
|
58 |
import java.net.http.HttpClient;
|
|
59 |
import java.net.http.HttpRequest;
|
|
60 |
import java.net.http.HttpRequest.BodyPublisher;
|
|
61 |
import java.net.http.HttpRequest.BodyPublishers;
|
|
62 |
import java.net.http.HttpResponse;
|
|
63 |
import java.net.http.HttpResponse.BodyHandler;
|
|
64 |
import java.net.http.HttpResponse.BodyHandlers;
|
|
65 |
import java.util.List;
|
|
66 |
import java.util.Locale;
|
|
67 |
import java.util.StringTokenizer;
|
|
68 |
import java.util.concurrent.CompletableFuture;
|
|
69 |
import java.util.concurrent.ConcurrentHashMap;
|
|
70 |
import java.util.concurrent.ConcurrentLinkedQueue;
|
|
71 |
import java.util.concurrent.ConcurrentMap;
|
|
72 |
import java.util.concurrent.Executor;
|
|
73 |
import java.util.concurrent.Executors;
|
|
74 |
import java.util.concurrent.atomic.AtomicLong;
|
|
75 |
|
|
76 |
import static java.lang.System.out;
|
|
77 |
import static java.nio.charset.StandardCharsets.UTF_8;
|
|
78 |
|
|
79 |
public class ServerCloseTest implements HttpServerAdapters {
|
|
80 |
|
|
81 |
SSLContext sslContext;
|
|
82 |
DummyServer httpDummyServer; // HTTP/1.1 [ 2 servers ]
|
|
83 |
DummyServer httpsDummyServer; // HTTPS/1.1
|
|
84 |
String httpDummy;
|
|
85 |
String httpsDummy;
|
|
86 |
|
|
87 |
static final int ITERATION_COUNT = 3;
|
|
88 |
// a shared executor helps reduce the amount of threads created by the test
|
|
89 |
static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());
|
|
90 |
static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();
|
|
91 |
static volatile boolean tasksFailed;
|
|
92 |
static final AtomicLong serverCount = new AtomicLong();
|
|
93 |
static final AtomicLong clientCount = new AtomicLong();
|
|
94 |
static final long start = System.nanoTime();
|
|
95 |
public static String now() {
|
|
96 |
long now = System.nanoTime() - start;
|
|
97 |
long secs = now / 1000_000_000;
|
|
98 |
long mill = (now % 1000_000_000) / 1000_000;
|
|
99 |
long nan = now % 1000_000;
|
|
100 |
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
|
|
101 |
}
|
|
102 |
|
|
103 |
private volatile HttpClient sharedClient;
|
|
104 |
|
|
105 |
static class TestExecutor implements Executor {
|
|
106 |
final AtomicLong tasks = new AtomicLong();
|
|
107 |
Executor executor;
|
|
108 |
TestExecutor(Executor executor) {
|
|
109 |
this.executor = executor;
|
|
110 |
}
|
|
111 |
|
|
112 |
@Override
|
|
113 |
public void execute(Runnable command) {
|
|
114 |
long id = tasks.incrementAndGet();
|
|
115 |
executor.execute(() -> {
|
|
116 |
try {
|
|
117 |
command.run();
|
|
118 |
} catch (Throwable t) {
|
|
119 |
tasksFailed = true;
|
|
120 |
System.out.printf(now() + "Task %s failed: %s%n", id, t);
|
|
121 |
System.err.printf(now() + "Task %s failed: %s%n", id, t);
|
|
122 |
FAILURES.putIfAbsent("Task " + id, t);
|
|
123 |
throw t;
|
|
124 |
}
|
|
125 |
});
|
|
126 |
}
|
|
127 |
}
|
|
128 |
|
|
129 |
@AfterClass
|
|
130 |
static final void printFailedTests() {
|
|
131 |
out.println("\n=========================");
|
|
132 |
try {
|
|
133 |
out.printf("%n%sCreated %d servers and %d clients%n",
|
|
134 |
now(), serverCount.get(), clientCount.get());
|
|
135 |
if (FAILURES.isEmpty()) return;
|
|
136 |
out.println("Failed tests: ");
|
|
137 |
FAILURES.entrySet().forEach((e) -> {
|
|
138 |
out.printf("\t%s: %s%n", e.getKey(), e.getValue());
|
|
139 |
e.getValue().printStackTrace(out);
|
|
140 |
});
|
|
141 |
if (tasksFailed) {
|
|
142 |
System.out.println("WARNING: Some tasks failed");
|
|
143 |
}
|
|
144 |
} finally {
|
|
145 |
out.println("\n=========================\n");
|
|
146 |
}
|
|
147 |
}
|
|
148 |
|
|
149 |
private String[] uris() {
|
|
150 |
return new String[] {
|
|
151 |
httpDummy,
|
|
152 |
httpsDummy,
|
|
153 |
};
|
|
154 |
}
|
|
155 |
|
|
156 |
@DataProvider(name = "servers")
|
|
157 |
public Object[][] noThrows() {
|
|
158 |
String[] uris = uris();
|
|
159 |
Object[][] result = new Object[uris.length * 2][];
|
|
160 |
//Object[][] result = new Object[uris.length][];
|
|
161 |
int i = 0;
|
|
162 |
for (boolean sameClient : List.of(false, true)) {
|
|
163 |
//if (!sameClient) continue;
|
|
164 |
for (String uri: uris()) {
|
|
165 |
result[i++] = new Object[] {uri, sameClient};
|
|
166 |
}
|
|
167 |
}
|
|
168 |
assert i == uris.length * 2;
|
|
169 |
// assert i == uris.length ;
|
|
170 |
return result;
|
|
171 |
}
|
|
172 |
|
|
173 |
private HttpClient makeNewClient() {
|
|
174 |
clientCount.incrementAndGet();
|
|
175 |
return HttpClient.newBuilder()
|
|
176 |
.executor(executor)
|
|
177 |
.sslContext(sslContext)
|
|
178 |
.build();
|
|
179 |
}
|
|
180 |
|
|
181 |
HttpClient newHttpClient(boolean share) {
|
|
182 |
if (!share) return makeNewClient();
|
|
183 |
HttpClient shared = sharedClient;
|
|
184 |
if (shared != null) return shared;
|
|
185 |
synchronized (this) {
|
|
186 |
shared = sharedClient;
|
|
187 |
if (shared == null) {
|
|
188 |
shared = sharedClient = makeNewClient();
|
|
189 |
}
|
|
190 |
return shared;
|
|
191 |
}
|
|
192 |
}
|
|
193 |
|
|
194 |
final String ENCODED = "/01%252F03/";
|
|
195 |
|
|
196 |
@Test(dataProvider = "servers")
|
|
197 |
public void testServerClose(String uri, boolean sameClient) {
|
|
198 |
HttpClient client = null;
|
|
199 |
out.printf("%n%s testServerClose(%s, %b)%n", now(), uri, sameClient);
|
|
200 |
uri = uri + ENCODED;
|
|
201 |
for (int i=0; i< ITERATION_COUNT; i++) {
|
|
202 |
if (!sameClient || client == null)
|
|
203 |
client = newHttpClient(sameClient);
|
|
204 |
|
|
205 |
BodyPublisher bodyPublisher = BodyPublishers.ofString(uri);
|
|
206 |
|
|
207 |
HttpRequest req = HttpRequest.newBuilder(URI.create(uri))
|
|
208 |
.POST(bodyPublisher)
|
|
209 |
.build();
|
|
210 |
BodyHandler<String> handler = BodyHandlers.ofString();
|
|
211 |
HttpClient c = client;
|
|
212 |
CompletableFuture<HttpResponse<String>> responseCF = c.sendAsync(req, handler);
|
|
213 |
// retry POST if needed #### Replace with exceptionallyCompose
|
|
214 |
responseCF = responseCF.handle((r,t) ->
|
|
215 |
t == null ? CompletableFuture.completedFuture(r)
|
|
216 |
: c.sendAsync(req, handler)).thenCompose(x -> x);
|
|
217 |
HttpResponse<String> response = responseCF.join();
|
|
218 |
String body = response.body();
|
|
219 |
if (!uri.contains(body)) {
|
|
220 |
System.err.println("Test failed: " + response);
|
|
221 |
throw new RuntimeException(uri + " doesn't contain '" + body + "'");
|
|
222 |
} else {
|
|
223 |
System.out.println("Found expected " + body + " in " + uri);
|
|
224 |
}
|
|
225 |
}
|
|
226 |
}
|
|
227 |
|
|
228 |
@BeforeTest
|
|
229 |
public void setup() throws Exception {
|
|
230 |
sslContext = new SimpleSSLContext().get();
|
|
231 |
if (sslContext == null)
|
|
232 |
throw new AssertionError("Unexpected null sslContext");
|
|
233 |
|
|
234 |
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
|
|
235 |
|
|
236 |
// DummyServer
|
|
237 |
httpDummyServer = DummyServer.create(sa);
|
|
238 |
httpsDummyServer = DummyServer.create(sa, sslContext);
|
|
239 |
httpDummy = "http://" + httpDummyServer.serverAuthority() + "/http1/dummy/x";
|
|
240 |
httpsDummy = "https://" + httpsDummyServer.serverAuthority() + "/https1/dummy/x";
|
|
241 |
|
|
242 |
|
|
243 |
serverCount.addAndGet(2);
|
|
244 |
httpDummyServer.start();
|
|
245 |
httpsDummyServer.start();
|
|
246 |
}
|
|
247 |
|
|
248 |
@AfterTest
|
|
249 |
public void teardown() throws Exception {
|
|
250 |
sharedClient = null;
|
|
251 |
httpDummyServer.stopServer();
|
|
252 |
httpsDummyServer.stopServer();
|
|
253 |
}
|
|
254 |
|
|
255 |
static class DummyServer extends Thread {
|
|
256 |
final ServerSocket ss;
|
|
257 |
final boolean secure;
|
|
258 |
ConcurrentLinkedQueue<Socket> connections = new ConcurrentLinkedQueue<>();
|
|
259 |
volatile boolean stopped;
|
|
260 |
DummyServer(ServerSocket ss, boolean secure) {
|
|
261 |
super("DummyServer[" + ss.getLocalPort()+"]");
|
|
262 |
this.secure = secure;
|
|
263 |
this.ss = ss;
|
|
264 |
}
|
|
265 |
|
|
266 |
// This is a bit shaky. It doesn't handle continuation
|
|
267 |
// lines, but our client shouldn't send any.
|
|
268 |
// Read a line from the input stream, swallowing the final
|
|
269 |
// \r\n sequence. Stops at the first \n, doesn't complain
|
|
270 |
// if it wasn't preceded by '\r'.
|
|
271 |
//
|
|
272 |
String readLine(InputStream r) throws IOException {
|
|
273 |
StringBuilder b = new StringBuilder();
|
|
274 |
int c;
|
|
275 |
while ((c = r.read()) != -1) {
|
|
276 |
if (c == '\n') break;
|
|
277 |
b.appendCodePoint(c);
|
|
278 |
}
|
|
279 |
if (b.codePointAt(b.length() -1) == '\r') {
|
|
280 |
b.delete(b.length() -1, b.length());
|
|
281 |
}
|
|
282 |
return b.toString();
|
|
283 |
}
|
|
284 |
|
|
285 |
@Override
|
|
286 |
public void run() {
|
|
287 |
try {
|
|
288 |
while(!stopped) {
|
|
289 |
Socket clientConnection = ss.accept();
|
|
290 |
connections.add(clientConnection);
|
|
291 |
System.out.println(now() + getName() + ": Client accepted");
|
|
292 |
StringBuilder headers = new StringBuilder();
|
|
293 |
Socket targetConnection = null;
|
|
294 |
InputStream ccis = clientConnection.getInputStream();
|
|
295 |
OutputStream ccos = clientConnection.getOutputStream();
|
|
296 |
Writer w = new OutputStreamWriter(
|
|
297 |
clientConnection.getOutputStream(), "UTF-8");
|
|
298 |
PrintWriter pw = new PrintWriter(w);
|
|
299 |
System.out.println(now() + getName() + ": Reading request line");
|
|
300 |
String requestLine = readLine(ccis);
|
|
301 |
System.out.println(now() + getName() + ": Request line: " + requestLine);
|
|
302 |
|
|
303 |
StringTokenizer tokenizer = new StringTokenizer(requestLine);
|
|
304 |
String method = tokenizer.nextToken();
|
|
305 |
assert method.equalsIgnoreCase("POST")
|
|
306 |
|| method.equalsIgnoreCase("GET");
|
|
307 |
String path = tokenizer.nextToken();
|
|
308 |
URI uri;
|
|
309 |
try {
|
|
310 |
String hostport = serverAuthority();
|
|
311 |
uri = new URI((secure ? "https" : "http") +"://" + hostport + path);
|
|
312 |
} catch (Throwable x) {
|
|
313 |
System.err.printf("Bad target address: \"%s\" in \"%s\"%n",
|
|
314 |
path, requestLine);
|
|
315 |
clientConnection.close();
|
|
316 |
continue;
|
|
317 |
}
|
|
318 |
|
|
319 |
// Read all headers until we find the empty line that
|
|
320 |
// signals the end of all headers.
|
|
321 |
String line = requestLine;
|
|
322 |
while (!line.equals("")) {
|
|
323 |
System.out.println(now() + getName() + ": Reading header: "
|
|
324 |
+ (line = readLine(ccis)));
|
|
325 |
headers.append(line).append("\r\n");
|
|
326 |
}
|
|
327 |
|
|
328 |
StringBuilder response = new StringBuilder();
|
|
329 |
|
|
330 |
int index = headers.toString()
|
|
331 |
.toLowerCase(Locale.US)
|
|
332 |
.indexOf("content-length: ");
|
|
333 |
byte[] b = uri.toString().getBytes(UTF_8);
|
|
334 |
if (index >= 0) {
|
|
335 |
index = index + "content-length: ".length();
|
|
336 |
String cl = headers.toString().substring(index);
|
|
337 |
StringTokenizer tk = new StringTokenizer(cl);
|
|
338 |
int len = Integer.parseInt(tk.nextToken());
|
|
339 |
assert len < b.length * 2;
|
|
340 |
System.out.println(now() + getName()
|
|
341 |
+ ": received body: "
|
|
342 |
+ new String(ccis.readNBytes(len), UTF_8));
|
|
343 |
}
|
|
344 |
System.out.println(now()
|
|
345 |
+ getName() + ": sending back " + uri);
|
|
346 |
|
|
347 |
response.append("HTTP/1.1 200 OK\r\nContent-Length: ")
|
|
348 |
.append(b.length)
|
|
349 |
.append("\r\n\r\n");
|
|
350 |
|
|
351 |
// Then send the 200 OK response to the client
|
|
352 |
System.out.println(now() + getName() + ": Sending "
|
|
353 |
+ response);
|
|
354 |
pw.print(response);
|
|
355 |
pw.flush();
|
|
356 |
ccos.write(b);
|
|
357 |
ccos.flush();
|
|
358 |
ccos.close();
|
|
359 |
connections.remove(clientConnection);
|
|
360 |
clientConnection.close();
|
|
361 |
}
|
|
362 |
} catch (Throwable t) {
|
|
363 |
if (!stopped) {
|
|
364 |
System.out.println(now() + getName() + ": failed: " + t);
|
|
365 |
t.printStackTrace();
|
|
366 |
try {
|
|
367 |
stopServer();
|
|
368 |
} catch (Throwable e) {
|
|
369 |
|
|
370 |
}
|
|
371 |
}
|
|
372 |
} finally {
|
|
373 |
System.out.println(now() + getName() + ": exiting");
|
|
374 |
}
|
|
375 |
}
|
|
376 |
|
|
377 |
void close(Socket s) {
|
|
378 |
try {
|
|
379 |
s.close();
|
|
380 |
} catch(Throwable t) {
|
|
381 |
|
|
382 |
}
|
|
383 |
}
|
|
384 |
public void stopServer() throws IOException {
|
|
385 |
stopped = true;
|
|
386 |
ss.close();
|
|
387 |
connections.forEach(this::close);
|
|
388 |
}
|
|
389 |
|
|
390 |
public String serverAuthority() {
|
|
391 |
return InetAddress.getLoopbackAddress().getHostName() + ":"
|
|
392 |
+ ss.getLocalPort();
|
|
393 |
}
|
|
394 |
|
|
395 |
static DummyServer create(InetSocketAddress sa) throws IOException {
|
|
396 |
ServerSocket ss = ServerSocketFactory.getDefault()
|
|
397 |
.createServerSocket(sa.getPort(), -1, sa.getAddress());
|
|
398 |
return new DummyServer(ss, false);
|
|
399 |
}
|
|
400 |
|
|
401 |
static DummyServer create(InetSocketAddress sa, SSLContext sslContext) throws IOException {
|
|
402 |
ServerSocket ss = sslContext.getServerSocketFactory()
|
|
403 |
.createServerSocket(sa.getPort(), -1, sa.getAddress());
|
|
404 |
return new DummyServer(ss, true);
|
|
405 |
}
|
|
406 |
|
|
407 |
|
|
408 |
}
|
|
409 |
|
|
410 |
}
|