Repository navigation
Expand file tree
/
Copy pathServerImpl.java
More file actions
1608 lines (1440 loc) · 62.2 KB
/
Copy pathServerImpl.java
File metadata and controls
1608 lines (1440 loc) · 62.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package robaho.net.httpserver;
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import robaho.net.httpserver.http2.Http2ErrorCode;
import robaho.net.httpserver.http2.Http2Exception;
import robaho.net.httpserver.http2.Http2Stats;
import robaho.net.httpserver.http2.internal.Http2Connection;
import robaho.net.httpserver.http2.internal.Http2Stream;
import robaho.net.httpserver.internal.NoSyncBufferedInputStream;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
/**
* Provides implementation for both HTTP and HTTPS
*/
class ServerImpl {
private final String protocol;
private final boolean https;
private Executor executor;
private HttpsConfigurator httpsConfig;
private final ContextList contexts;
private final ServerSocket socket;
private final Set<HttpConnection> allConnections = Collections.newSetFromMap(new ConcurrentHashMap<>());
// per-instance (was static): a JVM-global registry made every server's
// ping task ping every OTHER server's connections (N x amplification),
// let one server's ping failure close another server's live connection,
// and bled /__debug output across instances
private final Set<Http2ConnectionHandler> allHttp2Connections = Collections.newSetFromMap(new ConcurrentHashMap<>());
/**
* O(1) live connection count: deriving it from allConnections.size()
* walks the whole backing map on every accept
*/
private final java.util.concurrent.atomic.AtomicInteger connectionCount = new java.util.concurrent.atomic.AtomicInteger();
// in-flight exchanges (h1 + h2 doFilter sections): lets stop(delay) return
// as soon as the server goes idle instead of sleeping the full delay
private final java.util.concurrent.atomic.AtomicInteger activeExchanges = new java.util.concurrent.atomic.AtomicInteger();
/**
* h2 keepalive ping interval (ServerConfig.http2PingIntervalMillis):
* the reader loop schedules the task at this period and the task treats
* a connection as ping-worthy after the same window - both sites read
* the one config value. <= 0 disables the ping entirely
*/
private static final long H2_PING_INTERVAL_MILLIS = ServerConfig.http2PingIntervalMillis();
private volatile boolean finished = false;
private boolean bound = false;
private boolean started = false;
private final HttpServer wrapper;
// schedule for the timer task that's responsible for idle connection management
static final long IDLE_TIMER_TASK_SCHEDULE = ServerConfig.getIdleTimerScheduleMillis();
static final int MAX_CONNECTIONS = ServerConfig.getMaxConnections();
static final int MAX_IDLE_CONNECTIONS = ServerConfig.getMaxIdleConnections();
// schedule for the timer task that's responsible for request/response timeout
// management
static final long MAX_REQ_TIME = getTimeMillis(ServerConfig.getMaxReqTime());
// the maximum idle duration for a connection which is currently idle but has
// served
// some request in the past
static final long IDLE_INTERVAL = ServerConfig.getIdleIntervalMillis();
/**
* the connection-cleaner timer. created lazily by
* connectionRegistered(): java.util.Timer starts its thread in the
* constructor, so a server that never accepts a connection pays
* nothing for it
*/
private Timer cleanerTimer;
/**
* the scheduled connection-cleaner task, or null while this server
* has no open connections. guarded by cleanerTaskLock
*/
private TimerTask cleanerTask;
private final Object cleanerTaskLock = new Object();
/**
* separate from the cleaner timer: ping writes can block on a stalled
* peer's connection lock and must not freeze connection management.
* created lazily by h2ConnectionRegistered(): java.util.Timer starts
* its thread in the constructor, so a server that never sees an h2
* connection pays nothing for it
*/
private Timer pingTimer;
/**
* the scheduled keepalive ping task, or null while this server has no
* h2 connections. guarded by pingTaskLock
*/
private TimerTask pingTask;
private final Object pingTaskLock = new Object();
private final Logger logger;
private Thread dispatcherThread;
// statistics
private final ServerStats stats = new ServerStats();
private final Http2Stats http2Stats = new Http2Stats();
ServerImpl(HttpServer wrapper, String protocol, InetSocketAddress addr, int backlog) throws IOException {
this.protocol = protocol;
this.wrapper = wrapper;
// channel-backed so accepted sockets expose a SocketChannel (the
// sendfile fast path needs it for FileChannel.transferTo). all
// stream IO is unchanged - blocking semantics and the accept loop
// behave exactly as with a plain ServerSocket
socket = ServerSocketChannel.open().socket();
// a single shared logger: per-instance logger names (identityHashCode)
// accumulate in the LogManager forever when servers are created and
// stopped repeatedly
this.logger = System.getLogger("robaho.net.httpserver");
https = protocol.equalsIgnoreCase("https");
contexts = new ContextList();
if (addr != null) {
socket.bind(addr, backlog);
bound = true;
logger.log(Level.INFO, "server bound to " + socket.getLocalSocketAddress() + " with backlog " + backlog);
}
dispatcher = new Dispatcher();
// the connection-cleaner task is NOT scheduled here: it is attached
// lazily to its own timer on the first accepted connection and
// detached when the last one closes (see connectionRegistered), so
// an idle server has no cleaner timer thread at all
// note: the shared CachedClock Date cache is refreshed on demand
// from the response path (see CachedClock) and has no timer or
// per-instance lifecycle at all
// the h2 keepalive ping task is NOT scheduled here: it is attached
// lazily to its own timer on the first h2 connection and detached
// on the last disconnect (see h2ConnectionRegistered)
logger.log(Level.DEBUG, "HttpServer created " + protocol + " " + addr);
if (Boolean.getBoolean("robaho.net.httpserver.EnableStats")) {
createContext("/__stats", new StatsHandler());
}
if (Boolean.getBoolean("robaho.net.httpserver.EnableDebug")) {
createContext("/__debug", new DebugHandler());
}
}
private class StatsHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
var output = ("Active Connections: " + connectionCount.get() + "\n" + stats.stats() + http2Stats.stats())
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, output.length);
exchange.getResponseBody().write(output);
exchange.getResponseBody().close();
}
}
/** dump connection/stream state to the response body (and the log) */
private class DebugHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
logger.log(Level.INFO, "logging debug state, requestor " + exchange.getRemoteAddress());
StringBuilder sb = new StringBuilder(4096);
for (var connection : allConnections) {
connection.debug();
sb.append(connection).append('\n');
}
// per-instance registry (was static): dump only THIS server's
// h2 connections
for (var handler : allHttp2Connections) {
handler.debug();
}
byte[] body = sb.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
try (var os = exchange.getResponseBody()) {
os.write(body);
}
}
}
public void bind(InetSocketAddress addr, int backlog) throws IOException {
if (bound) {
throw new BindException("HttpServer already bound");
}
if (addr == null) {
throw new NullPointerException("null address");
}
socket.bind(addr, backlog);
logger.log(Level.INFO, "server bound to " + socket.getLocalSocketAddress() + " with backlog " + backlog);
bound = true;
}
public void start() {
if (!bound || started || finished) {
throw new IllegalStateException("server in wrong state");
}
if (https && httpsConfig == null) {
throw new IllegalStateException("no HttpsConfigurator set on HttpsServer");
}
if (executor == null) {
executor = new DefaultExecutor();
}
logger.log(Level.INFO, "using " + executor + " as executor");
// report the JVM-level performance features (ZGC / compact object
// headers) once; see ServerConfig.logJvmFeatures for the fallback story
ServerConfig.logJvmFeatures(logger);
dispatcherThread = new Thread(null, dispatcher, "HTTP-Dispatcher", 0, false);
started = true;
dispatcherThread.start();
}
public void setExecutor(Executor executor) {
if (started) {
throw new IllegalStateException("server already started");
}
this.executor = executor;
}
private static class DefaultExecutor implements Executor {
// virtual threads by default (JDK 21, JEP 444): connection handling is
// blocking-IO-heavy (request reads, drains, SSL handshakes) and
// thread-per-connection scales far better virtually than on the
// platform-thread pool. the old "no monitors anywhere" rule existed
// only for JEP 444 pinning; JDK 24 (JEP 491) removed it, and locks
// that need tryLock (h2 connection, websocket watchdog) keep
// ReentrantLock for that semantic, not for pinning
// opt out with robaho.net.httpserver.virtualThreads=false
private final ExecutorService executor = ServerConfig.virtualThreads()
? Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("httpserver-vt-", 0).factory())
: Executors.newCachedThreadPool();
@Override
public void execute(Runnable task) {
executor.execute(task);
}
public void shutdown() {
executor.shutdown();
}
}
public Executor getExecutor() { return executor; }
public void setHttpsConfigurator(HttpsConfigurator config) {
if (config == null) {
throw new NullPointerException("null HttpsConfigurator");
}
if (started) {
throw new IllegalStateException("server already started");
}
this.httpsConfig = config;
}
public HttpsConfigurator getHttpsConfigurator() { return httpsConfig; }
public final boolean isFinishing() { return finished; }
public void stop(int delay) {
if (delay < 0) {
throw new IllegalArgumentException("negative delay parameter");
}
logger.log(Level.INFO, "server shutting down: " + protocol);
finished = true;
try {
socket.close();
} catch (IOException e) {}
if (executor instanceof DefaultExecutor de) {
// since we created it, shut it down when stopping because it is private
de.shutdown();
}
long latest = System.currentTimeMillis() + delay * 1000L;
while (System.currentTimeMillis() < latest) {
if (activeExchanges.get() == 0 && noConnectionBusy()) {
// all in-flight exchanges completed, no connection is
// parsing or handling a request, and no new ones can start
// (finished is already set): return early instead of
// sleeping out the full delay. the busy check is required:
// activeExchanges only increments at doFilter entry, so a
// request mid-parse (or an h2 stream mid-flight) was
// invisible to the old check and was abandoned by the sweep
break;
}
// sleep the remaining interval (in coarse steps) instead of a
// fixed yield+sleep that overshoots the deadline
long remaining = latest - System.currentTimeMillis();
try {
Thread.sleep(Math.min(remaining, 200));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
// graceful h2 shutdown (RFC 7540 6.8 SHOULD): tell live h2 peers
// which streams were processed so they can retry safely on a new
// connection instead of guessing at a bare TCP close
// best-effort GOAWAY on a helper thread with a HARD bound: the
// GOAWAY write itself can block on a stalled peer's full kernel
// send buffer (verified: stop(0) hung until the peer's socket was
// force-closed) - the operator's stop() must never be hostage to a
// remote client. a skipped GOAWAY only loses the graceful-drain hint
var goawayExecutor = java.util.concurrent.Executors.newSingleThreadExecutor(r -> {
var t = new Thread(r, "h2-goaway");
t.setDaemon(true);
return t;
});
try {
for (HttpConnection c : allConnections) {
if (c.http2Connection != null) {
goawayExecutor.execute(() -> {
try {
c.http2Connection.sendGoAwayIfIdle(Http2ErrorCode.NO_ERROR);
} catch (IOException ignored) {}
});
}
}
goawayExecutor.shutdown();
goawayExecutor.awaitTermination(500, java.util.concurrent.TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
goawayExecutor.shutdownNow();
}
for (HttpConnection c : allConnections) {
c.close(false);
}
allConnections.clear();
connectionCount.set(0);
// under cleanerTaskLock: connectionRegistered() re-checks finished
// inside the same lock, so an accept racing this cancel either sees
// finished (and skips) or its timer is covered by this cancel - a
// bare racy null-check could strand a live cleaner timer past stop
synchronized (cleanerTaskLock) {
if (cleanerTimer != null) {
cleanerTimer.cancel();
}
}
// under pingTaskLock: h2ConnectionRegistered() re-checks finished
// inside the same lock, so a registration racing this cancel either
// sees finished (and skips) or its timer is covered by this cancel -
// a bare racy null-check could strand a live ping timer past stop
synchronized (pingTaskLock) {
if (pingTimer != null) {
pingTimer.cancel();
}
}
if (dispatcherThread != null && dispatcherThread != Thread.currentThread()) {
try {
dispatcherThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.log(Level.TRACE, "ServerImpl.stop: ", e);
}
}
}
Dispatcher dispatcher;
public HttpContextImpl createContext(String path, HttpHandler handler) {
if (handler == null || path == null) {
throw new NullPointerException("null handler, or path parameter");
}
HttpContextImpl context = new HttpContextImpl(protocol, path, handler, this);
contexts.add(context);
logger.log(Level.DEBUG, "context created: " + path);
return context;
}
public HttpContextImpl createContext(String path) {
if (path == null) {
throw new NullPointerException("null path parameter");
}
HttpContextImpl context = new HttpContextImpl(protocol, path, null, this);
contexts.add(context);
logger.log(Level.DEBUG, "context created: " + path);
return context;
}
public void removeContext(String path) throws IllegalArgumentException {
if (path == null) {
throw new NullPointerException("null path parameter");
}
contexts.remove(protocol, path);
logger.log(Level.DEBUG, "context removed: " + path);
}
public void removeContext(HttpContext context) throws IllegalArgumentException {
if (!(context instanceof HttpContextImpl)) {
throw new IllegalArgumentException("wrong HttpContext type");
}
contexts.remove((HttpContextImpl) context);
logger.log(Level.DEBUG, "context removed: " + context.getPath());
}
public InetSocketAddress getAddress() {
// no AccessController.doPrivileged: the socket is owned by this
// instance and reading its local address needs no privileges
return (InetSocketAddress) socket.getLocalSocketAddress();
}
/**
* The Dispatcher is responsible for accepting any connections and then
* using those connections to process incoming requests.
*/
class Dispatcher implements Runnable {
@Override
public void run() {
long backoff = 1;
while (true) {
try {
Socket s = socket.accept();
backoff = 1;
try {
executor.execute(() -> {
try {
acceptConnection(s);
} catch (IOException | RuntimeException t) {
// socket-level failures during connection setup are
// client-side noise, not server faults: an RST'd
// connection fails setTcpNoDelay with EINVAL on
// macOS ("Invalid argument") and resets during the
// preface peek surface as SocketException too.
// keep them out of the WARNING stream; anything
// else (e.g. SSL handshake problems) stays visible
Level level = t instanceof java.net.SocketException ? Level.DEBUG : Level.WARNING;
logger.log(level, "unable to accept connection", t);
try {
s.close();
} catch (IOException ex) {
// socket already dead; nothing to close
}
}
});
} catch (RuntimeException e) {
// REE is the standard overload signal; any other
// RuntimeException from a user-supplied executor
// (custom bounded pools throw ISE) used to escape and
// kill the accept loop permanently - the server kept
// "started" while accepting nothing
logger.log(Level.DEBUG, "executor rejected connection", e);
try {
s.close();
} catch (IOException closeFailed) {
// the outer IOException catch would misattribute
// a close failure as an accept failure
}
}
} catch (IOException e) {
if (isFinishing() || socket.isClosed()) {
if (!isFinishing()) {
logger.log(Level.ERROR, "socket accept failed", e);
}
return;
}
// a transient accept failure (e.g. EMFILE when the process
// runs out of file descriptors) must not kill the
// dispatcher: retry with exponential backoff so the server
// recovers once the resource is freed
logger.log(Level.ERROR, "socket accept failed, retrying in " + backoff + "ms", e);
try {
Thread.sleep(backoff);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return;
}
backoff = Math.min(backoff * 2, 1000);
}
}
}
private void acceptConnection(Socket s) throws IOException {
if (isFinishing()) {
// a queued accept task running after stop()'s connection sweep:
// the connection would be registered into the freshly swept set
// with the cleaner timer already cancelled, so nothing would
// ever close it (leaked socket + blocked exchange thread)
try {
s.close();
} catch (IOException ignored) {}
return;
}
if (logger.isLoggable(Level.TRACE)) {
logger.log(Level.TRACE, "accepted connection: " + s.toString());
}
stats.connectionCount.incrementAndGet();
if (MAX_CONNECTIONS > 0 && connectionCount.get() >= MAX_CONNECTIONS) {
// we've hit max limit of current open connections, so we go
// ahead and close this connection without processing it
try {
stats.maxConnectionsExceededCount.incrementAndGet();
logger.log(Level.WARNING, "closing accepted connection due to too many connections");
s.close();
} catch (IOException ignore) {}
return;
}
if (ServerConfig.noDelay()) {
s.setTcpNoDelay(true);
}
boolean http2 = false;
if (https) {
// for some reason, creating an SSLServerSocket and setting the default parameters would
// not work, so upgrade to a SSLSocket after connection
SSLSocketFactory ssf = httpsConfig.getSSLContext().getSocketFactory();
// autoClose=true: with false, closing the layered SSLSocket
// never closes the underlying accepted socket (JDK
// SSLSocketImpl.closeSocket only calls super.close() when
// autoClose || !isLayered()) - every HTTPS connection leaked
// its raw socket fd (CLOSE_WAIT accumulation until EMFILE)
SSLSocket sslSocket = (SSLSocket) ssf.createSocket(s, null, true);
SSLConfigurator.configure(sslSocket, httpsConfig);
sslSocket.setHandshakeApplicationProtocolSelector((_sslSocket, protocols) -> {
if (protocols.contains("h2") && ServerConfig.http2OverSSL()) {
return "h2";
}
if (protocols.contains("http/1.1")) {
return "http/1.1";
}
// RFC 7301: never answer with a protocol the client did
// not offer (a gRPC client offering only "h2" against
// http2OverSSL=false used to get "http/1.1" - strict
// OpenSSL peers abort the handshake on the mismatch).
// "" (NOT null) omits the ALPN extension from the reply:
// the JDK selector contract treats null as "no agreement"
// and answers with a fatal no_application_protocol alert,
// hard-failing the TLS handshake for every h2-only client
return "";
});
// the following forces the SSL handshake to complete in order to determine the negotiated protocol.
// the handshake is bounded so a stalled client cannot hold the connection thread indefinitely
// clamp before the int cast: a huge configured timeout
// overflowed to negative and made every https accept throw
sslSocket.setSoTimeout((int) Math.min(Math.max(ServerConfig.getSslHandshakeTimeoutMillis(), 1), Integer.MAX_VALUE));
try {
// getSession() SWALLOWS IOExceptions and returns a dummy
// invalid session on handshake failure (the JDK closes the
// socket in that case): without the validity check a dead
// socket proceeded into connection registration, and the
// finally's setSoTimeout(0) on the closed socket threw
// SocketException - misclassified as client noise at
// DEBUG, hiding every real handshake failure from the logs
if (!sslSocket.getSession().isValid()) {
throw new java.net.SocketException("SSL handshake failed");
}
} finally {
try {
sslSocket.setSoTimeout(0);
} catch (java.net.SocketException closedDuringHandshake) {
// socket already closed by the failed handshake
}
}
if ("h2".equals(sslSocket.getApplicationProtocol())) {
logger.log(Level.DEBUG, () -> "http2 connection " + sslSocket);
http2 = true;
// protocol-specific TCP_NODELAY (see ServerConfig.http2NoDelay)
sslSocket.setTcpNoDelay(ServerConfig.http2NoDelay());
} else {
logger.log(Level.DEBUG, () -> "http/1.1 connection " + sslSocket);
}
s = sslSocket;
}
HttpConnection c = new HttpConnection(s);
try {
allConnections.add(c);
connectionCount.incrementAndGet();
connectionRegistered();
if (isFinishing()) {
// stop()'s sweep may have completed between the entry
// check and this registration (the SSL handshake can
// stretch the window by seconds): nothing would ever
// close this connection - the sweep is done and the
// cleaner timer is cancelled. close it here
closeConnection(c);
return;
}
if (http2) {
if (c.getInputStream() instanceof NoSyncBufferedInputStream nis) {
nis.growBuffer();
}
Http2ConnectionHandler t = new Http2ConnectionHandler(protocol, c);
t.run();
} else {
Http1ConnectionHandler t = new Http1ConnectionHandler(protocol, c);
t.run();
}
} catch (Throwable t) {
logger.log(Level.WARNING, "Dispatcher Exception", t);
stats.handleExceptionCount.incrementAndGet();
closeConnection(c);
}
}
}
Logger getLogger() { return logger; }
/**
* true when no connection is parsing or handling a request (h1
* inRequest, or h2 streams in progress) - used by stop(delay)'s
* early-exit so mid-flight requests are not abandoned
*/
private boolean noConnectionBusy() {
for (var c : allConnections) {
if (c.inRequest || (c.http2Connection != null && c.http2Connection.requestsInProgress.get() > 0)) {
return false;
}
}
return true;
}
/**
* called when an h2 connection registers: attaches the keepalive ping
* task on the first registration, creating the timer if needed. the
* task is detached by h2ConnectionClosed() on the last disconnect, so
* a server with no h2 connections pays no per-second ping wakeups
* (previously the task fired forever from server start, pinging an
* empty registry every second).
* the timer is SEPARATE from the connection-cleaner's because the ping
* write takes the connection lock, which a stalled h2 download can
* hold in a blocking socket write for the TCP retransmission timeout;
* sharing the single-threaded cleaner timer let that freeze
* idle-close, maxReqTime and maxIdleConnections enforcement
* server-wide.
* both this and the removal path synchronize fully on pingTaskLock and
* mutate the registry BEFORE taking the lock: whichever side wins the
* lock either observes the other's registry change or leaves pingTask
* null for the latecomer to (re)schedule, so the registry can never be
* left non-empty with no task attached
*/
private void h2ConnectionRegistered() {
synchronized (pingTaskLock) {
if (finished || H2_PING_INTERVAL_MILLIS <= 0) {
return;
}
if (pingTask == null) {
if (pingTimer == null) {
pingTimer = new Timer("h2-keepalive-ping", true);
}
pingTask = createH2PingTask();
pingTimer.schedule(pingTask, H2_PING_INTERVAL_MILLIS, H2_PING_INTERVAL_MILLIS);
}
}
}
/**
* called when an h2 connection deregisters: detaches the keepalive ping
* task once the LAST h2 connection is gone, so no timer fire happens
* while the registry is empty. the timer itself survives (its thread
* parks at zero CPU on the empty queue) and is reused by the next h2
* connection; it dies only with stop()'s pingTimer.cancel()
*/
private void h2ConnectionClosed() {
if (allHttp2Connections.isEmpty()) {
synchronized (pingTaskLock) {
if (allHttp2Connections.isEmpty() && pingTask != null) {
pingTask.cancel();
pingTimer.purge();
pingTask = null;
}
}
}
}
/**
* the h2 keepalive ping task: iterates THIS server's h2 connections
* (the registry is per-instance - a JVM-global one made every server
* ping every other server's connections and let one server's ping
* failure close another's live connection)
*/
private TimerTask createH2PingTask() {
return new TimerTask() {
@Override
public void run() {
long now = System.currentTimeMillis();
for (var exchange : allHttp2Connections) {
if (exchange.connection.lastActivityTime + H2_PING_INTERVAL_MILLIS < now) {
try {
// the ping write refreshes lastActivityTime via
// the activity timer stream; restore it afterwards
// so a dead connection still appears idle to the
// cleaner. NOTE: a real activity landing inside the
// microsecond window of the ping write is clobbered
// by the restore; any live request generates
// further socket activity that re-updates the
// timestamp, so this micro-race is accepted
var before = exchange.connection.lastActivityTime;
exchange.http2.sendPing();
exchange.connection.lastActivityTime = before;
} catch (IOException ex) {
// ping failed - the connection is dead. closing
// the socket unblocks the reader thread, whose
// finally block performs the full cleanup
// management thread: no flush (a stalled peer
// must not stall keepalive detection)
exchange.connection.close(false);
}
}
}
}
};
}
private void closeConnection(HttpConnection conn) {
// the connection's own thread: deliver any pending coalesced response
closeConnection(conn, true);
}
/**
* @param flushResponse false from the cleaner/stop threads: the flush
* can block on a stalled peer's full kernel send buffer, and those
* threads must never be held hostage by a remote client
*/
private void closeConnection(HttpConnection conn, boolean flushResponse) {
logger.log(Level.TRACE, () -> "closing connection: " + conn.toString());
conn.close(flushResponse);
if (allConnections.remove(conn)) {
connectionCount.decrementAndGet();
}
connectionClosed();
}
/* used to link to 2 or more Filter.Chains together */
class LinkHandler implements HttpHandler {
Filter.Chain nextChain;
LinkHandler(Filter.Chain nextChain) {
this.nextChain = nextChain;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
nextChain.doFilter(exchange);
}
}
class Http2ConnectionHandler implements Runnable, Http2Connection.StreamHandler {
final HttpConnection connection;
final Http2Connection http2;
final String protocol;
void debug() {
// the CALLER already iterates allHttp2Connections: the loop here
// made the dump quadratic (N connections x N dumps) after the
// static-to-instance registry conversion
http2.debug();
}
Http2ConnectionHandler(String protocol, HttpConnection conn) throws IOException {
this.connection = conn;
this.protocol = protocol;
if (protocol.equals("https")) {
// the server protocol is "http"/"https" (never "https2" -
// that comparison was always false and counted every ALPN
// h2 connection as non-SSL in the stats)
if (Http2Stats.ENABLED)
http2Stats.sslConnections.incrementAndGet();
} else {
if (Http2Stats.ENABLED)
http2Stats.nonsslConnections.incrementAndGet();
}
http2 = new Http2Connection(conn, http2Stats, connection.getInputStream(), connection.getOutputStream(), this);
// let the idle cleaner reach the h2 stream buffer pool for shrinking
conn.http2Connection = http2;
}
@Override
public void run() {
allHttp2Connections.add(this);
h2ConnectionRegistered();
try {
if (!http2.hasProperPreface()) {
http2.sendGoAway(Http2ErrorCode.PROTOCOL_ERROR);
logger.log(Level.WARNING, "ServerImpl HTTP2 preface failed");
return;
}
http2.sendMySettings();
http2.handle();
} catch (Http2Exception ex) {
logger.log(Level.WARNING, "ServerImpl http2 protocol exception " + http2, ex);
} catch (IOException ex) {
stats.socketExceptionCount.incrementAndGet();
logger.log(Level.DEBUG, "end of stream " + http2);
} catch (Exception ex) {
logger.log(Level.WARNING, "ServerImpl unexpected exception handling http2 connection " + http2, ex);
} finally {
try {
logger.log(Level.DEBUG, "closing HTTP2 connection and streams " + http2);
closeConnection(connection);
http2.close();
} catch (Throwable t) {
logger.log(Level.WARNING, "error closing http2 connection " + http2, t);
}
allHttp2Connections.remove(this);
h2ConnectionClosed();
}
}
@Override
public Executor getExecutor() { return ServerImpl.this.executor; }
@Override
public void handleStream(Http2Stream stream, InputStream in, OutputStream out) throws IOException {
connection.requestCount.incrementAndGet();
if (ServerStats.ENABLED)
stats.requestCount.incrementAndGet();
if (Http2Stats.ENABLED)
http2Stats.totalStreams.incrementAndGet();
var request = stream.getRequestHeaders();
var response = stream.getResponseHeaders();
String scheme = https ? "https" : "http";
String authority = request.getFirst(":authority");
String path = request.getFirst(":path");
String query = request.getFirst(":query");
logger.log(Level.TRACE, () -> "http2 stream started " + stream);
if (authority == null || path == null) {
throw new IOException("Invalid HTTP/2 headers: missing :authority or :path");
}
// the query string is part of :path in HTTP/2 (RFC 7540 8.1.2.3);
// there is no :query pseudo header, so split it off if present
if (query == null) {
int q = path.indexOf('?');
if (q >= 0) {
query = path.substring(q + 1);
path = path.substring(0, q);
}
}
request.set("Host", authority);
URI uri;
try {
uri = new URI(scheme, authority, path, query, null);
} catch (URISyntaxException ex) {
throw new IOException("invalid uri", ex);
}
String method = request.getFirst(":method");
if (method == null) {
throw new IOException("Invalid HTTP/2 headers: missing :method");
}
// Validate Transfer-Encoding headers for HTTP/2
List<String> transferEncoding = request.get("Transfer-encoding");
if (transferEncoding != null && !transferEncoding.isEmpty()) {
if (transferEncoding.size() > 1 || !transferEncoding.get(0).equalsIgnoreCase("chunked")) {
throw new IOException("Unsupported Transfer-Encoding value");
}
}
// opt-in request body cap: reject a declared Content-Length up
// front (bodies without a declared length are bounded
// incrementally in the stream's DATA path)
long bodySizeLimit = ServerConfig.getMaxRequestBodySize();
if (bodySizeLimit > 0) {
String contentLength = request.getFirst("content-length");
if (contentLength != null) {
try {
if (Long.parseLong(contentLength) > bodySizeLimit) {
rejectStream(stream, out, "413");
return;
}
} catch (NumberFormatException ignored) {
// malformed content-length: the stream-level
// expectedSize check rejects it on END_STREAM
}
}
}
// null-check, not Optional.ofNullable: a fresh Optional per request is
// pure allocation on the dispatch hot path
String uriPath = uri.getPath();
if (uriPath == null) {
uriPath = "/";
}
HttpContextImpl ctx = contexts.findContext(protocol, uriPath);
if (ctx == null) {
logger.log(Level.DEBUG, "No context found for request " + uriPath + ", rejecting as not found");
rejectStream(stream, out, "404");
return;
}
if (ctx.getHandler() == null) {
// h1 parity: a context without a handler gets a 500 there
// (ServerImpl's h1 path checks this); h2 NPE'd inside the
// filter chain instead, resetting the stream with
// INTERNAL_ERROR and logging a WARNING
logger.log(Level.WARNING, "no handler configured for context " + uriPath);
rejectStream(stream, out, "500");
return;
}
logger.log(Level.TRACE, () -> "http2 request on " + connection + " " + method + " for " + uri);
try {
// doFilterTracked is the SINGLE counting site for the
// in-flight exchange counter (h1 counts there too) - the old
// outer increment/finally here double-counted every h2 request
doFilterTracked(buildChain(ctx), new Http2ExchangeImpl(stream, uri, method, ctx, request, response, in, out));
} catch (IOException e) {