1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.quic;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufAllocator;
20 import io.netty.buffer.Unpooled;
21 import io.netty.channel.Channel;
22 import io.netty.channel.ChannelFuture;
23 import io.netty.channel.ChannelId;
24 import io.netty.channel.ChannelMetadata;
25 import io.netty.channel.ChannelOutboundBuffer;
26 import io.netty.channel.ChannelPipeline;
27 import io.netty.channel.ChannelPromise;
28 import io.netty.channel.DefaultChannelId;
29 import io.netty.channel.DefaultChannelPipeline;
30 import io.netty.channel.EventLoop;
31 import io.netty.channel.PendingWriteQueue;
32 import io.netty.channel.RecvByteBufAllocator;
33 import io.netty.channel.VoidChannelPromise;
34 import io.netty.channel.socket.ChannelInputShutdownEvent;
35 import io.netty.channel.socket.ChannelInputShutdownReadComplete;
36 import io.netty.channel.socket.ChannelOutputShutdownException;
37 import io.netty.util.DefaultAttributeMap;
38 import io.netty.util.ReferenceCountUtil;
39 import io.netty.util.concurrent.PromiseNotifier;
40 import io.netty.util.internal.StringUtil;
41 import io.netty.util.internal.logging.InternalLogger;
42 import io.netty.util.internal.logging.InternalLoggerFactory;
43 import org.jetbrains.annotations.Nullable;
44
45 import java.net.SocketAddress;
46 import java.nio.channels.ClosedChannelException;
47 import java.util.concurrent.RejectedExecutionException;
48
49
50
51
52 final class QuicheQuicStreamChannel extends DefaultAttributeMap implements QuicStreamChannel {
53 private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
54 private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(QuicheQuicStreamChannel.class);
55 private final QuicheQuicChannel parent;
56 private final ChannelId id;
57 private final ChannelPipeline pipeline;
58 private final QuicStreamChannelUnsafe unsafe;
59 private final ChannelPromise closePromise;
60 private final PendingWriteQueue queue;
61
62 private final QuicStreamChannelConfig config;
63 private final QuicStreamAddress address;
64
65 private boolean readable;
66 private boolean readPending;
67 private boolean inRecv;
68 private boolean inWriteQueued;
69 private boolean finReceived;
70 private boolean finSent;
71 private boolean inputReset;
72
73 private volatile boolean registered;
74 private volatile boolean writable = true;
75 private volatile boolean active = true;
76 private volatile boolean inputShutdown;
77 private volatile boolean outputShutdown;
78 private volatile QuicStreamPriority priority;
79 private volatile long capacity;
80
81 QuicheQuicStreamChannel(QuicheQuicChannel parent, long streamId) {
82 this.parent = parent;
83 this.id = DefaultChannelId.newInstance();
84 unsafe = new QuicStreamChannelUnsafe();
85 this.pipeline = new DefaultChannelPipeline(this) {
86
87 };
88 config = new QuicheQuicStreamChannelConfig(this);
89 this.address = new QuicStreamAddress(streamId);
90 this.closePromise = newPromise();
91 queue = new PendingWriteQueue(this);
92
93
94 if (parent.streamType(streamId) == QuicStreamType.UNIDIRECTIONAL && parent.isStreamLocalCreated(streamId)) {
95 inputShutdown = true;
96 }
97 }
98
99 @Override
100 public QuicStreamAddress localAddress() {
101 return address;
102 }
103
104 @Override
105 public QuicStreamAddress remoteAddress() {
106 return address;
107 }
108
109 @Override
110 public boolean isLocalCreated() {
111 return parent().isStreamLocalCreated(streamId());
112 }
113
114 @Override
115 public QuicStreamType type() {
116 return parent().streamType(streamId());
117 }
118
119 @Override
120 public long streamId() {
121 return address.streamId();
122 }
123
124 @Override
125 public QuicStreamPriority priority() {
126 return priority;
127 }
128
129 @Override
130 public ChannelFuture updatePriority(QuicStreamPriority priority, ChannelPromise promise) {
131 if (eventLoop().inEventLoop()) {
132 updatePriority0(priority, promise);
133 } else {
134 eventLoop().execute(() -> updatePriority0(priority, promise));
135 }
136 return promise;
137 }
138
139 private void updatePriority0(QuicStreamPriority priority, ChannelPromise promise) {
140 assert eventLoop().inEventLoop();
141 if (!promise.setUncancellable()) {
142 return;
143 }
144 try {
145 parent().streamPriority(streamId(), (byte) priority.urgency(), priority.isIncremental());
146 } catch (Throwable cause) {
147 promise.setFailure(cause);
148 return;
149 }
150 this.priority = priority;
151 promise.setSuccess();
152 }
153
154 @Override
155 public boolean isInputShutdown() {
156 return inputShutdown;
157 }
158
159 @Override
160 public ChannelFuture shutdownOutput(ChannelPromise promise) {
161 if (eventLoop().inEventLoop()) {
162 shutdownOutput0(promise);
163 } else {
164 eventLoop().execute(() -> shutdownOutput0(promise));
165 }
166 return promise;
167 }
168
169 private void shutdownOutput0(ChannelPromise promise) {
170 assert eventLoop().inEventLoop();
171 if (!promise.setUncancellable()) {
172 return;
173 }
174 outputShutdown = true;
175 unsafe.writeWithoutCheckChannelState(QuicStreamFrame.EMPTY_FIN, promise);
176 unsafe.flush();
177 }
178
179 @Override
180 public ChannelFuture shutdownInput(int error, ChannelPromise promise) {
181 if (eventLoop().inEventLoop()) {
182 shutdownInput0(error, promise);
183 } else {
184 eventLoop().execute(() -> shutdownInput0(error, promise));
185 }
186 return promise;
187 }
188
189 @Override
190 public ChannelFuture shutdownOutput(int error, ChannelPromise promise) {
191 if (eventLoop().inEventLoop()) {
192 shutdownOutput0(error, promise);
193 } else {
194 eventLoop().execute(() -> shutdownOutput0(error, promise));
195 }
196 return promise;
197 }
198
199 @Override
200 public QuicheQuicChannel parent() {
201 return parent;
202 }
203
204 private void shutdownInput0(int err, ChannelPromise channelPromise) {
205 assert eventLoop().inEventLoop();
206 if (!channelPromise.setUncancellable()) {
207 return;
208 }
209 inputShutdown = true;
210 parent().streamShutdown(streamId(), true, false, err, channelPromise);
211 closeIfDone();
212 }
213
214 @Override
215 public boolean isOutputShutdown() {
216 return outputShutdown;
217 }
218
219 private void shutdownOutput0(int error, ChannelPromise channelPromise) {
220 assert eventLoop().inEventLoop();
221 if (!channelPromise.setUncancellable()) {
222 return;
223 }
224 parent().streamShutdown(streamId(), false, true, error, channelPromise);
225 outputShutdown = true;
226 closeIfDone();
227 }
228
229 @Override
230 public boolean isShutdown() {
231 return outputShutdown && inputShutdown;
232 }
233
234 @Override
235 public ChannelFuture shutdown(ChannelPromise channelPromise) {
236 if (eventLoop().inEventLoop()) {
237 shutdown0(channelPromise);
238 } else {
239 eventLoop().execute(() -> shutdown0(channelPromise));
240 }
241 return channelPromise;
242 }
243
244 private void shutdown0(ChannelPromise promise) {
245 assert eventLoop().inEventLoop();
246 if (!promise.setUncancellable()) {
247 return;
248 }
249 inputShutdown = true;
250 outputShutdown = true;
251 unsafe.writeWithoutCheckChannelState(QuicStreamFrame.EMPTY_FIN, unsafe.voidPromise());
252 unsafe.flush();
253 parent().streamShutdown(streamId(), true, false, 0, promise);
254 closeIfDone();
255 }
256
257 @Override
258 public ChannelFuture shutdown(int error, ChannelPromise promise) {
259 if (eventLoop().inEventLoop()) {
260 shutdown0(error, promise);
261 } else {
262 eventLoop().execute(() -> shutdown0(error, promise));
263 }
264 return promise;
265 }
266
267 private void shutdown0(int error, ChannelPromise channelPromise) {
268 assert eventLoop().inEventLoop();
269 if (!channelPromise.setUncancellable()) {
270 return;
271 }
272 inputShutdown = true;
273 outputShutdown = true;
274 parent().streamShutdown(streamId(), true, true, error, channelPromise);
275 closeIfDone();
276 }
277
278 private void sendFinIfNeeded() throws Exception {
279 if (!finSent) {
280 finSent = true;
281 parent().streamSendFin(streamId());
282 }
283 }
284
285 private boolean isInputTerminated() {
286 return finReceived || inputReset;
287 }
288
289 private void closeIfDone() {
290 if (finSent && (isInputTerminated() || type() == QuicStreamType.UNIDIRECTIONAL && isLocalCreated())) {
291 unsafe().close(unsafe().voidPromise());
292 }
293 }
294
295 private void removeStreamFromParent() {
296 if (!active && isInputTerminated()) {
297 parent().streamClosed(streamId());
298 inputShutdown = true;
299 outputShutdown = true;
300 }
301 }
302
303 @Override
304 public QuicStreamChannel flush() {
305 pipeline.flush();
306 return this;
307 }
308
309 @Override
310 public QuicStreamChannel read() {
311 pipeline.read();
312 return this;
313 }
314
315 @Override
316 public QuicStreamChannelConfig config() {
317 return config;
318 }
319
320 @Override
321 public boolean isOpen() {
322 return active;
323 }
324
325 @Override
326 public boolean isActive() {
327 return isOpen();
328 }
329
330 @Override
331 public ChannelMetadata metadata() {
332 return METADATA;
333 }
334
335 @Override
336 public ChannelId id() {
337 return id;
338 }
339
340 @Override
341 public EventLoop eventLoop() {
342 return parent.eventLoop();
343 }
344
345 @Override
346 public boolean isRegistered() {
347 return registered;
348 }
349
350 @Override
351 public ChannelFuture closeFuture() {
352 return closePromise;
353 }
354
355 @Override
356 public boolean isWritable() {
357 return writable;
358 }
359
360 @Override
361 public long bytesBeforeUnwritable() {
362
363 return Math.max(capacity, 0);
364 }
365
366 @Override
367 public long bytesBeforeWritable() {
368 if (writable) {
369 return 0;
370 }
371
372 return 8;
373 }
374
375 @Override
376 public QuicStreamChannelUnsafe unsafe() {
377 return unsafe;
378 }
379
380 @Override
381 public ChannelPipeline pipeline() {
382 return pipeline;
383 }
384
385 @Override
386 public ByteBufAllocator alloc() {
387 return config.getAllocator();
388 }
389
390 @Override
391 public int compareTo(Channel o) {
392 return id.compareTo(o.id());
393 }
394
395
396
397
398 @Override
399 public int hashCode() {
400 return id.hashCode();
401 }
402
403
404
405
406
407 @Override
408 public boolean equals(Object o) {
409 return this == o;
410 }
411
412 @Override
413 public String toString() {
414 return "[id: 0x" + id.asShortText() + ", " + address + "]";
415 }
416
417
418
419
420 boolean writable(long capacity) {
421 assert eventLoop().inEventLoop();
422 if (capacity < 0) {
423
424 if (capacity != Quiche.QUICHE_ERR_DONE) {
425 if (!queue.isEmpty()) {
426 if (capacity == Quiche.QUICHE_ERR_STREAM_STOPPED) {
427 queue.removeAndFailAll(new ChannelOutputShutdownException("STOP_SENDING frame received"));
428
429 return false;
430 } else {
431 queue.removeAndFailAll(Quiche.convertToException((int) capacity));
432 }
433 } else if (capacity == Quiche.QUICHE_ERR_STREAM_STOPPED) {
434
435 return false;
436 }
437
438 finSent = true;
439 unsafe().close(unsafe().voidPromise());
440 }
441 return false;
442 }
443 this.capacity = capacity;
444 boolean mayNeedWrite = unsafe().writeQueued();
445
446 updateWritabilityIfNeeded(this.capacity > 0);
447 return mayNeedWrite;
448 }
449
450 private void updateWritabilityIfNeeded(boolean newWritable) {
451 if (writable != newWritable) {
452 writable = newWritable;
453 pipeline.fireChannelWritabilityChanged();
454 }
455 }
456
457
458
459
460 void readable() {
461 assert eventLoop().inEventLoop();
462
463
464 readable = true;
465 if (readPending || !active) {
466 unsafe().recv();
467 }
468 }
469
470 final class QuicStreamChannelUnsafe implements Unsafe {
471
472 @SuppressWarnings("deprecation")
473 private RecvByteBufAllocator.Handle recvHandle;
474
475 private final ChannelPromise voidPromise = new VoidChannelPromise(
476 QuicheQuicStreamChannel.this, false);
477 @Override
478 public void connect(SocketAddress remote, SocketAddress local, ChannelPromise promise) {
479 assert eventLoop().inEventLoop();
480 promise.setFailure(new UnsupportedOperationException());
481 }
482
483 @SuppressWarnings("deprecation")
484 @Override
485 public RecvByteBufAllocator.Handle recvBufAllocHandle() {
486 if (recvHandle == null) {
487 recvHandle = config.getRecvByteBufAllocator().newHandle();
488 }
489 return recvHandle;
490 }
491
492 @Override
493 public SocketAddress localAddress() {
494 return address;
495 }
496
497 @Override
498 public SocketAddress remoteAddress() {
499 return address;
500 }
501
502 @Override
503 public void register(EventLoop eventLoop, ChannelPromise promise) {
504 assert eventLoop.inEventLoop();
505 if (!promise.setUncancellable()) {
506 return;
507 }
508 if (registered) {
509 promise.setFailure(new IllegalStateException());
510 return;
511 }
512 if (eventLoop != parent.eventLoop()) {
513 promise.setFailure(new IllegalArgumentException());
514 return;
515 }
516 registered = true;
517 promise.setSuccess();
518 pipeline.fireChannelRegistered();
519 pipeline.fireChannelActive();
520 }
521
522 @Override
523 public void bind(SocketAddress localAddress, ChannelPromise promise) {
524 assert eventLoop().inEventLoop();
525 if (!promise.setUncancellable()) {
526 return;
527 }
528 promise.setFailure(new UnsupportedOperationException());
529 }
530
531 @Override
532 public void disconnect(ChannelPromise promise) {
533 assert eventLoop().inEventLoop();
534 close(promise);
535 }
536
537 @Override
538 public void close(ChannelPromise promise) {
539 close(null, promise);
540 }
541
542 void close(@Nullable ClosedChannelException writeFailCause, ChannelPromise promise) {
543 assert eventLoop().inEventLoop();
544 if (!promise.setUncancellable()) {
545 return;
546 }
547 if (!active || closePromise.isDone()) {
548 if (promise.isVoid()) {
549 return;
550 }
551 closePromise.addListener(new PromiseNotifier<>(promise));
552 return;
553 }
554 active = false;
555 try {
556
557 sendFinIfNeeded();
558 } catch (Exception ignore) {
559
560 } finally {
561 if (!queue.isEmpty()) {
562
563 if (writeFailCause == null) {
564 writeFailCause = new ClosedChannelException();
565 }
566 queue.removeAndFailAll(writeFailCause);
567 }
568
569 promise.trySuccess();
570 closePromise.trySuccess();
571 if (type() == QuicStreamType.UNIDIRECTIONAL && isLocalCreated()) {
572 inputShutdown = true;
573 outputShutdown = true;
574
575
576 parent().streamClosed(streamId());
577 } else {
578 removeStreamFromParent();
579 }
580 }
581 if (inWriteQueued) {
582 invokeLater(() -> deregister(voidPromise(), true));
583 } else {
584 deregister(voidPromise(), true);
585 }
586
587
588 if (readable && !inRecv) {
589
590 recv();
591
592
593
594
595
596
597
598
599 parent().connectionSendAndFlush();
600 }
601 }
602
603 private void deregister(final ChannelPromise promise, final boolean fireChannelInactive) {
604 assert eventLoop().inEventLoop();
605 if (!promise.setUncancellable()) {
606 return;
607 }
608
609 if (!registered) {
610 promise.trySuccess();
611 return;
612 }
613
614
615
616
617
618
619
620
621
622
623 invokeLater(() -> {
624 if (fireChannelInactive) {
625 pipeline.fireChannelInactive();
626 }
627
628
629
630
631 if (registered) {
632 registered = false;
633 pipeline.fireChannelUnregistered();
634 }
635 promise.setSuccess();
636 });
637 }
638
639 private void invokeLater(Runnable task) {
640 try {
641
642
643
644
645
646
647
648
649
650
651
652 eventLoop().execute(task);
653 } catch (RejectedExecutionException e) {
654 LOGGER.warn("Can't invoke task later as EventLoop rejected it", e);
655 }
656 }
657
658 @Override
659 public void closeForcibly() {
660 assert eventLoop().inEventLoop();
661 close(unsafe().voidPromise());
662 }
663
664 @Override
665 public void deregister(ChannelPromise promise) {
666 assert eventLoop().inEventLoop();
667 deregister(promise, false);
668 }
669
670 @Override
671 public void beginRead() {
672 assert eventLoop().inEventLoop();
673 readPending = true;
674 if (readable) {
675 unsafe().recv();
676
677
678
679
680
681
682 parent().connectionSendAndFlush();
683 }
684 }
685
686 private void closeIfNeeded(boolean wasFinSent) {
687
688
689
690
691 if (!wasFinSent && QuicheQuicStreamChannel.this.finSent
692 && (type() == QuicStreamType.UNIDIRECTIONAL || isInputTerminated())) {
693
694 close(voidPromise());
695 }
696 }
697
698 boolean writeQueued() {
699 assert eventLoop().inEventLoop();
700 boolean wasFinSent = QuicheQuicStreamChannel.this.finSent;
701 inWriteQueued = true;
702 try {
703 if (queue.isEmpty()) {
704 return false;
705 }
706 boolean written = false;
707 for (;;) {
708 Object msg = queue.current();
709 if (msg == null) {
710 break;
711 }
712 try {
713 int res = write0(msg);
714 if (res == 1) {
715 queue.remove().setSuccess();
716 written = true;
717 } else if (res == 0 || res == Quiche.QUICHE_ERR_DONE) {
718 break;
719 } else if (res == Quiche.QUICHE_ERR_STREAM_STOPPED) {
720
721
722
723 queue.removeAndFailAll(
724 new ChannelOutputShutdownException("STOP_SENDING frame received"));
725 break;
726 } else {
727 queue.remove().setFailure(Quiche.convertToException(res));
728 }
729 } catch (Exception e) {
730 queue.remove().setFailure(e);
731 }
732 }
733 if (written) {
734 updateWritabilityIfNeeded(capacity > 0);
735 }
736 return written;
737 } finally {
738 closeIfNeeded(wasFinSent);
739 inWriteQueued = false;
740 }
741 }
742
743 @Override
744 public void write(Object msg, ChannelPromise promise) {
745 assert eventLoop().inEventLoop();
746 if (!promise.setUncancellable()) {
747 ReferenceCountUtil.release(msg);
748 return;
749 }
750
751
752 if (!isOpen()) {
753 queueAndFailAll(msg, promise, new ClosedChannelException());
754 } else if (finSent) {
755 queueAndFailAll(msg, promise, new ChannelOutputShutdownException("Fin was sent already"));
756 } else if (!queue.isEmpty()) {
757
758
759 try {
760 msg = filterMsg(msg);
761 } catch (UnsupportedOperationException e) {
762 ReferenceCountUtil.release(msg);
763 promise.setFailure(e);
764 return;
765 }
766
767
768 ReferenceCountUtil.touch(msg);
769 queue.add(msg, promise);
770
771
772 writeQueued();
773 } else {
774 assert queue.isEmpty();
775 writeWithoutCheckChannelState(msg, promise);
776 }
777 }
778
779 private void queueAndFailAll(Object msg, ChannelPromise promise, Throwable cause) {
780
781 ReferenceCountUtil.touch(msg);
782
783 queue.add(msg, promise);
784 queue.removeAndFailAll(cause);
785 }
786
787 private Object filterMsg(Object msg) {
788 if (msg instanceof ByteBuf) {
789 ByteBuf buffer = (ByteBuf) msg;
790 if (!buffer.isDirect()) {
791 ByteBuf tmpBuffer = alloc().directBuffer(buffer.readableBytes());
792 tmpBuffer.writeBytes(buffer, buffer.readerIndex(), buffer.readableBytes());
793 buffer.release();
794 return tmpBuffer;
795 }
796 } else if (msg instanceof QuicStreamFrame) {
797 QuicStreamFrame frame = (QuicStreamFrame) msg;
798 ByteBuf buffer = frame.content();
799 if (!buffer.isDirect()) {
800 ByteBuf tmpBuffer = alloc().directBuffer(buffer.readableBytes());
801 tmpBuffer.writeBytes(buffer, buffer.readerIndex(), buffer.readableBytes());
802 QuicStreamFrame tmpFrame = frame.replace(tmpBuffer);
803 frame.release();
804 return tmpFrame;
805 }
806 } else {
807 throw new UnsupportedOperationException(
808 "unsupported message type: " + StringUtil.simpleClassName(msg));
809 }
810 return msg;
811 }
812
813 void writeWithoutCheckChannelState(Object msg, ChannelPromise promise) {
814 try {
815 msg = filterMsg(msg);
816 } catch (UnsupportedOperationException e) {
817 ReferenceCountUtil.release(msg);
818 promise.setFailure(e);
819 return;
820 }
821
822 boolean wasFinSent = QuicheQuicStreamChannel.this.finSent;
823 boolean mayNeedWritabilityUpdate = false;
824 try {
825 int res = write0(msg);
826 if (res > 0) {
827 ReferenceCountUtil.release(msg);
828 promise.setSuccess();
829 mayNeedWritabilityUpdate = capacity == 0;
830 } else if (res == 0 || res == Quiche.QUICHE_ERR_DONE) {
831
832 ReferenceCountUtil.touch(msg);
833 queue.add(msg, promise);
834 mayNeedWritabilityUpdate = true;
835 } else if (res == Quiche.QUICHE_ERR_STREAM_STOPPED) {
836 throw new ChannelOutputShutdownException("STOP_SENDING frame received");
837 } else {
838 throw Quiche.convertToException(res);
839 }
840 } catch (Exception e) {
841 ReferenceCountUtil.release(msg);
842 promise.setFailure(e);
843 mayNeedWritabilityUpdate = capacity == 0;
844 } finally {
845 if (mayNeedWritabilityUpdate) {
846 updateWritabilityIfNeeded(false);
847 }
848 closeIfNeeded(wasFinSent);
849 }
850 }
851
852 private int write0(Object msg) throws Exception {
853 if (type() == QuicStreamType.UNIDIRECTIONAL && !isLocalCreated()) {
854 throw new UnsupportedOperationException(
855 "Writes on non-local created streams that are unidirectional are not supported");
856 }
857 if (finSent) {
858 throw new ChannelOutputShutdownException("Fin was sent already");
859 }
860
861 final boolean fin;
862 ByteBuf buffer;
863 if (msg instanceof ByteBuf) {
864 fin = false;
865 buffer = (ByteBuf) msg;
866 } else {
867 QuicStreamFrame frame = (QuicStreamFrame) msg;
868 fin = frame.hasFin();
869 buffer = frame.content();
870 }
871
872 boolean readable = buffer.isReadable();
873 if (!fin && !readable) {
874 return 1;
875 }
876
877 boolean sendSomething = false;
878 try {
879 do {
880 int res = parent().streamSend(streamId(), buffer, fin);
881
882
883 long cap = parent.streamCapacity(streamId());
884 if (cap >= 0) {
885 capacity = cap;
886 }
887 if (res < 0) {
888 return res;
889 }
890 if (readable && res == 0) {
891 return 0;
892 }
893 sendSomething = true;
894 buffer.skipBytes(res);
895 } while (buffer.isReadable());
896
897 if (fin) {
898 finSent = true;
899 outputShutdown = true;
900 }
901 return 1;
902 } finally {
903
904
905
906
907 if (sendSomething) {
908 parent.connectionSendAndFlush();
909 }
910 }
911 }
912
913 @Override
914 public void flush() {
915 assert eventLoop().inEventLoop();
916
917 }
918
919 @Override
920 public ChannelPromise voidPromise() {
921 assert eventLoop().inEventLoop();
922 return voidPromise;
923 }
924
925 @Override
926 @Nullable
927 public ChannelOutboundBuffer outboundBuffer() {
928 return null;
929 }
930
931 private void closeOnRead(ChannelPipeline pipeline, boolean readFrames) {
932 if (readFrames && finReceived && finSent) {
933 close(voidPromise());
934 } else if (config.isAllowHalfClosure()) {
935 if (finReceived) {
936
937
938 pipeline.fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
939 pipeline.fireUserEventTriggered(ChannelInputShutdownReadComplete.INSTANCE);
940 if (finSent) {
941
942
943 close(voidPromise());
944 }
945 }
946 } else {
947
948
949 close(voidPromise());
950 }
951 }
952
953 private void handleReadException(ChannelPipeline pipeline, @Nullable ByteBuf byteBuf, Throwable cause,
954 @SuppressWarnings("deprecation") RecvByteBufAllocator.Handle allocHandle,
955 boolean readFrames) {
956 if (byteBuf != null) {
957 if (byteBuf.isReadable()) {
958 pipeline.fireChannelRead(byteBuf);
959 } else {
960 byteBuf.release();
961 }
962 }
963
964 readComplete(allocHandle, pipeline);
965 pipeline.fireExceptionCaught(cause);
966 if (finReceived) {
967 closeOnRead(pipeline, readFrames);
968 }
969 }
970
971 void recv() {
972 assert eventLoop().inEventLoop();
973 if (inRecv) {
974
975
976 return;
977 }
978
979 inRecv = true;
980 try {
981 ChannelPipeline pipeline = pipeline();
982 QuicheQuicStreamChannelConfig config = (QuicheQuicStreamChannelConfig) config();
983
984
985 DirectIoByteBufAllocator allocator = config.allocator;
986 @SuppressWarnings("deprecation")
987 RecvByteBufAllocator.Handle allocHandle = this.recvBufAllocHandle();
988 boolean readFrames = config.isReadFrames();
989
990
991
992 while (active && readPending && readable) {
993 allocHandle.reset(config);
994 ByteBuf byteBuf = null;
995 QuicheQuicChannel parent = parent();
996
997
998
999 boolean readCompleteNeeded = false;
1000 boolean continueReading = true;
1001 try {
1002 while (!isInputTerminated() && continueReading) {
1003 byteBuf = allocHandle.allocate(allocator);
1004 allocHandle.attemptedBytesRead(byteBuf.writableBytes());
1005 handleRecvResult(parent.streamRecv(streamId(), byteBuf));
1006 allocHandle.lastBytesRead(byteBuf.readableBytes());
1007 if (allocHandle.lastBytesRead() <= 0) {
1008 byteBuf.release();
1009 if (finReceived && readFrames) {
1010
1011
1012 byteBuf = Unpooled.EMPTY_BUFFER;
1013 } else {
1014 byteBuf = null;
1015 break;
1016 }
1017 }
1018
1019 allocHandle.incMessagesRead(1);
1020 readCompleteNeeded = true;
1021
1022
1023
1024 readPending = false;
1025
1026 if (readFrames) {
1027 pipeline.fireChannelRead(new DefaultQuicStreamFrame(byteBuf, finReceived));
1028 } else {
1029 pipeline.fireChannelRead(byteBuf);
1030 }
1031 byteBuf = null;
1032 continueReading = allocHandle.continueReading();
1033 }
1034
1035 if (readCompleteNeeded) {
1036 readComplete(allocHandle, pipeline);
1037 }
1038 if (isInputTerminated()) {
1039 readable = false;
1040 if (finReceived) {
1041 closeOnRead(pipeline, readFrames);
1042 }
1043 }
1044 } catch (Throwable cause) {
1045 readable = false;
1046 if (cause instanceof QuicStreamResetException) {
1047 inputReset = true;
1048 inputShutdown = true;
1049 }
1050 handleReadException(pipeline, byteBuf, cause, allocHandle, readFrames);
1051 if (inputReset) {
1052 closeIfDone();
1053 }
1054 }
1055 }
1056 if (!active) {
1057 discardInput(allocator, allocHandle);
1058 }
1059 } finally {
1060
1061 inRecv = false;
1062 removeStreamFromParent();
1063 }
1064 }
1065
1066 private void handleRecvResult(QuicheQuicChannel.StreamRecvResult result) {
1067 switch (result) {
1068 case DONE:
1069
1070 readable = false;
1071 break;
1072 case FIN:
1073
1074
1075 readable = false;
1076 finReceived = true;
1077 inputShutdown = true;
1078 break;
1079 case OK:
1080 break;
1081 default:
1082 throw new Error("Unexpected StreamRecvResult: " + result);
1083 }
1084 }
1085
1086
1087
1088
1089
1090
1091 private void discardInput(DirectIoByteBufAllocator allocator,
1092 @SuppressWarnings("deprecation") RecvByteBufAllocator.Handle allocHandle) {
1093 QuicheQuicChannel parent = parent();
1094 while (readable && !isInputTerminated()) {
1095 allocHandle.reset(config());
1096 ByteBuf byteBuf = allocHandle.allocate(allocator);
1097 try {
1098 handleRecvResult(parent.streamRecv(streamId(), byteBuf));
1099 } catch (Throwable cause) {
1100
1101
1102 readable = false;
1103 if (cause instanceof QuicStreamResetException) {
1104 inputReset = true;
1105 } else {
1106 finReceived = true;
1107 }
1108 inputShutdown = true;
1109
1110
1111
1112
1113 if (!(cause instanceof ClosedChannelException)) {
1114 pipeline().fireExceptionCaught(cause);
1115 }
1116 } finally {
1117 byteBuf.release();
1118 }
1119 }
1120 }
1121
1122
1123
1124 private void readComplete(@SuppressWarnings("deprecation") RecvByteBufAllocator.Handle allocHandle,
1125 ChannelPipeline pipeline) {
1126 allocHandle.readComplete();
1127 pipeline.fireChannelReadComplete();
1128 }
1129 }
1130 }