36131
|
1 |
/*
|
|
2 |
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
|
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
|
4 |
*
|
|
5 |
* This code is free software; you can redistribute it and/or modify it
|
|
6 |
* under the terms of the GNU General Public License version 2 only, as
|
|
7 |
* published by the Free Software Foundation. Oracle designates this
|
|
8 |
* particular file as subject to the "Classpath" exception as provided
|
|
9 |
* by Oracle in the LICENSE file that accompanied this code.
|
|
10 |
*
|
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT
|
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that
|
|
15 |
* accompanied this code).
|
|
16 |
*
|
|
17 |
* You should have received a copy of the GNU General Public License version
|
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation,
|
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
20 |
*
|
|
21 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
|
22 |
* or visit www.oracle.com if you need additional information or have any
|
|
23 |
*/
|
|
24 |
package java.net.http;
|
|
25 |
|
|
26 |
import java.io.IOException;
|
|
27 |
import java.net.Authenticator;
|
|
28 |
import java.net.CookieManager;
|
|
29 |
import java.net.ProxySelector;
|
|
30 |
import java.net.URI;
|
|
31 |
import static java.net.http.Utils.BUFSIZE;
|
|
32 |
import java.nio.ByteBuffer;
|
|
33 |
import java.nio.channels.SelectableChannel;
|
|
34 |
import java.nio.channels.SelectionKey;
|
|
35 |
import static java.nio.channels.SelectionKey.OP_CONNECT;
|
|
36 |
import static java.nio.channels.SelectionKey.OP_READ;
|
|
37 |
import static java.nio.channels.SelectionKey.OP_WRITE;
|
|
38 |
import java.nio.channels.Selector;
|
|
39 |
import java.util.LinkedList;
|
|
40 |
import java.util.List;
|
|
41 |
import java.util.Set;
|
|
42 |
import java.util.concurrent.ExecutorService;
|
|
43 |
import java.security.NoSuchAlgorithmException;
|
|
44 |
import java.util.ListIterator;
|
|
45 |
import java.util.Optional;
|
|
46 |
import java.util.concurrent.Executors;
|
|
47 |
import java.util.concurrent.ThreadFactory;
|
|
48 |
import javax.net.ssl.SSLContext;
|
|
49 |
import javax.net.ssl.SSLParameters;
|
|
50 |
|
|
51 |
/**
|
|
52 |
* Client implementation. Contains all configuration information and also
|
|
53 |
* the selector manager thread which allows async events to be registered
|
|
54 |
* and delivered when they occur. See AsyncEvent.
|
|
55 |
*/
|
|
56 |
class HttpClientImpl extends HttpClient implements BufferHandler {
|
|
57 |
|
|
58 |
private final CookieManager cookieManager;
|
|
59 |
private final Redirect followRedirects;
|
|
60 |
private final ProxySelector proxySelector;
|
|
61 |
private final Authenticator authenticator;
|
|
62 |
private final Version version;
|
|
63 |
private boolean pipelining = false;
|
|
64 |
private final ConnectionPool connections;
|
|
65 |
private final ExecutorWrapper executor;
|
|
66 |
// Security parameters
|
|
67 |
private final SSLContext sslContext;
|
|
68 |
private final SSLParameters sslParams;
|
|
69 |
private final SelectorManager selmgr;
|
|
70 |
private final FilterFactory filters;
|
|
71 |
private final Http2ClientImpl client2;
|
|
72 |
private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
|
|
73 |
private final LinkedList<TimeoutEvent> timeouts;
|
|
74 |
|
|
75 |
//@Override
|
|
76 |
void debugPrint() {
|
|
77 |
selmgr.debugPrint();
|
|
78 |
client2.debugPrint();
|
|
79 |
}
|
|
80 |
|
|
81 |
public static HttpClientImpl create(HttpClientBuilderImpl builder) {
|
|
82 |
HttpClientImpl impl = new HttpClientImpl(builder);
|
|
83 |
impl.start();
|
|
84 |
return impl;
|
|
85 |
}
|
|
86 |
|
|
87 |
private HttpClientImpl(HttpClientBuilderImpl builder) {
|
|
88 |
if (builder.sslContext == null) {
|
|
89 |
try {
|
|
90 |
sslContext = SSLContext.getDefault();
|
|
91 |
} catch (NoSuchAlgorithmException ex) {
|
|
92 |
throw new InternalError(ex);
|
|
93 |
}
|
|
94 |
} else {
|
|
95 |
sslContext = builder.sslContext;
|
|
96 |
}
|
|
97 |
ExecutorService ex = builder.executor;
|
|
98 |
if (ex == null) {
|
|
99 |
ex = Executors.newCachedThreadPool((r) -> {
|
|
100 |
Thread t = defaultFactory.newThread(r);
|
|
101 |
t.setDaemon(true);
|
|
102 |
return t;
|
|
103 |
});
|
|
104 |
} else {
|
|
105 |
ex = builder.executor;
|
|
106 |
}
|
|
107 |
client2 = new Http2ClientImpl(this);
|
|
108 |
executor = ExecutorWrapper.wrap(ex);
|
|
109 |
cookieManager = builder.cookieManager;
|
|
110 |
followRedirects = builder.followRedirects == null ?
|
|
111 |
Redirect.NEVER : builder.followRedirects;
|
|
112 |
this.proxySelector = builder.proxy;
|
|
113 |
authenticator = builder.authenticator;
|
|
114 |
version = builder.version;
|
|
115 |
sslParams = builder.sslParams;
|
|
116 |
connections = new ConnectionPool();
|
|
117 |
connections.start();
|
|
118 |
timeouts = new LinkedList<>();
|
|
119 |
try {
|
|
120 |
selmgr = new SelectorManager();
|
|
121 |
} catch (IOException e) {
|
|
122 |
// unlikely
|
|
123 |
throw new InternalError(e);
|
|
124 |
}
|
|
125 |
selmgr.setDaemon(true);
|
|
126 |
selmgr.setName("HttpSelector");
|
|
127 |
filters = new FilterFactory();
|
|
128 |
initFilters();
|
|
129 |
}
|
|
130 |
|
|
131 |
private void start() {
|
|
132 |
selmgr.start();
|
|
133 |
}
|
|
134 |
|
|
135 |
/**
|
|
136 |
* Wait for activity on given exchange (assuming blocking = false).
|
|
137 |
* It's a no-op if blocking = true. In particular, the following occurs
|
|
138 |
* in the SelectorManager thread.
|
|
139 |
*
|
|
140 |
* 1) mark the connection non-blocking
|
|
141 |
* 2) add to selector
|
|
142 |
* 3) If selector fires for this exchange then
|
|
143 |
* 4) - mark connection as blocking
|
|
144 |
* 5) - call AsyncEvent.handle()
|
|
145 |
*
|
|
146 |
* If exchange needs to block again, then call registerEvent() again
|
|
147 |
*/
|
|
148 |
void registerEvent(AsyncEvent exchange) throws IOException {
|
|
149 |
selmgr.register(exchange);
|
|
150 |
}
|
|
151 |
|
|
152 |
Http2ClientImpl client2() {
|
|
153 |
return client2;
|
|
154 |
}
|
|
155 |
|
|
156 |
LinkedList<ByteBuffer> freelist = new LinkedList<>();
|
|
157 |
|
|
158 |
@Override
|
|
159 |
public synchronized ByteBuffer getBuffer() {
|
|
160 |
if (freelist.isEmpty()) {
|
|
161 |
return ByteBuffer.allocate(BUFSIZE);
|
|
162 |
}
|
|
163 |
return freelist.removeFirst();
|
|
164 |
}
|
|
165 |
|
|
166 |
@Override
|
|
167 |
public synchronized void returnBuffer(ByteBuffer buffer) {
|
|
168 |
buffer.clear();
|
|
169 |
freelist.add(buffer);
|
|
170 |
}
|
|
171 |
|
|
172 |
|
|
173 |
// Main loop for this client's selector
|
|
174 |
|
|
175 |
class SelectorManager extends Thread {
|
|
176 |
|
|
177 |
final Selector selector;
|
|
178 |
boolean closed;
|
|
179 |
|
|
180 |
final List<AsyncEvent> readyList;
|
|
181 |
final List<AsyncEvent> registrations;
|
|
182 |
|
|
183 |
List<AsyncEvent> debugList;
|
|
184 |
|
|
185 |
SelectorManager() throws IOException {
|
|
186 |
readyList = new LinkedList<>();
|
|
187 |
registrations = new LinkedList<>();
|
|
188 |
debugList = new LinkedList<>();
|
|
189 |
selector = Selector.open();
|
|
190 |
}
|
|
191 |
|
|
192 |
// This returns immediately. So caller not allowed to send/receive
|
|
193 |
// on connection.
|
|
194 |
|
|
195 |
synchronized void register(AsyncEvent e) throws IOException {
|
|
196 |
registrations.add(e);
|
|
197 |
selector.wakeup();
|
|
198 |
}
|
|
199 |
|
|
200 |
void wakeupSelector() {
|
|
201 |
selector.wakeup();
|
|
202 |
}
|
|
203 |
|
|
204 |
synchronized void shutdown() {
|
|
205 |
closed = true;
|
|
206 |
try {
|
|
207 |
selector.close();
|
|
208 |
} catch (IOException e) {}
|
|
209 |
}
|
|
210 |
|
|
211 |
private List<AsyncEvent> copy(List<AsyncEvent> list) {
|
|
212 |
LinkedList<AsyncEvent> c = new LinkedList<>();
|
|
213 |
for (AsyncEvent e : list) {
|
|
214 |
c.add(e);
|
|
215 |
}
|
|
216 |
return c;
|
|
217 |
}
|
|
218 |
|
|
219 |
synchronized void debugPrint() {
|
|
220 |
System.err.println("Selecting on:");
|
|
221 |
for (AsyncEvent e : debugList) {
|
|
222 |
System.err.println(opvals(e.interestOps()));
|
|
223 |
}
|
|
224 |
}
|
|
225 |
|
|
226 |
String opvals(int i) {
|
|
227 |
StringBuilder sb = new StringBuilder();
|
|
228 |
if ((i & OP_READ) != 0)
|
|
229 |
sb.append("OP_READ ");
|
|
230 |
if ((i & OP_CONNECT) != 0)
|
|
231 |
sb.append("OP_CONNECT ");
|
|
232 |
if ((i & OP_WRITE) != 0)
|
|
233 |
sb.append("OP_WRITE ");
|
|
234 |
return sb.toString();
|
|
235 |
}
|
|
236 |
|
|
237 |
@Override
|
|
238 |
public void run() {
|
|
239 |
try {
|
|
240 |
while (true) {
|
|
241 |
synchronized (this) {
|
|
242 |
debugList = copy(registrations);
|
|
243 |
for (AsyncEvent exchange : registrations) {
|
|
244 |
SelectableChannel c = exchange.channel();
|
|
245 |
try {
|
|
246 |
c.configureBlocking(false);
|
|
247 |
c.register(selector,
|
|
248 |
exchange.interestOps(),
|
|
249 |
exchange);
|
|
250 |
} catch (IOException e) {
|
|
251 |
Log.logError("HttpClientImpl: " + e);
|
|
252 |
c.close();
|
|
253 |
// let the exchange deal with it
|
|
254 |
handleEvent(exchange);
|
|
255 |
}
|
|
256 |
}
|
|
257 |
registrations.clear();
|
|
258 |
}
|
|
259 |
long timeval = getTimeoutValue();
|
|
260 |
long now = System.currentTimeMillis();
|
|
261 |
int n = selector.select(timeval);
|
|
262 |
if (n == 0) {
|
|
263 |
signalTimeouts(now);
|
|
264 |
continue;
|
|
265 |
}
|
|
266 |
Set<SelectionKey> keys = selector.selectedKeys();
|
|
267 |
|
|
268 |
for (SelectionKey key : keys) {
|
|
269 |
if (key.isReadable() || key.isConnectable() || key.isWritable()) {
|
|
270 |
key.cancel();
|
|
271 |
AsyncEvent exchange = (AsyncEvent) key.attachment();
|
|
272 |
readyList.add(exchange);
|
|
273 |
}
|
|
274 |
}
|
|
275 |
selector.selectNow(); // complete cancellation
|
|
276 |
selector.selectedKeys().clear();
|
|
277 |
|
|
278 |
for (AsyncEvent exchange : readyList) {
|
|
279 |
if (exchange instanceof AsyncEvent.Blocking) {
|
|
280 |
exchange.channel().configureBlocking(true);
|
|
281 |
} else {
|
|
282 |
assert exchange instanceof AsyncEvent.NonBlocking;
|
|
283 |
}
|
|
284 |
executor.synchronize();
|
|
285 |
handleEvent(exchange); // will be delegated to executor
|
|
286 |
}
|
|
287 |
readyList.clear();
|
|
288 |
}
|
|
289 |
} catch (Throwable e) {
|
|
290 |
if (!closed) {
|
|
291 |
System.err.println("HttpClientImpl terminating on error");
|
|
292 |
// This terminates thread. So, better just print stack trace
|
|
293 |
String err = Utils.stackTrace(e);
|
|
294 |
Log.logError("HttpClientImpl: fatal error: " + err);
|
|
295 |
}
|
|
296 |
}
|
|
297 |
}
|
|
298 |
|
|
299 |
void handleEvent(AsyncEvent e) {
|
|
300 |
if (closed) {
|
|
301 |
e.abort();
|
|
302 |
} else {
|
|
303 |
e.handle();
|
|
304 |
}
|
|
305 |
}
|
|
306 |
}
|
|
307 |
|
|
308 |
/**
|
|
309 |
* Creates a HttpRequest associated with this group.
|
|
310 |
*
|
|
311 |
* @throws IllegalStateException if the group has been stopped
|
|
312 |
*/
|
|
313 |
@Override
|
|
314 |
public HttpRequestBuilderImpl request() {
|
|
315 |
return new HttpRequestBuilderImpl(this, null);
|
|
316 |
}
|
|
317 |
|
|
318 |
/**
|
|
319 |
* Creates a HttpRequest associated with this group.
|
|
320 |
*
|
|
321 |
* @throws IllegalStateException if the group has been stopped
|
|
322 |
*/
|
|
323 |
@Override
|
|
324 |
public HttpRequestBuilderImpl request(URI uri) {
|
|
325 |
return new HttpRequestBuilderImpl(this, uri);
|
|
326 |
}
|
|
327 |
|
|
328 |
@Override
|
|
329 |
public SSLContext sslContext() {
|
|
330 |
Utils.checkNetPermission("getSSLContext");
|
|
331 |
return sslContext;
|
|
332 |
}
|
|
333 |
|
|
334 |
@Override
|
|
335 |
public Optional<SSLParameters> sslParameters() {
|
|
336 |
return Optional.ofNullable(sslParams);
|
|
337 |
}
|
|
338 |
|
|
339 |
@Override
|
|
340 |
public Optional<Authenticator> authenticator() {
|
|
341 |
return Optional.ofNullable(authenticator);
|
|
342 |
}
|
|
343 |
|
|
344 |
@Override
|
|
345 |
public ExecutorService executorService() {
|
|
346 |
return executor.userExecutor();
|
|
347 |
}
|
|
348 |
|
|
349 |
ExecutorWrapper executorWrapper() {
|
|
350 |
return executor;
|
|
351 |
}
|
|
352 |
|
|
353 |
@Override
|
|
354 |
public boolean pipelining() {
|
|
355 |
return this.pipelining;
|
|
356 |
}
|
|
357 |
|
|
358 |
ConnectionPool connectionPool() {
|
|
359 |
return connections;
|
|
360 |
}
|
|
361 |
|
|
362 |
@Override
|
|
363 |
public Redirect followRedirects() {
|
|
364 |
return followRedirects;
|
|
365 |
}
|
|
366 |
|
|
367 |
|
|
368 |
@Override
|
|
369 |
public Optional<CookieManager> cookieManager() {
|
|
370 |
return Optional.ofNullable(cookieManager);
|
|
371 |
}
|
|
372 |
|
|
373 |
@Override
|
|
374 |
public Optional<ProxySelector> proxy() {
|
|
375 |
return Optional.ofNullable(this.proxySelector);
|
|
376 |
}
|
|
377 |
|
|
378 |
@Override
|
|
379 |
public Version version() {
|
|
380 |
return version;
|
|
381 |
}
|
|
382 |
|
|
383 |
//private final HashMap<String, Boolean> http2NotSupported = new HashMap<>();
|
|
384 |
|
|
385 |
boolean getHttp2Allowed() {
|
|
386 |
return version.equals(Version.HTTP_2);
|
|
387 |
}
|
|
388 |
|
|
389 |
//void setHttp2NotSupported(String host) {
|
|
390 |
//http2NotSupported.put(host, false);
|
|
391 |
//}
|
|
392 |
|
|
393 |
final void initFilters() {
|
|
394 |
addFilter(AuthenticationFilter.class);
|
|
395 |
addFilter(RedirectFilter.class);
|
|
396 |
}
|
|
397 |
|
|
398 |
final void addFilter(Class<? extends HeaderFilter> f) {
|
|
399 |
filters.addFilter(f);
|
|
400 |
}
|
|
401 |
|
|
402 |
final List<HeaderFilter> filterChain() {
|
|
403 |
return filters.getFilterChain();
|
|
404 |
}
|
|
405 |
|
|
406 |
// Timer controls. Timers are implemented through timed Selector.select()
|
|
407 |
// calls.
|
|
408 |
synchronized void registerTimer(TimeoutEvent event) {
|
|
409 |
long elapse = event.timevalMillis();
|
|
410 |
ListIterator<TimeoutEvent> iter = timeouts.listIterator();
|
|
411 |
long listval = 0;
|
|
412 |
event.delta = event.timeval; // in case list empty
|
|
413 |
TimeoutEvent next;
|
|
414 |
while (iter.hasNext()) {
|
|
415 |
next = iter.next();
|
|
416 |
listval += next.delta;
|
|
417 |
if (elapse < listval) {
|
|
418 |
listval -= next.delta;
|
|
419 |
event.delta = elapse - listval;
|
|
420 |
next.delta -= event.delta;
|
|
421 |
iter.previous();
|
|
422 |
break;
|
|
423 |
} else if (!iter.hasNext()) {
|
|
424 |
event.delta = event.timeval - listval ;
|
|
425 |
}
|
|
426 |
}
|
|
427 |
iter.add(event);
|
|
428 |
//debugPrintList("register");
|
|
429 |
selmgr.wakeupSelector();
|
|
430 |
}
|
|
431 |
|
|
432 |
void debugPrintList(String s) {
|
|
433 |
System.err.printf("%s: {", s);
|
|
434 |
for (TimeoutEvent e : timeouts) {
|
|
435 |
System.err.printf("(%d,%d) ", e.delta, e.timeval);
|
|
436 |
}
|
|
437 |
System.err.println("}");
|
|
438 |
}
|
|
439 |
|
|
440 |
synchronized void signalTimeouts(long then) {
|
|
441 |
if (timeouts.isEmpty()) {
|
|
442 |
return;
|
|
443 |
}
|
|
444 |
long now = System.currentTimeMillis();
|
|
445 |
long duration = now - then;
|
|
446 |
ListIterator<TimeoutEvent> iter = timeouts.listIterator();
|
|
447 |
TimeoutEvent event = iter.next();
|
|
448 |
long delta = event.delta;
|
|
449 |
if (duration < delta) {
|
|
450 |
event.delta -= duration;
|
|
451 |
return;
|
|
452 |
}
|
|
453 |
event.handle();
|
|
454 |
iter.remove();
|
|
455 |
while (iter.hasNext()) {
|
|
456 |
event = iter.next();
|
|
457 |
if (event.delta == 0) {
|
|
458 |
event.handle();
|
|
459 |
iter.remove();
|
|
460 |
} else {
|
|
461 |
event.delta += delta;
|
|
462 |
break;
|
|
463 |
}
|
|
464 |
}
|
|
465 |
//debugPrintList("signalTimeouts");
|
|
466 |
}
|
|
467 |
|
|
468 |
synchronized void cancelTimer(TimeoutEvent event) {
|
|
469 |
ListIterator<TimeoutEvent> iter = timeouts.listIterator();
|
|
470 |
while (iter.hasNext()) {
|
|
471 |
TimeoutEvent ev = iter.next();
|
|
472 |
if (event == ev) {
|
|
473 |
if (iter.hasNext()) {
|
|
474 |
// adjust
|
|
475 |
TimeoutEvent next = iter.next();
|
|
476 |
next.delta += ev.delta;
|
|
477 |
iter.previous();
|
|
478 |
}
|
|
479 |
iter.remove();
|
|
480 |
}
|
|
481 |
}
|
|
482 |
}
|
|
483 |
|
|
484 |
// used for the connection window
|
|
485 |
int getReceiveBufferSize() {
|
|
486 |
return Utils.getIntegerNetProperty(
|
|
487 |
"sun.net.httpclient.connectionWindowSize", 256 * 1024
|
|
488 |
);
|
|
489 |
}
|
|
490 |
|
|
491 |
// returns 0 meaning block forever, or a number of millis to block for
|
|
492 |
synchronized long getTimeoutValue() {
|
|
493 |
if (timeouts.isEmpty()) {
|
|
494 |
return 0;
|
|
495 |
} else {
|
|
496 |
return timeouts.get(0).delta;
|
|
497 |
}
|
|
498 |
}
|
|
499 |
}
|