/
HTTP3StreamConnection.java
537 lines (487 loc) · 16.9 KB
/
HTTP3StreamConnection.java
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
//
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.http3.internal;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http3.api.Stream;
import org.eclipse.jetty.http3.frames.DataFrame;
import org.eclipse.jetty.http3.frames.HeadersFrame;
import org.eclipse.jetty.http3.internal.parser.MessageParser;
import org.eclipse.jetty.http3.internal.parser.ParserListener;
import org.eclipse.jetty.io.AbstractConnection;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.RetainableByteBuffer;
import org.eclipse.jetty.io.RetainableByteBufferPool;
import org.eclipse.jetty.quic.common.QuicStreamEndPoint;
import org.eclipse.jetty.util.thread.AutoLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class HTTP3StreamConnection extends AbstractConnection
{
private static final Logger LOG = LoggerFactory.getLogger(HTTP3StreamConnection.class);
// An empty DATA frame is the sequence of bytes [0x0, 0x0].
private static final ByteBuffer EMPTY_DATA_FRAME = ByteBuffer.allocate(2);
private final AutoLock lock = new AutoLock();
private final RetainableByteBufferPool buffers;
private final MessageParser parser;
private boolean useInputDirectByteBuffers = true;
private RetainableByteBuffer buffer;
private boolean applicationMode;
private boolean parserDataMode;
private boolean dataDemand;
private boolean dataStalled;
private DataFrame dataFrame;
private boolean dataLast;
private boolean noData;
private boolean remotelyClosed;
public HTTP3StreamConnection(QuicStreamEndPoint endPoint, Executor executor, ByteBufferPool byteBufferPool, MessageParser parser)
{
super(endPoint, executor);
this.buffers = RetainableByteBufferPool.findOrAdapt(null, byteBufferPool);
this.parser = parser;
parser.init(MessageListener::new);
}
@Override
public QuicStreamEndPoint getEndPoint()
{
return (QuicStreamEndPoint)super.getEndPoint();
}
public boolean isUseInputDirectByteBuffers()
{
return useInputDirectByteBuffers;
}
public void setUseInputDirectByteBuffers(boolean useInputDirectByteBuffers)
{
this.useInputDirectByteBuffers = useInputDirectByteBuffers;
}
public void setApplicationMode(boolean mode)
{
this.applicationMode = mode;
}
@Override
public void onOpen()
{
super.onOpen();
fillInterested();
}
@Override
public void onClose(Throwable cause)
{
tryReleaseBuffer(true);
super.onClose(cause);
}
@Override
protected boolean onReadTimeout(Throwable timeout)
{
// Idle timeouts are handled by HTTP3Stream.
return false;
}
@Override
public void onFillable()
{
if (LOG.isDebugEnabled())
LOG.debug("processing parserDataMode={} on {}", parserDataMode, this);
if (parserDataMode)
processDataFrames();
else
processNonDataFrames();
}
private void processDataFrames()
{
processDataDemand();
if (!parserDataMode)
{
if (hasBuffer() && buffer.hasRemaining())
processNonDataFrames();
else
fillInterested();
}
}
private void processNonDataFrames()
{
try
{
tryAcquireBuffer();
while (true)
{
if (parseAndFill(true) == MessageParser.Result.NO_FRAME)
{
tryReleaseBuffer(false);
return;
}
// TODO: we should also exit if the connection was closed due to errors.
// There is not yet a isClosed() primitive though.
if (remotelyClosed)
{
// We have detected the end of the stream,
// do not loop around to fill & parse again.
// However, the last frame may have
// caused a write that we need to flush.
getEndPoint().getQuicSession().flush();
tryReleaseBuffer(false);
return;
}
if (parserDataMode)
{
if (buffer.hasRemaining())
{
processDataFrames();
}
else
{
if (applicationMode)
{
if (LOG.isDebugEnabled())
LOG.debug("skipping fill interest on {}", this);
}
else
{
if (LOG.isDebugEnabled())
LOG.debug("setting fill interest on {}", this);
fillInterested();
}
tryReleaseBuffer(false);
}
return;
}
}
}
catch (Throwable x)
{
tryReleaseBuffer(true);
long error = HTTP3ErrorCode.REQUEST_CANCELLED_ERROR.code();
getEndPoint().close(error, x);
// Notify the application that a failure happened.
parser.getListener().onStreamFailure(getEndPoint().getStreamId(), error, x);
}
}
protected abstract void onDataAvailable(long streamId);
public Stream.Data readData()
{
try
{
if (LOG.isDebugEnabled())
LOG.debug("reading data on {}", this);
tryAcquireBuffer();
switch (parseAndFill(false))
{
case FRAME:
{
if (parserDataMode)
{
DataFrame frame = dataFrame;
dataFrame = null;
if (LOG.isDebugEnabled())
LOG.debug("read data {} on {}", frame, this);
buffer.retain();
// Store in a local variable so that the lambda captures the right buffer.
RetainableByteBuffer current = buffer;
// Release the network buffer here (if empty), since the application may
// not be reading more bytes, to avoid to keep around a consumed buffer.
tryReleaseBuffer(false);
return new Stream.Data(frame, () -> completeReadData(current));
}
else
{
// Not anymore in data mode, so it's a trailer frame.
tryReleaseBuffer(false);
return null;
}
}
case MODE_SWITCH:
{
if (LOG.isDebugEnabled())
LOG.debug("switching to parserDataMode=false on {}", this);
dataLast = true;
parserDataMode = false;
parser.setDataMode(false);
tryReleaseBuffer(false);
return null;
}
case NO_FRAME:
{
if (LOG.isDebugEnabled())
LOG.debug("read no data on {}", this);
tryReleaseBuffer(false);
return null;
}
default:
{
throw new IllegalStateException();
}
}
}
catch (Throwable x)
{
cancelDemand();
tryReleaseBuffer(true);
getEndPoint().close(HTTP3ErrorCode.REQUEST_CANCELLED_ERROR.code(), x);
// Rethrow so the application has a chance to handle it.
throw x;
}
}
private void completeReadData(RetainableByteBuffer buffer)
{
buffer.release();
if (LOG.isDebugEnabled())
LOG.debug("released retained {}", buffer);
}
public void demand()
{
boolean hasData;
boolean process = false;
try (AutoLock l = lock.lock())
{
hasData = !noData;
dataDemand = true;
if (dataStalled && hasData)
{
dataStalled = false;
process = true;
}
}
if (LOG.isDebugEnabled())
LOG.debug("demand, wasStalled={} hasData={} on {}", process, hasData, this);
if (process)
processDataFrames();
else if (!hasData)
fillInterested();
}
public boolean hasDemand()
{
try (AutoLock l = lock.lock())
{
return dataDemand;
}
}
private void cancelDemand()
{
try (AutoLock l = lock.lock())
{
dataDemand = false;
}
}
private boolean isStalled()
{
try (AutoLock l = lock.lock())
{
return dataStalled;
}
}
private void setNoData(boolean noData)
{
try (AutoLock l = lock.lock())
{
this.noData = noData;
}
}
private void processDataDemand()
{
while (true)
{
boolean process = true;
try (AutoLock l = lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug("processing demand={}, last={} fillInterested={} on {}", dataDemand, dataLast, isFillInterested(), this);
if (dataDemand)
{
// Do not process if the last frame was already
// notified, or if there is demand but no data.
if (dataLast || isFillInterested())
process = false;
else
dataDemand = false;
}
else
{
dataStalled = true;
process = false;
}
}
if (!process)
return;
onDataAvailable(getEndPoint().getStreamId());
}
}
private void tryAcquireBuffer()
{
if (!hasBuffer())
{
buffer = buffers.acquire(getInputBufferSize(), isUseInputDirectByteBuffers());
if (LOG.isDebugEnabled())
LOG.debug("acquired {}", buffer);
}
}
private void tryReleaseBuffer(boolean force)
{
if (hasBuffer())
{
if (buffer.hasRemaining() && force)
buffer.clear();
if (!buffer.hasRemaining())
{
buffer.release();
if (LOG.isDebugEnabled())
LOG.debug("released {}", buffer);
buffer = null;
}
}
}
public boolean hasBuffer()
{
return buffer != null;
}
private MessageParser.Result parseAndFill(boolean setFillInterest)
{
try
{
if (LOG.isDebugEnabled())
LOG.debug("parse+fill setFillInterest={} on {} with buffer {}", setFillInterest, this, buffer);
setNoData(false);
while (true)
{
ByteBuffer byteBuffer = buffer.getBuffer();
MessageParser.Result result = parser.parse(byteBuffer);
if (LOG.isDebugEnabled())
LOG.debug("parsed {} on {} with buffer {}", result, this, buffer);
if (result == MessageParser.Result.FRAME || result == MessageParser.Result.MODE_SWITCH)
return result;
if (buffer.isRetained())
{
buffer.release();
RetainableByteBuffer newBuffer = buffers.acquire(getInputBufferSize(), isUseInputDirectByteBuffers());
if (LOG.isDebugEnabled())
LOG.debug("reacquired {} for retained {}", newBuffer, buffer);
buffer = newBuffer;
byteBuffer = buffer.getBuffer();
}
int filled = fill(byteBuffer);
if (LOG.isDebugEnabled())
LOG.debug("filled {} on {} with buffer {}", filled, this, buffer);
if (filled > 0)
continue;
if (filled == 0)
{
// Workaround for a Quiche glitch, that sometimes reports
// an HTTP/3 frame with last=false, but a subsequent read
// of zero bytes reports that the stream is finished.
if (!remotelyClosed && getEndPoint().isStreamFinished())
{
if (LOG.isDebugEnabled())
LOG.debug("detected end of stream on {}", this);
parser.parse(EMPTY_DATA_FRAME.slice());
return MessageParser.Result.FRAME;
}
setNoData(true);
if (setFillInterest)
fillInterested();
}
return MessageParser.Result.NO_FRAME;
}
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("parse+fill failure on {}", this, x);
throw x;
}
}
private int fill(ByteBuffer byteBuffer)
{
try
{
return getEndPoint().fill(byteBuffer);
}
catch (IOException x)
{
throw new UncheckedIOException(x.getMessage(), x);
}
}
@Override
public String toConnectionString()
{
return String.format("%s[demand=%b,stalled=%b,parserDataMode=%b]", super.toConnectionString(), hasDemand(), isStalled(), parserDataMode);
}
private class MessageListener extends ParserListener.Wrapper
{
private MessageListener(ParserListener listener)
{
super(listener);
}
@Override
public void onHeaders(long streamId, HeadersFrame frame)
{
MetaData metaData = frame.getMetaData();
if (metaData.isRequest())
{
// Expect DATA frames now.
parserDataMode = true;
parser.setDataMode(true);
if (LOG.isDebugEnabled())
LOG.debug("switching to parserDataMode=true for request {} on {}", metaData, this);
}
else if (metaData.isResponse())
{
MetaData.Response response = (MetaData.Response)metaData;
if (HttpStatus.isInformational(response.getStatus()))
{
if (LOG.isDebugEnabled())
LOG.debug("staying in parserDataMode=false for response {} on {}", metaData, this);
}
else
{
// Expect DATA frames now.
parserDataMode = true;
parser.setDataMode(true);
if (LOG.isDebugEnabled())
LOG.debug("switching to parserDataMode=true for response {} on {}", metaData, this);
}
}
else
{
// Trailer.
if (!frame.isLast())
frame = new HeadersFrame(metaData, true);
}
if (frame.isLast())
shutdownInput();
super.onHeaders(streamId, frame);
}
@Override
public void onData(long streamId, DataFrame frame)
{
if (dataFrame != null)
throw new IllegalStateException();
dataFrame = frame;
if (frame.isLast())
{
dataLast = true;
shutdownInput();
}
super.onData(streamId, frame);
}
private void shutdownInput()
{
remotelyClosed = true;
// We want to shutdown the input to avoid "spurious" wakeups where
// zero bytes could be spuriously read from the EndPoint after the
// stream is remotely closed by receiving a frame with last=true.
getEndPoint().shutdownInput(HTTP3ErrorCode.NO_ERROR.code());
}
}
}