View Javadoc
1   /*
2    * Copyright 2020 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * {@link QuicStreamChannel} implementation that uses <a href="https://github.com/cloudflare/quiche">quiche</a>.
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              // TODO: add some overrides maybe ?
87          };
88          config = new QuicheQuicStreamChannelConfig(this);
89          this.address = new QuicStreamAddress(streamId);
90          this.closePromise = newPromise();
91          queue = new PendingWriteQueue(this);
92          // Local created unidirectional streams have the input shutdown by spec. There will never be any data for
93          // these to be read.
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         // Capacity might be negative if the stream was closed.
363         return Math.max(capacity, 0);
364     }
365 
366     @Override
367     public long bytesBeforeWritable() {
368         if (writable) {
369             return 0;
370         }
371         // Just return something positive for now
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      * Returns the ID of this channel.
397      */
398     @Override
399     public int hashCode() {
400         return id.hashCode();
401     }
402 
403     /**
404      * Returns {@code true} if and only if the specified object is identical
405      * with this channel (i.e: {@code this == o}).
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      * Stream writability changed.
419      */
420     boolean writable(long capacity) {
421         assert eventLoop().inEventLoop();
422         if (capacity < 0) {
423             // If the value is negative its a quiche error.
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                         // If STOP_SENDING is received we should not close the channel but just fail all queued writes.
429                         return false;
430                     } else {
431                         queue.removeAndFailAll(Quiche.convertToException((int) capacity));
432                     }
433                 } else if (capacity == Quiche.QUICHE_ERR_STREAM_STOPPED) {
434                     // If STOP_SENDING is received we should not close the channel
435                     return false;
436                 }
437                 // IF this error was not QUICHE_ERR_STREAM_STOPPED we should close the channel.
438                 finSent = true;
439                 unsafe().close(unsafe().voidPromise());
440             }
441             return false;
442         }
443         this.capacity = capacity;
444         boolean mayNeedWrite = unsafe().writeQueued();
445         // we need to re-read this.capacity as writeQueued() may update the capacity.
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      * Stream is readable.
459      */
460     void readable() {
461         assert eventLoop().inEventLoop();
462         // Mark as readable and if a read is pending execute it. If the channel was closed already, what is left
463         // must be dropped, see QuicStreamChannelUnsafe.recv().
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                 // Close the channel and fail the queued messages in all cases.
557                 sendFinIfNeeded();
558             } catch (Exception ignore) {
559                 // Just ignore
560             } finally {
561                 if (!queue.isEmpty()) {
562                     // Only fail if the queue is non-empty.
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                     // If its an unidirectional stream and was created locally it is safe to close the stream now as
575                     // we will never receive data from the other side.
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             // If we are in recv() already, it drops what is left once the loop is done and the parent flushes after
587             // it processed the received packets.
588             if (readable && !inRecv) {
589                 // Drop what is left to read, see recv().
590                 recv();
591 
592                 // As the stream was readable, and we called recv() ourselves we also need to call
593                 // connectionSendAndFlush(). This is needed as recv() consumes data and so a window update frame
594                 // might be produced. If close() was not triggered while processing received packets (for example
595                 // by a timeout or a cancellation from another task) nobody else will send it. If we miss to call
596                 // connectionSendAndFlush() the remote peer may not learn about the new credit and so might never
597                 // send more data, on this stream or on the connection.
598                 // See also https://docs.rs/quiche/latest/quiche/struct.Connection.html#method.send.
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             // As a user may call deregister() from within any method while doing processing in the ChannelPipeline,
615             // we need to ensure we do the actual deregister operation later. This is needed as for example,
616             // we may be in the ByteToMessageDecoder.callDecode(...) method and so still try to do processing in
617             // the old EventLoop while the user already registered the Channel to a new EventLoop. Without delay,
618             // the deregister operation this could lead to have a handler invoked by different EventLoop and so
619             // threads.
620             //
621             // See:
622             // https://github.com/netty/netty/issues/4435
623             invokeLater(() -> {
624                 if (fireChannelInactive) {
625                     pipeline.fireChannelInactive();
626                 }
627                 // Some transports like local and AIO does not allow the deregistration of
628                 // an open channel.  Their doDeregister() calls close(). Consequently,
629                 // close() calls deregister() again - no need to fire channelUnregistered, so check
630                 // if it was registered.
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                 // This method is used by outbound operation implementations to trigger an inbound event later.
642                 // They do not trigger an inbound event immediately because an outbound operation might have been
643                 // triggered by another inbound event handler method.  If fired immediately, the call stack
644                 // will look like this for example:
645                 //
646                 //   handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection.
647                 //   -> handlerA.ctx.close()
648                 //      -> channel.unsafe.close()
649                 //         -> handlerA.channelInactive() - (2) another inbound handler method called while in (1) yet
650                 //
651                 // which means the execution of two inbound handler methods of the same handler overlap undesirably.
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                 // As the stream was readable, and we called recv() ourselves we also need to call
678                 // connectionSendAndFlush(). This is needed as recv() might consume data and so a window update
679                 // frame might be produced. If we miss to call connectionSendAndFlush() we might never send the update
680                 // to the remote peer and so the remote peer might never attempt to send more data.
681                 // See also https://docs.rs/quiche/latest/quiche/struct.Connection.html#method.send.
682                 parent().connectionSendAndFlush();
683             }
684         }
685 
686         private void closeIfNeeded(boolean wasFinSent) {
687             // Let's check if we should close the channel now.
688             // If it's a unidirectional channel we can close it as there will be no fin that we can read
689             // from the remote peer. If its an bidirectional channel we should only close the channel if we
690             // also received the fin from the remote peer.
691             if (!wasFinSent && QuicheQuicStreamChannel.this.finSent
692                     && (type() == QuicStreamType.UNIDIRECTIONAL || isInputTerminated())) {
693                 // close the channel now
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                             // Once its signaled that the stream is stopped we can just fail everything.
721                             // That said we should not close the channel yet as there might be some data that is
722                             // not read yet by the user.
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             // Check first if the Channel is in a state in which it will accept writes, if not fail everything
751             // with the right exception
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                 // If the queue is not empty we should just add the message to the queue as we will drain
758                 // it later once the stream becomes writable again.
759                 try {
760                     msg = filterMsg(msg);
761                 } catch (UnsupportedOperationException e) {
762                     ReferenceCountUtil.release(msg);
763                     promise.setFailure(e);
764                     return;
765                 }
766 
767                 // Touch the message to make things easier in terms of debugging buffer leaks.
768                 ReferenceCountUtil.touch(msg);
769                 queue.add(msg, promise);
770 
771                 // Try again to write queued messages.
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             // Touch the message to make things easier in terms of debugging buffer leaks.
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                     // Touch the message to make things easier in terms of debugging buffer leaks.
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                     // Update the capacity as well.
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                 // As we called quiche_conn_stream_send(...) we need to ensure we will call quiche_conn_send(...) either
904                 // now or we will do so once we see the channelReadComplete event.
905                 //
906                 // See https://docs.rs/quiche/0.6.0/quiche/struct.Connection.html#method.send
907                 if (sendSomething) {
908                     parent.connectionSendAndFlush();
909                 }
910             }
911         }
912 
913         @Override
914         public void flush() {
915             assert eventLoop().inEventLoop();
916             // NOOP.
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                     // If we receive a fin there will be no more data to read so we need to fire both events
937                     // to be consistent with other transports.
938                     pipeline.fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
939                     pipeline.fireUserEventTriggered(ChannelInputShutdownReadComplete.INSTANCE);
940                     if (finSent) {
941                         // This was an unidirectional stream which means as soon as we received FIN and sent a FIN
942                         // we need close the connection.
943                         close(voidPromise());
944                     }
945                 }
946             } else {
947                 // This was an unidirectional stream which means as soon as we received FIN we need
948                 // close the connection.
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                 // As the use may call read() we need to guard against reentrancy here as otherwise it could
975                 // be possible that we re-enter this method while still processing it.
976                 return;
977             }
978 
979             inRecv = true;
980             try {
981                 ChannelPipeline pipeline = pipeline();
982                 QuicheQuicStreamChannelConfig config = (QuicheQuicStreamChannelConfig) config();
983                 // Directly access the DirectIoByteBufAllocator as we need an direct buffer to read into in all cases
984                 // even if there is no Unsafe present and the direct buffer is not pooled.
985                 DirectIoByteBufAllocator allocator = config.allocator;
986                 @SuppressWarnings("deprecation")
987                 RecvByteBufAllocator.Handle allocHandle = this.recvBufAllocHandle();
988                 boolean readFrames = config.isReadFrames();
989 
990                 // We should loop as long as a read() was requested and there is anything left to read, which means the
991                 // stream was marked as readable before.
992                 while (active && readPending && readable) {
993                     allocHandle.reset(config);
994                     ByteBuf byteBuf = null;
995                     QuicheQuicChannel parent = parent();
996                     // It's possible that the stream was marked as finish while we iterated over the readable streams
997                     // or while we did have auto read disabled. If so we need to ensure we not try to read from it as it
998                     // would produce an error.
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                                     // If we read QuicStreamFrames we should fire an frame through the pipeline
1011                                     // with an empty buffer but the fin flag set to true.
1012                                     byteBuf = Unpooled.EMPTY_BUFFER;
1013                                 } else {
1014                                     byteBuf = null;
1015                                     break;
1016                                 }
1017                             }
1018                             // We did read one message.
1019                             allocHandle.incMessagesRead(1);
1020                             readCompleteNeeded = true;
1021 
1022                             // It's important that we reset this to false before we call fireChannelRead(...)
1023                             // as the user may request another read() from channelRead(...) callback.
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                 // About to leave the method lets reset so we can enter it again.
1061                 inRecv = false;
1062                 removeStreamFromParent();
1063             }
1064         }
1065 
1066         private void handleRecvResult(QuicheQuicChannel.StreamRecvResult result) {
1067             switch (result) {
1068                 case DONE:
1069                     // Nothing left to read;
1070                     readable = false;
1071                     break;
1072                 case FIN:
1073                     // If we received a FIN we also should mark the channel as non-readable as
1074                     // there is nothing left to read really.
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          * The channel was closed before the end of the stream was read. Read and drop what is left: as long as quiche
1088          * holds the data it keeps its connection flow control credit, and the stream is never completed and collected,
1089          * so its stream credit is never returned to the remote peer either.
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                     // The stream was reset by the remote peer or the connection was closed, there is nothing left
1101                     // to read.
1102                     readable = false;
1103                     if (cause instanceof QuicStreamResetException) {
1104                         inputReset = true;
1105                     } else {
1106                         finReceived = true;
1107                     }
1108                     inputShutdown = true;
1109                     // A ClosedChannelException means the connection was closed or freed already. This is expected
1110                     // when the streams are closed as part of closing the connection, and the user is notified about
1111                     // the closure of the stream and the connection anyway, so there is no need to fire it. Everything
1112                     // else is reported as the data that was dropped is lost.
1113                     if (!(cause instanceof ClosedChannelException)) {
1114                         pipeline().fireExceptionCaught(cause);
1115                     }
1116                 } finally {
1117                     byteBuf.release();
1118                 }
1119             }
1120         }
1121 
1122         // Read was complete and something was read, so we we need to reset the readPending flags, the allocHandle
1123         // and call fireChannelReadComplete(). The user may schedule another read now.
1124         private void readComplete(@SuppressWarnings("deprecation") RecvByteBufAllocator.Handle allocHandle,
1125                                   ChannelPipeline pipeline) {
1126             allocHandle.readComplete();
1127             pipeline.fireChannelReadComplete();
1128         }
1129     }
1130 }