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.Unpooled;
20  import io.netty.channel.AbstractChannel;
21  import io.netty.channel.Channel;
22  import io.netty.channel.ChannelFuture;
23  import io.netty.channel.ChannelFutureListener;
24  import io.netty.channel.ChannelHandler;
25  import io.netty.channel.ChannelHandlerContext;
26  import io.netty.channel.ChannelMetadata;
27  import io.netty.channel.ChannelOption;
28  import io.netty.channel.ChannelOutboundBuffer;
29  import io.netty.channel.ChannelPipeline;
30  import io.netty.channel.ChannelPromise;
31  import io.netty.channel.ConnectTimeoutException;
32  import io.netty.channel.DefaultChannelPipeline;
33  import io.netty.channel.EventLoop;
34  import io.netty.channel.RecvByteBufAllocator;
35  import io.netty.channel.socket.DatagramPacket;
36  import io.netty.handler.ssl.ClientAuth;
37  import io.netty.handler.ssl.SniCompletionEvent;
38  import io.netty.handler.ssl.SslHandshakeCompletionEvent;
39  import io.netty.util.AttributeKey;
40  import io.netty.util.collection.LongObjectHashMap;
41  import io.netty.util.collection.LongObjectMap;
42  import io.netty.util.concurrent.Future;
43  import io.netty.util.concurrent.ImmediateEventExecutor;
44  import io.netty.util.concurrent.ImmediateExecutor;
45  import io.netty.util.concurrent.Promise;
46  import io.netty.util.internal.StringUtil;
47  import io.netty.util.internal.logging.InternalLogger;
48  import io.netty.util.internal.logging.InternalLoggerFactory;
49  import org.jetbrains.annotations.Nullable;
50  
51  import javax.net.ssl.SSLEngine;
52  import javax.net.ssl.SSLHandshakeException;
53  import javax.net.ssl.SSLPeerUnverifiedException;
54  import java.io.File;
55  import java.net.ConnectException;
56  import java.net.InetSocketAddress;
57  import java.net.SocketAddress;
58  import java.nio.BufferUnderflowException;
59  import java.nio.ByteBuffer;
60  import java.nio.channels.AlreadyConnectedException;
61  import java.nio.channels.ClosedChannelException;
62  import java.nio.channels.ConnectionPendingException;
63  import java.util.ArrayList;
64  import java.util.Collections;
65  import java.util.HashSet;
66  import java.util.List;
67  import java.util.Map;
68  import java.util.Set;
69  import java.util.concurrent.Executor;
70  import java.util.concurrent.ScheduledFuture;
71  import java.util.concurrent.TimeUnit;
72  import java.util.concurrent.atomic.AtomicLongFieldUpdater;
73  import java.util.function.Consumer;
74  import java.util.function.Function;
75  
76  /**
77   * {@link QuicChannel} implementation that uses <a href="https://github.com/cloudflare/quiche">quiche</a>.
78   */
79  final class QuicheQuicChannel extends AbstractChannel implements QuicChannel {
80      private static final InternalLogger logger = InternalLoggerFactory.getInstance(QuicheQuicChannel.class);
81      private static final String QLOG_FILE_EXTENSION = ".qlog";
82  
83      enum StreamRecvResult {
84          /**
85           * Nothing more to read from the stream.
86           */
87          DONE,
88          /**
89           * FIN flag received.
90           */
91          FIN,
92          /**
93           * Normal read without FIN flag.
94           */
95          OK
96      }
97  
98      private enum ChannelState {
99          OPEN,
100         ACTIVE,
101         CLOSED
102     }
103 
104     private enum SendResult {
105         SOME,
106         NONE,
107         CLOSE
108     }
109 
110     private static final class CloseData implements ChannelFutureListener {
111         final boolean applicationClose;
112         final int err;
113         final ByteBuf reason;
114 
115         CloseData(boolean applicationClose, int err, ByteBuf reason) {
116             this.applicationClose = applicationClose;
117             this.err = err;
118             this.reason = reason;
119         }
120 
121         @Override
122         public void operationComplete(ChannelFuture future) {
123             reason.release();
124         }
125     }
126 
127     private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
128     private long[] readableStreams = new long[4];
129     private long[] writableStreams = new long[4];
130     private final LongObjectMap<QuicheQuicStreamChannel> streams = new LongObjectHashMap<>();
131     private final QuicheQuicChannelConfig config;
132     private final boolean server;
133     private final QuicStreamIdGenerator idGenerator;
134     private final ChannelHandler streamHandler;
135     private final Map.Entry<ChannelOption<?>, Object>[] streamOptionsArray;
136     private final Map.Entry<AttributeKey<?>, Object>[] streamAttrsArray;
137     private final TimeoutHandler timeoutHandler;
138     private final QuicConnectionIdGenerator connectionIdAddressGenerator;
139     private final QuicResetTokenGenerator resetTokenGenerator;
140     private final Set<ByteBuffer> sourceConnectionIds = new HashSet<>();
141 
142     private Consumer<QuicheQuicChannel> freeTask;
143     private Executor sslTaskExecutor;
144     private boolean inFireChannelReadCompleteQueue;
145     private boolean fireChannelReadCompletePending;
146     private ByteBuf finBuffer;
147     private ByteBuf outErrorCodeBuffer;
148     private ChannelPromise connectPromise;
149     private ScheduledFuture<?> connectTimeoutFuture;
150     private QuicConnectionAddress connectLocalAddress;
151     private QuicConnectionAddress connectRemoteAddress;
152     private CloseData closeData;
153     private QuicConnectionCloseEvent connectionCloseEvent;
154     private QuicConnectionStats statsAtClose;
155     private boolean supportsDatagram;
156     private boolean recvDatagramPending;
157     private boolean datagramReadable;
158     private boolean recvStreamPending;
159     private boolean streamReadable;
160     private boolean handshakeCompletionNotified;
161     private boolean earlyDataReadyNotified;
162     private int reantranceGuard;
163     private static final int IN_RECV = 1 << 1;
164     private static final int IN_CONNECTION_SEND = 1 << 2;
165     private static final int IN_HANDLE_WRITABLE_STREAMS = 1 << 3;
166     private volatile ChannelState state = ChannelState.OPEN;
167     private volatile boolean timedOut;
168     private volatile String traceId;
169     private volatile QuicheQuicConnection connection;
170     private volatile InetSocketAddress local;
171     private volatile InetSocketAddress remote;
172 
173     private final ChannelFutureListener continueSendingListener = f -> {
174         if (connectionSend(connection) != SendResult.NONE) {
175             flushParent();
176         }
177     };
178 
179     private static final AtomicLongFieldUpdater<QuicheQuicChannel> UNI_STREAMS_LEFT_UPDATER =
180             AtomicLongFieldUpdater.newUpdater(QuicheQuicChannel.class, "uniStreamsLeft");
181     private volatile long uniStreamsLeft;
182 
183     private static final AtomicLongFieldUpdater<QuicheQuicChannel> BIDI_STREAMS_LEFT_UPDATER =
184             AtomicLongFieldUpdater.newUpdater(QuicheQuicChannel.class, "bidiStreamsLeft");
185     private volatile long bidiStreamsLeft;
186 
187     // Whether the cached stream credits were refreshed from quiche at least once. Only updated
188     // and accessed from the event loop thread, so it needs no synchronization. Before the
189     // first refresh the caches are 0 even though the peer may have announced credits, so the
190     // fail-fast check in connectStream(...) must not fire yet; a rejected implicit open in
191     // that window is instead handled by rolling back the allocated stream id.
192     private boolean streamCreditsInitialized;
193 
194     private QuicheQuicChannel(Channel parent, boolean server, @Nullable ByteBuffer key, InetSocketAddress local,
195                               InetSocketAddress remote, boolean supportsDatagram, ChannelHandler streamHandler,
196                               Map.Entry<ChannelOption<?>, Object>[] streamOptionsArray,
197                               Map.Entry<AttributeKey<?>, Object>[] streamAttrsArray,
198                               @Nullable Consumer<QuicheQuicChannel> freeTask,
199                               @Nullable Executor sslTaskExecutor,
200                               @Nullable QuicConnectionIdGenerator connectionIdAddressGenerator,
201                               @Nullable QuicResetTokenGenerator resetTokenGenerator) {
202         super(parent);
203         config = new QuicheQuicChannelConfig(this);
204         this.freeTask = freeTask;
205         this.server = server;
206         this.idGenerator = new QuicStreamIdGenerator(server);
207         this.connectionIdAddressGenerator = connectionIdAddressGenerator;
208         this.resetTokenGenerator = resetTokenGenerator;
209         if (key != null) {
210             this.sourceConnectionIds.add(key);
211         }
212 
213         this.supportsDatagram = supportsDatagram;
214         this.local = local;
215         this.remote = remote;
216 
217         this.streamHandler = streamHandler;
218         this.streamOptionsArray = streamOptionsArray;
219         this.streamAttrsArray = streamAttrsArray;
220         timeoutHandler = new TimeoutHandler();
221         this.sslTaskExecutor = sslTaskExecutor == null ? ImmediateExecutor.INSTANCE : sslTaskExecutor;
222     }
223 
224     static QuicheQuicChannel forClient(Channel parent, InetSocketAddress local, InetSocketAddress remote,
225                                        ChannelHandler streamHandler,
226                                        Map.Entry<ChannelOption<?>, Object>[] streamOptionsArray,
227                                        Map.Entry<AttributeKey<?>, Object>[] streamAttrsArray) {
228         return new QuicheQuicChannel(parent, false, null, local, remote, false, streamHandler,
229                 streamOptionsArray, streamAttrsArray, null, null, null, null);
230     }
231 
232     static QuicheQuicChannel forServer(Channel parent, ByteBuffer key, InetSocketAddress local,
233                                        InetSocketAddress remote,
234                                        boolean supportsDatagram, ChannelHandler streamHandler,
235                                        Map.Entry<ChannelOption<?>, Object>[] streamOptionsArray,
236                                        Map.Entry<AttributeKey<?>, Object>[] streamAttrsArray,
237                                        Consumer<QuicheQuicChannel> freeTask, Executor sslTaskExecutor,
238                                        QuicConnectionIdGenerator connectionIdAddressGenerator,
239                                        QuicResetTokenGenerator resetTokenGenerator) {
240         return new QuicheQuicChannel(parent, true, key, local, remote, supportsDatagram,
241                 streamHandler, streamOptionsArray, streamAttrsArray, freeTask,
242                 sslTaskExecutor, connectionIdAddressGenerator, resetTokenGenerator);
243     }
244 
245     private static final int MAX_ARRAY_LEN = 128;
246 
247     private static long[] growIfNeeded(long[] array, int maxLength) {
248         if (maxLength > array.length) {
249             if (array.length == MAX_ARRAY_LEN) {
250                 return array;
251             }
252             // Increase by 4 until we reach MAX_ARRAY_LEN
253             return new long[Math.min(MAX_ARRAY_LEN, array.length + 4)];
254         }
255         return array;
256     }
257 
258     @Override
259     public boolean isTimedOut() {
260         return timedOut;
261     }
262 
263     @Override
264     public SSLEngine sslEngine() {
265         QuicheQuicConnection connection = this.connection;
266         return connection == null ? null : connection.engine();
267     }
268 
269     private void notifyAboutHandshakeCompletionIfNeeded(QuicheQuicConnection conn,
270                                                         @Nullable SSLHandshakeException cause) {
271         if (handshakeCompletionNotified) {
272             return;
273         }
274         if (cause != null) {
275             pipeline().fireUserEventTriggered(new SslHandshakeCompletionEvent(cause));
276             return;
277         }
278         if (conn.isFreed()) {
279             return;
280         }
281         switch (connection.engine().getHandshakeStatus()) {
282             case NOT_HANDSHAKING:
283             case FINISHED:
284                 SSLHandshakeException rejection = rejectIfClientCertificateRequiredButMissing(connection.engine());
285                 if (rejection != null) {
286                     handshakeCompletionNotified = true;
287                     pipeline().fireUserEventTriggered(new SslHandshakeCompletionEvent(rejection));
288                     // Terminate the connection with the "certificate_required" TLS alert (RFC 8446, Section 6.2)
289                     // mapped to a QUIC CRYPTO_ERROR (RFC 9000, Section 4.8): 0x100 + alert code.
290                     close(false, 0x100 + 116, Unpooled.EMPTY_BUFFER, newPromise());
291                     return;
292                 }
293                 handshakeCompletionNotified = true;
294                 pipeline().fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
295                 break;
296             default:
297                 break;
298         }
299     }
300 
301     /**
302      * Defense in depth for https://github.com/netty/netty/security/advisories/GHSA-6xv6-9mgg-mfvc : a client
303      * certificate is not re-requested when a session is resumed (e.g. via a session ticket), so a session which
304      * was established without a client certificate under a more lenient {@link ClientAuth} configuration must
305      * never be allowed to satisfy {@link ClientAuth#REQUIRE} here, even if the underlying native library would
306      * otherwise consider the (abbreviated) handshake successful.
307      */
308     @Nullable
309     private static SSLHandshakeException rejectIfClientCertificateRequiredButMissing(QuicheQuicSslEngine engine) {
310         if (engine.getUseClientMode() || engine.ctx.clientAuth != ClientAuth.REQUIRE) {
311             return null;
312         }
313         try {
314             if (engine.getSession().getPeerCertificates().length > 0) {
315                 return null;
316             }
317         } catch (SSLPeerUnverifiedException e) {
318             // Fall through, no client certificate was presented.
319         }
320         return new SSLHandshakeException(
321                 "client did not present a certificate, but is required to under ClientAuth.REQUIRE");
322     }
323 
324     @Override
325     public long peerAllowedStreams(QuicStreamType type) {
326         switch (type) {
327             case BIDIRECTIONAL:
328                 return bidiStreamsLeft;
329             case UNIDIRECTIONAL:
330                 return uniStreamsLeft;
331             default:
332                 return 0;
333         }
334     }
335 
336     void attachQuicheConnection(QuicheQuicConnection connection) {
337         this.connection = connection;
338 
339         byte[] traceId = Quiche.quiche_conn_trace_id(connection.address());
340         if (traceId != null) {
341             this.traceId = new String(traceId);
342         }
343 
344         connection.init(local, remote,
345                 sniHostname -> pipeline().fireUserEventTriggered(new SniCompletionEvent(sniHostname)));
346 
347         // Setup QLOG if needed.
348         QLogConfiguration configuration = config.getQLogConfiguration();
349         if (configuration != null) {
350             final String fileName;
351             File file = new File(configuration.path());
352             if (file.isDirectory()) {
353                 // Create directory if needed.
354                 file.mkdir();
355                 if (this.traceId != null) {
356                     fileName = configuration.path() + File.separatorChar + this.traceId + "-" +
357                             id().asShortText() + QLOG_FILE_EXTENSION;
358                 } else {
359                     fileName = configuration.path() + File.separatorChar + id().asShortText() + QLOG_FILE_EXTENSION;
360                 }
361             } else {
362                 fileName = configuration.path();
363             }
364 
365             if (!Quiche.quiche_conn_set_qlog_path(connection.address(), fileName,
366                     configuration.logTitle(), configuration.logDescription())) {
367                 logger.info("Unable to create qlog file: {} ", fileName);
368             }
369         }
370     }
371 
372     void connectNow(Function<QuicChannel, ? extends QuicSslEngine> engineProvider, Executor sslTaskExecutor,
373                     Consumer<QuicheQuicChannel> freeTask, long configAddr, int localConnIdLength,
374                     boolean supportsDatagram, ByteBuffer fromSockaddrMemory, ByteBuffer toSockaddrMemory)
375             throws Exception {
376         assert this.connection == null;
377         assert this.traceId == null;
378         assert this.sourceConnectionIds.isEmpty();
379 
380         this.sslTaskExecutor = sslTaskExecutor;
381         this.freeTask = freeTask;
382 
383         QuicConnectionAddress connectLocalAddress = this.connectLocalAddress;
384 
385         if (connectLocalAddress == QuicConnectionAddress.EPHEMERAL) {
386             connectLocalAddress = QuicConnectionAddress.random(localConnIdLength);
387         }
388         ByteBuffer localConnectId = connectLocalAddress.id();
389         if (localConnectId.remaining() != localConnIdLength) {
390             failConnectPromiseAndThrow(new IllegalArgumentException("connectionAddress has length "
391                     + localConnectId.remaining()
392                     + " instead of " + localConnIdLength));
393         }
394         QuicConnectionAddress connectRemoteAddress = this.connectRemoteAddress;
395 
396         QuicSslEngine engine = engineProvider.apply(this);
397         if (!(engine instanceof QuicheQuicSslEngine)) {
398             failConnectPromiseAndThrow(new IllegalArgumentException("QuicSslEngine is not of type "
399                     + QuicheQuicSslEngine.class.getSimpleName()));
400             return;
401         }
402         if (!engine.getUseClientMode()) {
403             failConnectPromiseAndThrow(new IllegalArgumentException("QuicSslEngine is not create in client mode"));
404         }
405         QuicheQuicSslEngine quicheEngine = (QuicheQuicSslEngine) engine;
406         ByteBuf localIdBuffer = alloc().directBuffer(localConnectId.remaining()).writeBytes(localConnectId.duplicate());
407         ByteBuf remoteIdBuffer;
408         if (connectRemoteAddress != QuicConnectionAddress.EPHEMERAL) {
409             ByteBuffer remoteId = connectRemoteAddress.id();
410             remoteIdBuffer = alloc().directBuffer(remoteId.remaining()).writeBytes(remoteId.duplicate());
411         } else {
412             remoteIdBuffer = null;
413         }
414         try {
415             int fromSockaddrLen = SockaddrIn.setAddress(fromSockaddrMemory, local);
416             int toSockaddrLen = SockaddrIn.setAddress(toSockaddrMemory, remote);
417             QuicheQuicConnection connection = quicheEngine.createConnection(ssl -> {
418                 long localIdMemoryAddress = Quiche.readerMemoryAddress(localIdBuffer);
419                 int localIdLength = localIdBuffer.readableBytes();
420 
421                 final long remoteIdMemoryAddress;
422                 final int remoteIdLength;
423                 if (remoteIdBuffer == null) {
424                     return Quiche.quiche_conn_new_with_tls(localIdMemoryAddress, localIdLength,
425                             -1, -1,
426                             Quiche.memoryAddressWithPosition(fromSockaddrMemory), fromSockaddrLen,
427                             Quiche.memoryAddressWithPosition(toSockaddrMemory), toSockaddrLen,
428                             configAddr, ssl, false);
429                 } else {
430                     return Quiche.quiche_conn_new_with_tls_and_client_dcid(localIdMemoryAddress, localIdLength,
431                             Quiche.readerMemoryAddress(remoteIdBuffer), remoteIdBuffer.readableBytes(),
432                             Quiche.memoryAddressWithPosition(fromSockaddrMemory), fromSockaddrLen,
433                             Quiche.memoryAddressWithPosition(toSockaddrMemory), toSockaddrLen,
434                             configAddr, ssl);
435                 }
436             });
437             if (connection == null) {
438                 failConnectPromiseAndThrow(new ConnectException());
439                 return;
440             }
441             attachQuicheConnection(connection);
442             QuicClientSessionCache sessionCache = quicheEngine.ctx.getSessionCache();
443             if (sessionCache != null) {
444                 byte[] sessionBytes = sessionCache
445                         .getSession(quicheEngine.getSession().getPeerHost(), quicheEngine.getSession().getPeerPort());
446                 if (sessionBytes != null) {
447                     Quiche.quiche_conn_set_session(connection.address(), sessionBytes);
448                 }
449             }
450             this.supportsDatagram = supportsDatagram;
451             sourceConnectionIds.add(localConnectId);
452         } finally {
453             localIdBuffer.release();
454             if (remoteIdBuffer != null) {
455                 remoteIdBuffer.release();
456             }
457         }
458     }
459 
460     private void failConnectPromiseAndThrow(Exception e) throws Exception {
461         tryFailConnectPromise(e);
462         throw e;
463     }
464 
465     private boolean tryFailConnectPromise(Exception e) {
466         ChannelPromise promise = connectPromise;
467         if (promise != null) {
468             connectPromise = null;
469             promise.tryFailure(e);
470             return true;
471         }
472         return false;
473     }
474 
475     Set<ByteBuffer> sourceConnectionIds() {
476         return sourceConnectionIds;
477     }
478 
479     boolean markInFireChannelReadCompleteQueue() {
480         if (inFireChannelReadCompleteQueue) {
481             return false;
482         }
483         inFireChannelReadCompleteQueue = true;
484         return true;
485     }
486 
487     private void failPendingConnectPromise() {
488         ChannelPromise promise = QuicheQuicChannel.this.connectPromise;
489         if (promise != null) {
490             QuicheQuicChannel.this.connectPromise = null;
491             promise.tryFailure(new QuicClosedChannelException(this.connectionCloseEvent));
492         }
493     }
494 
495     void forceClose() {
496         unsafe().close(voidPromise());
497     }
498 
499     @Override
500     protected DefaultChannelPipeline newChannelPipeline() {
501         return new DefaultChannelPipeline(this) {
502             @Override
503             protected void onUnhandledInboundMessage(ChannelHandlerContext ctx, Object msg) {
504                 if (msg instanceof QuicStreamChannel) {
505                     QuicStreamChannel channel = (QuicStreamChannel) msg;
506                     Quic.setupChannel(channel, streamOptionsArray, streamAttrsArray, streamHandler, logger);
507                     ctx.channel().eventLoop().register(channel);
508                 } else {
509                     super.onUnhandledInboundMessage(ctx, msg);
510                 }
511             }
512         };
513     }
514 
515     @Override
516     public QuicChannel flush() {
517         super.flush();
518         return this;
519     }
520 
521     @Override
522     public QuicChannel read() {
523         super.read();
524         return this;
525     }
526 
527     @Override
528     public Future<QuicStreamChannel> createStream(QuicStreamType type, @Nullable ChannelHandler handler,
529                                                   Promise<QuicStreamChannel> promise) {
530         if (eventLoop().inEventLoop()) {
531             ((QuicChannelUnsafe) unsafe()).connectStream(type, handler, promise);
532         } else {
533             eventLoop().execute(() -> ((QuicChannelUnsafe) unsafe()).connectStream(type, handler, promise));
534         }
535         return promise;
536     }
537 
538     @Override
539     public ChannelFuture close(boolean applicationClose, int error, ByteBuf reason, ChannelPromise promise) {
540         if (eventLoop().inEventLoop()) {
541             close0(applicationClose, error, reason, promise);
542         } else {
543             eventLoop().execute(() -> close0(applicationClose, error, reason, promise));
544         }
545         return promise;
546     }
547 
548     private void close0(boolean applicationClose, int error, ByteBuf reason, ChannelPromise promise) {
549         if (closeData == null) {
550             if (!reason.hasMemoryAddress()) {
551                 // Copy to direct buffer as that's what we need.
552                 ByteBuf copy = alloc().directBuffer(reason.readableBytes()).writeBytes(reason);
553                 reason.release();
554                 reason = copy;
555             }
556             closeData = new CloseData(applicationClose, error, reason);
557             promise.addListener(closeData);
558         } else {
559             // We already have a close scheduled that uses a close data. Lets release the buffer early.
560             reason.release();
561         }
562         close(promise);
563     }
564 
565     @Override
566     public String toString() {
567         String traceId = this.traceId;
568         if (traceId == null) {
569             return "()" + super.toString();
570         } else {
571             return '(' + traceId + ')' + super.toString();
572         }
573     }
574 
575     @Override
576     protected AbstractUnsafe newUnsafe() {
577         return new QuicChannelUnsafe();
578     }
579 
580     @Override
581     protected boolean isCompatible(EventLoop eventLoop) {
582         return parent().eventLoop() == eventLoop;
583     }
584 
585     @Override
586     @Nullable
587     protected QuicConnectionAddress localAddress0() {
588         QuicheQuicConnection connection = this.connection;
589         return connection == null ? null : connection.sourceId();
590     }
591 
592     @Override
593     @Nullable
594     protected QuicConnectionAddress remoteAddress0() {
595         QuicheQuicConnection connection = this.connection;
596         return connection == null ? null : connection.destinationId();
597     }
598 
599     @Override
600     @Nullable
601     public QuicConnectionAddress localAddress() {
602         // Override so we never cache as the sourceId() can change over life-time.
603         return localAddress0();
604     }
605 
606     @Override
607     @Nullable
608     public QuicConnectionAddress remoteAddress() {
609         // Override so we never cache as the destinationId() can change over life-time.
610         return remoteAddress0();
611     }
612 
613     @Override
614     @Nullable
615     public SocketAddress localSocketAddress() {
616         return local;
617     }
618 
619     @Override
620     @Nullable
621     public SocketAddress remoteSocketAddress() {
622         return remote;
623     }
624 
625     @Override
626     protected void doBind(SocketAddress socketAddress) {
627         throw new UnsupportedOperationException();
628     }
629 
630     @Override
631     protected void doDisconnect() throws Exception {
632         doClose();
633     }
634 
635     @Override
636     protected void doClose() throws Exception {
637         if (state == ChannelState.CLOSED) {
638             return;
639         }
640         state = ChannelState.CLOSED;
641 
642         QuicheQuicConnection conn = this.connection;
643         if (conn == null || conn.isFreed()) {
644             if (closeData != null) {
645                 closeData.reason.release();
646                 closeData = null;
647             }
648             failPendingConnectPromise();
649             return;
650         }
651 
652         // Call connectionSend() so we ensure we send all that is queued before we close the channel
653         SendResult sendResult = connectionSend(conn);
654 
655         final boolean app;
656         final int err;
657         final ByteBuf reason;
658         if (closeData == null) {
659             app = false;
660             err = 0;
661             reason = Unpooled.EMPTY_BUFFER;
662         } else {
663             app = closeData.applicationClose;
664             err = closeData.err;
665             reason = closeData.reason;
666             closeData = null;
667         }
668 
669         failPendingConnectPromise();
670         try {
671             int res = Quiche.quiche_conn_close(conn.address(), app, err,
672                     Quiche.readerMemoryAddress(reason), reason.readableBytes());
673             if (res < 0 && res != Quiche.QUICHE_ERR_DONE) {
674                 throw Quiche.convertToException(res);
675             }
676             // As we called quiche_conn_close(...) we need to ensure we will call quiche_conn_send(...) either
677             // now or we will do so once we see the channelReadComplete event.
678             //
679             // See https://docs.rs/quiche/0.6.0/quiche/struct.Connection.html#method.close
680             if (connectionSend(conn) == SendResult.SOME) {
681                 sendResult = SendResult.SOME;
682             }
683         } finally {
684 
685             // making sure that connection statistics is available
686             // even after channel is closed
687             statsAtClose = collectStats0(conn, eventLoop().newPromise());
688             try {
689                 timedOut = Quiche.quiche_conn_is_timed_out(conn.address());
690 
691                 closeStreams();
692                 if (finBuffer != null) {
693                     finBuffer.release();
694                     finBuffer = null;
695                 }
696                 if (outErrorCodeBuffer != null) {
697                     outErrorCodeBuffer.release();
698                     outErrorCodeBuffer = null;
699                 }
700             } finally {
701                 if (sendResult == SendResult.SOME) {
702                     // As this is the close let us flush it asap.
703                     forceFlushParent();
704                 } else {
705                     flushParent();
706                 }
707                 conn.free();
708                 if (freeTask != null) {
709                     freeTask.accept(this);
710                 }
711                 timeoutHandler.cancel();
712 
713                 local = null;
714                 remote = null;
715             }
716         }
717     }
718 
719     @Override
720     protected void doBeginRead() {
721         recvDatagramPending = true;
722         recvStreamPending = true;
723         if (datagramReadable || streamReadable) {
724             ((QuicChannelUnsafe) unsafe()).recv();
725         }
726     }
727 
728     @Override
729     protected Object filterOutboundMessage(Object msg) {
730         if (msg instanceof ByteBuf) {
731             return msg;
732         }
733         throw new UnsupportedOperationException("Unsupported message type: " + StringUtil.simpleClassName(msg));
734     }
735 
736     @Override
737     protected void doWrite(ChannelOutboundBuffer channelOutboundBuffer) throws Exception {
738         if (!supportsDatagram) {
739             throw new UnsupportedOperationException("Datagram extension is not supported");
740         }
741         boolean sendSomething = false;
742         boolean retry = false;
743         QuicheQuicConnection conn = connection;
744         try {
745             for (;;) {
746                 ByteBuf buffer = (ByteBuf) channelOutboundBuffer.current();
747                 if (buffer == null) {
748                     break;
749                 }
750 
751                 int readable = buffer.readableBytes();
752                 if (readable == 0) {
753                     // Skip empty buffers.
754                     channelOutboundBuffer.remove();
755                     continue;
756                 }
757 
758                 final int res;
759                 if (!buffer.isDirect() || buffer.nioBufferCount() > 1) {
760                     ByteBuf tmpBuffer = alloc().directBuffer(readable);
761                     try {
762                         tmpBuffer.writeBytes(buffer, buffer.readerIndex(), readable);
763                         res = sendDatagram(conn, tmpBuffer);
764                     } finally {
765                         tmpBuffer.release();
766                     }
767                 } else {
768                     res = sendDatagram(conn, buffer);
769                 }
770                 if (res >= 0) {
771                     channelOutboundBuffer.remove();
772                     sendSomething = true;
773                     retry = false;
774                 } else {
775                     if (res == Quiche.QUICHE_ERR_BUFFER_TOO_SHORT) {
776                         retry = false;
777                         channelOutboundBuffer.remove(new BufferUnderflowException());
778                     } else if (res == Quiche.QUICHE_ERR_INVALID_STATE) {
779                         throw new UnsupportedOperationException("Remote peer does not support Datagram extension");
780                     } else if (res == Quiche.QUICHE_ERR_DONE) {
781                         if (retry) {
782                             // We already retried and it didn't work. Let's drop the datagrams on the floor.
783                             for (;;) {
784                                 if (!channelOutboundBuffer.remove()) {
785                                     // The buffer is empty now.
786                                     return;
787                                 }
788                             }
789                         }
790                         // Set sendSomething to false a we will call connectionSend() now.
791                         sendSomething = false;
792                         // If this returned DONE we couldn't write anymore. This happens if the internal queue
793                         // is full. In this case we should call quiche_conn_send(...) and so make space again.
794                         if (connectionSend(conn) != SendResult.NONE) {
795                             forceFlushParent();
796                         }
797                         // Let's try again to write the message.
798                         retry = true;
799                     } else {
800                         throw Quiche.convertToException(res);
801                     }
802                 }
803             }
804         } finally {
805             if (sendSomething && connectionSend(conn) != SendResult.NONE) {
806                 flushParent();
807             }
808         }
809     }
810 
811     private static int sendDatagram(QuicheQuicConnection conn, ByteBuf buf) throws ClosedChannelException {
812         return Quiche.quiche_conn_dgram_send(connectionAddressChecked(conn),
813                 Quiche.readerMemoryAddress(buf), buf.readableBytes());
814     }
815 
816     @Override
817     public QuicChannelConfig config() {
818         return config;
819     }
820 
821     @Override
822     public boolean isOpen() {
823         return state != ChannelState.CLOSED;
824     }
825 
826     @Override
827     public boolean isActive() {
828         return state == ChannelState.ACTIVE;
829     }
830 
831     @Override
832     public ChannelMetadata metadata() {
833         return METADATA;
834     }
835 
836     /**
837      * This may call {@link #flush()} on the parent channel if needed. The flush may be delayed until the read loop
838      * is over.
839      */
840     private void flushParent() {
841         if (!inFireChannelReadCompleteQueue) {
842             forceFlushParent();
843         }
844     }
845 
846     /**
847      * Call {@link #flush()} on the parent channel.
848      */
849     private void forceFlushParent() {
850         parent().flush();
851     }
852 
853     private static long connectionAddressChecked(@Nullable QuicheQuicConnection conn) throws ClosedChannelException {
854         if (conn == null || conn.isFreed()) {
855             throw new ClosedChannelException();
856         }
857         return conn.address();
858     }
859 
860     boolean freeIfClosed() {
861         QuicheQuicConnection conn = connection;
862         if (conn == null || conn.isFreed()) {
863             return true;
864         }
865         if (conn.isClosed()) {
866             unsafe().close(newPromise());
867             return true;
868         }
869         return false;
870     }
871 
872     private void closeStreams() {
873         if (streams.isEmpty()) {
874             return;
875         }
876         final ClosedChannelException closedChannelException;
877         if (isTimedOut()) {
878             // Close the streams because of a timeout.
879             closedChannelException = new QuicTimeoutClosedChannelException();
880         } else {
881             closedChannelException = new ClosedChannelException();
882         }
883         // Make a copy to ensure we not run into a situation when we change the underlying iterator from
884         // another method and so run in an assert error.
885         for (QuicheQuicStreamChannel stream: streams.values().toArray(new QuicheQuicStreamChannel[0])) {
886             stream.unsafe().close(closedChannelException, voidPromise());
887         }
888         streams.clear();
889     }
890 
891     void streamPriority(long streamId, byte priority, boolean incremental) throws Exception {
892        int res = Quiche.quiche_conn_stream_priority(connectionAddressChecked(connection), streamId,
893                priority, incremental);
894        if (res < 0 && res != Quiche.QUICHE_ERR_DONE) {
895            throw Quiche.convertToException(res);
896        }
897     }
898 
899     void streamClosed(long streamId) {
900         streams.remove(streamId);
901     }
902 
903     // Package-private for testing.
904     boolean hasStream(long streamId) {
905         assert eventLoop().inEventLoop();
906         return streams.containsKey(streamId);
907     }
908 
909     boolean isStreamLocalCreated(long streamId) {
910         return (streamId & 0x1) == (server ? 1 : 0);
911     }
912 
913     QuicStreamType streamType(long streamId) {
914         return (streamId & 0x2) == 0 ? QuicStreamType.BIDIRECTIONAL : QuicStreamType.UNIDIRECTIONAL;
915     }
916 
917     void streamShutdown(long streamId, boolean read, boolean write, int err, ChannelPromise promise) {
918         QuicheQuicConnection conn = this.connection;
919         final long connectionAddress;
920         try {
921             connectionAddress = connectionAddressChecked(conn);
922         } catch (ClosedChannelException e) {
923             promise.setFailure(e);
924             return;
925         }
926         int res = 0;
927         if (read) {
928             res |= Quiche.quiche_conn_stream_shutdown(connectionAddress, streamId, Quiche.QUICHE_SHUTDOWN_READ, err);
929         }
930         if (write) {
931             res |= Quiche.quiche_conn_stream_shutdown(connectionAddress, streamId, Quiche.QUICHE_SHUTDOWN_WRITE, err);
932         }
933 
934         // As we called quiche_conn_stream_shutdown(...) we need to ensure we will call quiche_conn_send(...) either
935         // now or we will do so once we see the channelReadComplete event.
936         //
937         // See https://docs.rs/quiche/0.6.0/quiche/struct.Connection.html#method.send
938         if (connectionSend(conn) != SendResult.NONE) {
939             // Force the flush so the shutdown can be seen asap.
940             forceFlushParent();
941         }
942         if (res < 0 && res != Quiche.QUICHE_ERR_DONE) {
943             promise.setFailure(Quiche.convertToException(res));
944         } else {
945             promise.setSuccess();
946         }
947     }
948 
949     void streamSendFin(long streamId) throws Exception {
950         QuicheQuicConnection conn = connection;
951         try {
952             // Just write an empty buffer and set fin to true.
953             int res = streamSend0(conn, streamId, Unpooled.EMPTY_BUFFER, true);
954             if (res < 0 && res != Quiche.QUICHE_ERR_DONE) {
955                 throw Quiche.convertToException(res);
956             }
957         } finally {
958             // As we called quiche_conn_stream_send(...) we need to ensure we will call quiche_conn_send(...) either
959             // now or we will do so once we see the channelReadComplete event.
960             //
961             // See https://docs.rs/quiche/0.6.0/quiche/struct.Connection.html#method.send
962             if (connectionSend(conn) != SendResult.NONE) {
963                 flushParent();
964             }
965         }
966     }
967 
968     int streamSend(long streamId, ByteBuf buffer, boolean fin) throws ClosedChannelException {
969         QuicheQuicConnection conn = connection;
970         if (buffer.nioBufferCount() == 1) {
971             return streamSend0(conn, streamId, buffer, fin);
972         }
973         ByteBuffer[] nioBuffers  = buffer.nioBuffers();
974         int lastIdx = nioBuffers.length - 1;
975         int res = 0;
976         for (int i = 0; i < lastIdx; i++) {
977             ByteBuffer nioBuffer = nioBuffers[i];
978             while (nioBuffer.hasRemaining()) {
979                 int localRes = streamSend(conn, streamId, nioBuffer, false);
980                 if (localRes <= 0) {
981                     return res;
982                 }
983                 res += localRes;
984 
985                 nioBuffer.position(nioBuffer.position() + localRes);
986             }
987         }
988         int localRes = streamSend(conn, streamId, nioBuffers[lastIdx], fin);
989         if (localRes > 0) {
990             res += localRes;
991         }
992         return res;
993     }
994 
995     void connectionSendAndFlush() {
996         if (inFireChannelReadCompleteQueue || (reantranceGuard & IN_HANDLE_WRITABLE_STREAMS) != 0) {
997             return;
998         }
999         if (connectionSend(connection) != SendResult.NONE) {
1000             flushParent();
1001         }
1002     }
1003 
1004     private int streamSend0(QuicheQuicConnection conn, long streamId, ByteBuf buffer, boolean fin)
1005             throws ClosedChannelException {
1006         return Quiche.quiche_conn_stream_send(connectionAddressChecked(conn), streamId,
1007                 Quiche.readerMemoryAddress(buffer), buffer.readableBytes(), fin);
1008     }
1009 
1010     private int streamSend(QuicheQuicConnection conn, long streamId, ByteBuffer buffer, boolean fin)
1011             throws ClosedChannelException {
1012         return Quiche.quiche_conn_stream_send(connectionAddressChecked(conn), streamId,
1013                 Quiche.memoryAddressWithPosition(buffer), buffer.remaining(), fin);
1014     }
1015 
1016     StreamRecvResult streamRecv(long streamId, ByteBuf buffer) throws Exception {
1017         QuicheQuicConnection conn = connection;
1018         long connAddr = connectionAddressChecked(conn);
1019         if (finBuffer == null) {
1020             finBuffer = alloc().directBuffer(1);
1021         }
1022         if (outErrorCodeBuffer == null) {
1023             outErrorCodeBuffer = alloc().directBuffer(8);
1024         }
1025         outErrorCodeBuffer.setLongLE(0, -1L);
1026         int writerIndex = buffer.writerIndex();
1027         int recvLen = Quiche.quiche_conn_stream_recv(connAddr, streamId,
1028                 Quiche.writerMemoryAddress(buffer), buffer.writableBytes(), Quiche.writerMemoryAddress(finBuffer),
1029                 Quiche.writerMemoryAddress(outErrorCodeBuffer));
1030         long errorCode = outErrorCodeBuffer.getLongLE(0);
1031         if (recvLen == Quiche.QUICHE_ERR_DONE) {
1032             return StreamRecvResult.DONE;
1033         } else if (recvLen < 0) {
1034             throw Quiche.convertToException(recvLen, errorCode);
1035         }
1036         buffer.writerIndex(writerIndex + recvLen);
1037         return finBuffer.getBoolean(0) ? StreamRecvResult.FIN : StreamRecvResult.OK;
1038     }
1039 
1040     /**
1041      * Receive some data on a QUIC connection.
1042      */
1043     void recv(InetSocketAddress sender, InetSocketAddress recipient, ByteBuf buffer) {
1044         ((QuicChannelUnsafe) unsafe()).connectionRecv(sender, recipient, buffer);
1045     }
1046 
1047     /**
1048      * Return all source connection ids that are retired and so should be removed to map to the channel.
1049      *
1050      * @return retired ids.
1051      */
1052     List<ByteBuffer> retiredSourceConnectionId() {
1053         QuicheQuicConnection connection = this.connection;
1054         if (connection == null || connection.isFreed()) {
1055             return Collections.emptyList();
1056         }
1057         long connAddr = connection.address();
1058         assert connAddr != -1;
1059         List<ByteBuffer> retiredSourceIds = null;
1060         for (;;) {
1061             byte[] retired = Quiche.quiche_conn_retired_scid_next(connAddr);
1062             if (retired == null) {
1063                 break;
1064             }
1065             if (retiredSourceIds == null) {
1066                 retiredSourceIds = new ArrayList<>();
1067             }
1068             ByteBuffer retiredId = ByteBuffer.wrap(retired);
1069             retiredSourceIds.add(retiredId);
1070             sourceConnectionIds.remove(retiredId);
1071         }
1072         if (retiredSourceIds == null) {
1073             return Collections.emptyList();
1074         }
1075         return retiredSourceIds;
1076     }
1077 
1078     List<ByteBuffer> newSourceConnectionIds() {
1079         if (connectionIdAddressGenerator != null && resetTokenGenerator != null) {
1080             QuicheQuicConnection connection = this.connection;
1081             if (connection == null || connection.isFreed()) {
1082                 return Collections.emptyList();
1083             }
1084             long connAddr = connection.address();
1085             // Generate all extra source ids that we can provide. This will cause frames that need to be sent. Which
1086             // is the reason why we might need to call connectionSendAndFlush().
1087             int left = Quiche.quiche_conn_scids_left(connAddr);
1088             if (left > 0) {
1089                 QuicConnectionAddress sourceAddr = connection.sourceId();
1090                 if (sourceAddr == null) {
1091                     return Collections.emptyList();
1092                 }
1093                 List<ByteBuffer> generatedIds = new ArrayList<>(left);
1094                 boolean sendAndFlush = false;
1095                 ByteBuffer key = sourceAddr.id();
1096                 ByteBuf connIdBuffer = alloc().directBuffer(key.remaining());
1097 
1098                 byte[] resetTokenArray = new byte[Quic.RESET_TOKEN_LEN];
1099                 try {
1100                     do {
1101                         ByteBuffer srcId = connectionIdAddressGenerator.newId(key.duplicate(), key.remaining())
1102                                 .asReadOnlyBuffer();
1103                         connIdBuffer.clear();
1104                         connIdBuffer.writeBytes(srcId.duplicate());
1105                         ByteBuffer resetToken = resetTokenGenerator.newResetToken(srcId.duplicate());
1106                         resetToken.get(resetTokenArray);
1107                         long result = Quiche.quiche_conn_new_scid(
1108                                 connAddr, Quiche.memoryAddress(connIdBuffer, 0, connIdBuffer.readableBytes()),
1109                                 connIdBuffer.readableBytes(), resetTokenArray, false, -1);
1110                         if (result < 0) {
1111                             break;
1112                         }
1113                         sendAndFlush = true;
1114                         generatedIds.add(srcId.duplicate());
1115                         sourceConnectionIds.add(srcId);
1116                     } while (--left > 0);
1117                 } finally {
1118                     connIdBuffer.release();
1119                 }
1120 
1121                 if (sendAndFlush) {
1122                     connectionSendAndFlush();
1123                 }
1124                 return generatedIds;
1125             }
1126         }
1127         return Collections.emptyList();
1128     }
1129 
1130     void writable() {
1131         QuicheQuicConnection conn = connection;
1132         SendResult result = connectionSend(conn);
1133         handleWritableStreams(conn);
1134         if (connectionSend(conn) == SendResult.SOME) {
1135             result = SendResult.SOME;
1136         }
1137         if (result == SendResult.SOME) {
1138             // The writability changed so lets flush as fast as possible.
1139             forceFlushParent();
1140         }
1141         freeIfClosed();
1142     }
1143 
1144     long streamCapacity(long streamId) {
1145         QuicheQuicConnection conn = connection;
1146         if (conn.isClosed()) {
1147             return 0;
1148         }
1149         return Quiche.quiche_conn_stream_capacity(conn.address(), streamId);
1150     }
1151 
1152     private boolean handleWritableStreams(QuicheQuicConnection conn) {
1153         if (conn.isFreed()) {
1154             return false;
1155         }
1156         reantranceGuard |= IN_HANDLE_WRITABLE_STREAMS;
1157         try {
1158             long connAddr = conn.address();
1159             boolean mayNeedWrite = false;
1160 
1161             if (Quiche.quiche_conn_is_established(connAddr) ||
1162                     Quiche.quiche_conn_is_in_early_data(connAddr)) {
1163                 long writableIterator = Quiche.quiche_conn_writable(connAddr);
1164 
1165                 int totalWritable = 0;
1166                 try {
1167                     // For streams we always process all streams when at least on read was requested.
1168                     for (;;) {
1169                         int writable = Quiche.quiche_stream_iter_next(
1170                                 writableIterator, writableStreams);
1171                         for (int i = 0; i < writable; i++) {
1172                             long streamId = writableStreams[i];
1173                             QuicheQuicStreamChannel streamChannel = streams.get(streamId);
1174                             if (streamChannel != null) {
1175                                 long capacity = Quiche.quiche_conn_stream_capacity(connAddr, streamId);
1176                                 if (streamChannel.writable(capacity)) {
1177                                     mayNeedWrite = true;
1178                                 }
1179                             }
1180                         }
1181                         if (writable > 0) {
1182                             totalWritable += writable;
1183                         }
1184                         if (writable < writableStreams.length) {
1185                             // We did handle all writable streams.
1186                             break;
1187                         }
1188                     }
1189                 } finally {
1190                     Quiche.quiche_stream_iter_free(writableIterator);
1191                 }
1192                 writableStreams = growIfNeeded(writableStreams, totalWritable);
1193             }
1194             return mayNeedWrite;
1195         } finally {
1196             reantranceGuard &= ~IN_HANDLE_WRITABLE_STREAMS;
1197         }
1198     }
1199 
1200     /**
1201      * Called once we receive a channelReadComplete event. This method will take care of calling
1202      * {@link ChannelPipeline#fireChannelReadComplete()} if needed and also to handle pending flushes of
1203      * writable {@link QuicheQuicStreamChannel}s.
1204      */
1205     void recvComplete() {
1206         try {
1207             QuicheQuicConnection conn = connection;
1208             if (conn.isFreed()) {
1209                 // Ensure we flush all pending writes.
1210                 forceFlushParent();
1211                 return;
1212             }
1213             fireChannelReadCompleteIfNeeded();
1214 
1215             // If we had called recv we need to ensure we call send as well.
1216             // See https://docs.rs/quiche/0.6.0/quiche/struct.Connection.html#method.send
1217             connectionSend(conn);
1218 
1219             // We are done with the read loop, flush all pending writes now.
1220             forceFlushParent();
1221             freeIfClosed();
1222         } finally {
1223             inFireChannelReadCompleteQueue = false;
1224         }
1225     }
1226 
1227     private void fireChannelReadCompleteIfNeeded() {
1228         if (fireChannelReadCompletePending) {
1229             fireChannelReadCompletePending = false;
1230             pipeline().fireChannelReadComplete();
1231         }
1232     }
1233 
1234     private void fireExceptionEvents(QuicheQuicConnection conn, Throwable cause) {
1235         if (cause instanceof SSLHandshakeException) {
1236             notifyAboutHandshakeCompletionIfNeeded(conn, (SSLHandshakeException) cause);
1237         }
1238         pipeline().fireExceptionCaught(cause);
1239     }
1240 
1241     private boolean runTasksDirectly() {
1242         return sslTaskExecutor == null || sslTaskExecutor == ImmediateExecutor.INSTANCE ||
1243                 sslTaskExecutor == ImmediateEventExecutor.INSTANCE;
1244     }
1245 
1246     private void runAllTaskSend(QuicheQuicConnection conn, Runnable task) {
1247         sslTaskExecutor.execute(decorateTaskSend(conn, task));
1248     }
1249 
1250     private void runAll(QuicheQuicConnection conn, Runnable task) {
1251         do {
1252             task.run();
1253         } while ((task = conn.sslTask()) != null);
1254     }
1255 
1256     private Runnable decorateTaskSend(QuicheQuicConnection conn, Runnable task) {
1257         return () -> {
1258             try {
1259                 runAll(conn, task);
1260             } finally {
1261                 // Move back to the EventLoop.
1262                 eventLoop().execute(() -> {
1263                     // Call connection send to continue handshake if needed.
1264                     if (connectionSend(conn) != SendResult.NONE) {
1265                         forceFlushParent();
1266                     }
1267                     freeIfClosed();
1268                 });
1269             }
1270         };
1271     }
1272 
1273     private SendResult connectionSendSegments(QuicheQuicConnection conn,
1274                                               SegmentedDatagramPacketAllocator segmentedDatagramPacketAllocator) {
1275         if (conn.isClosed()) {
1276             return SendResult.NONE;
1277         }
1278         List<ByteBuf> bufferList = new ArrayList<>(segmentedDatagramPacketAllocator.maxNumSegments());
1279         long connAddr = conn.address();
1280         int maxDatagramSize = Quiche.quiche_conn_max_send_udp_payload_size(connAddr);
1281         SendResult sendResult = SendResult.NONE;
1282         boolean close = false;
1283         try {
1284             for (;;) {
1285                 int len = calculateSendBufferLength(connAddr, maxDatagramSize);
1286                 ByteBuf out = alloc().directBuffer(len);
1287 
1288                 ByteBuffer sendInfo = conn.nextSendInfo();
1289                 InetSocketAddress sendToAddress = this.remote;
1290 
1291                 int writerIndex = out.writerIndex();
1292                 int written = Quiche.quiche_conn_send(
1293                         connAddr, Quiche.writerMemoryAddress(out), out.writableBytes(),
1294                         Quiche.memoryAddressWithPosition(sendInfo));
1295                 if (written == 0) {
1296                     out.release();
1297                     // No need to create a new datagram packet. Just try again.
1298                     continue;
1299                 }
1300                 final boolean done;
1301                 if (written < 0) {
1302                     done = true;
1303                     if (written != Quiche.QUICHE_ERR_DONE) {
1304                         close = Quiche.shouldClose(written);
1305                         Exception e = Quiche.convertToException(written);
1306                         if (!tryFailConnectPromise(e)) {
1307                             // Only fire through the pipeline if this does not fail the connect promise.
1308                             fireExceptionEvents(conn, e);
1309                         }
1310                     }
1311                 } else {
1312                     done = false;
1313                 }
1314                 int size = bufferList.size();
1315                 if (done) {
1316                     // We are done, release the buffer and send what we did build up so far.
1317                     out.release();
1318 
1319                     switch (size) {
1320                         case 0:
1321                             // Nothing more to write.
1322                             break;
1323                         case 1:
1324                             // We can write a normal datagram packet.
1325                             parent().write(new DatagramPacket(bufferList.get(0), sendToAddress));
1326                             sendResult = SendResult.SOME;
1327                             break;
1328                         default:
1329                             int segmentSize = segmentSize(bufferList);
1330                             ByteBuf compositeBuffer = Unpooled.wrappedBuffer(bufferList.toArray(new ByteBuf[0]));
1331                             // We had more than one buffer, create a segmented packet.
1332                             parent().write(segmentedDatagramPacketAllocator.newPacket(
1333                                     compositeBuffer, segmentSize, sendToAddress));
1334                             sendResult = SendResult.SOME;
1335                             break;
1336                     }
1337                     bufferList.clear();
1338                     if (close) {
1339                         sendResult = SendResult.CLOSE;
1340                     }
1341                     return sendResult;
1342                 }
1343                 out.writerIndex(writerIndex + written);
1344 
1345                 int segmentSize = -1;
1346                 if (conn.isSendInfoChanged()) {
1347                     // Change the cached address and let the user know there was a connection migration.
1348                     remote = QuicheSendInfo.getToAddress(sendInfo);
1349                     local = QuicheSendInfo.getFromAddress(sendInfo);
1350 
1351                     if (size > 0) {
1352                         // We have something in the out list already, we need to send this now and so we set the
1353                         // segmentSize.
1354                         segmentSize = segmentSize(bufferList);
1355                     }
1356                 } else if (size > 0) {
1357                     int lastReadable = segmentSize(bufferList);
1358                     // Check if we either need to send now because the last buffer we added has a smaller size then this
1359                     // one or if we reached the maximum number of segments that we can send.
1360                     if (lastReadable != out.readableBytes() ||
1361                             size == segmentedDatagramPacketAllocator.maxNumSegments()) {
1362                         segmentSize = lastReadable;
1363                     }
1364                 }
1365 
1366                 // If the segmentSize is not -1 we know we need to send now what was in the out list.
1367                 if (segmentSize != -1) {
1368                     final boolean stop;
1369                     if (size == 1) {
1370                         // Only one buffer in the out list, there is no need to use segments.
1371                         stop = writePacket(new DatagramPacket(
1372                                 bufferList.get(0), sendToAddress), maxDatagramSize, len);
1373                     } else {
1374                         // Create a packet with segments in.
1375                         ByteBuf compositeBuffer = Unpooled.wrappedBuffer(bufferList.toArray(new ByteBuf[0]));
1376                         stop = writePacket(segmentedDatagramPacketAllocator.newPacket(
1377                                 compositeBuffer, segmentSize, sendToAddress), maxDatagramSize, len);
1378                     }
1379                     bufferList.clear();
1380                     sendResult = SendResult.SOME;
1381 
1382                     if (stop) {
1383                         // Nothing left in the window, continue later. That said we still need to also
1384                         // write the previous filled out buffer as otherwise we would either leak or need
1385                         // to drop it and so produce some loss.
1386                         if (out.isReadable()) {
1387                             parent().write(new DatagramPacket(out, sendToAddress));
1388                         } else {
1389                             out.release();
1390                         }
1391                         if (close) {
1392                             sendResult = SendResult.CLOSE;
1393                         }
1394                         return sendResult;
1395                     }
1396                 }
1397                 // Let's add a touch with the bufferList as a hint. This will help us to debug leaks if there
1398                 // are any.
1399                 out.touch(bufferList);
1400                 // store for later, so we can make use of segments.
1401                 bufferList.add(out);
1402             }
1403         } finally {
1404             // NOOP
1405         }
1406     }
1407 
1408     private static int segmentSize(List<ByteBuf> bufferList) {
1409         assert !bufferList.isEmpty();
1410         int size = bufferList.size();
1411         return bufferList.get(size - 1).readableBytes();
1412     }
1413 
1414     private SendResult connectionSendSimple(QuicheQuicConnection conn) {
1415         if (conn.isClosed()) {
1416             return SendResult.NONE;
1417         }
1418         long connAddr = conn.address();
1419         SendResult sendResult = SendResult.NONE;
1420         boolean close = false;
1421         int maxDatagramSize = Quiche.quiche_conn_max_send_udp_payload_size(connAddr);
1422         for (;;) {
1423             ByteBuffer sendInfo = conn.nextSendInfo();
1424 
1425             int len = calculateSendBufferLength(connAddr, maxDatagramSize);
1426             ByteBuf out = alloc().directBuffer(len);
1427             int writerIndex = out.writerIndex();
1428 
1429             int written = Quiche.quiche_conn_send(
1430                     connAddr, Quiche.writerMemoryAddress(out), out.writableBytes(),
1431                     Quiche.memoryAddressWithPosition(sendInfo));
1432 
1433             if (written == 0) {
1434                 // No need to create a new datagram packet. Just release and try again.
1435                 out.release();
1436                 continue;
1437             }
1438             if (written < 0) {
1439                 out.release();
1440                 if (written != Quiche.QUICHE_ERR_DONE) {
1441                     close = Quiche.shouldClose(written);
1442 
1443                     Exception e = Quiche.convertToException(written);
1444                     if (!tryFailConnectPromise(e)) {
1445                         fireExceptionEvents(conn, e);
1446                     }
1447                 }
1448                 break;
1449             }
1450             if (conn.isSendInfoChanged()) {
1451                 // Change the cached address
1452                 remote = QuicheSendInfo.getToAddress(sendInfo);
1453                 local = QuicheSendInfo.getFromAddress(sendInfo);
1454             }
1455             out.writerIndex(writerIndex + written);
1456             boolean stop = writePacket(new DatagramPacket(out, remote), maxDatagramSize, len);
1457             sendResult = SendResult.SOME;
1458             if (stop) {
1459                 // Nothing left in the window, continue later
1460                 break;
1461             }
1462         }
1463         if (close) {
1464             sendResult = SendResult.CLOSE;
1465         }
1466         return sendResult;
1467     }
1468 
1469     private boolean writePacket(DatagramPacket packet, int maxDatagramSize, int len) {
1470         ChannelFuture future = parent().write(packet);
1471         if (isSendWindowUsed(maxDatagramSize, len)) {
1472             // Nothing left in the window, continue later
1473             future.addListener(continueSendingListener);
1474             return true;
1475         }
1476         return false;
1477     }
1478 
1479     private static boolean isSendWindowUsed(int maxDatagramSize, int len) {
1480         return len < maxDatagramSize;
1481     }
1482 
1483     private static int calculateSendBufferLength(long connAddr, int maxDatagramSize) {
1484         int len = Math.min(maxDatagramSize, Quiche.quiche_conn_send_quantum(connAddr));
1485         if (len <= 0) {
1486             // If there is no room left we just return some small number to reduce the risk of packet drop
1487             // while still be able to attach the listener to the write future.
1488             // We use the value of 8 because such an allocation will be cheap to serve from the
1489             // PooledByteBufAllocator while still serve our need.
1490             return 8;
1491         }
1492         return len;
1493     }
1494 
1495     /**
1496      * Write datagrams if needed and return {@code true} if something was written and we need to call
1497      * {@link Channel#flush()} at some point.
1498      */
1499     private SendResult connectionSend(QuicheQuicConnection conn) {
1500         if (conn.isFreed()) {
1501             return SendResult.NONE;
1502         }
1503         if ((reantranceGuard & IN_CONNECTION_SEND) != 0) {
1504             // Let's notify about early data if needed.
1505             notifyEarlyDataReadyIfNeeded(conn);
1506             return SendResult.NONE;
1507         }
1508 
1509         reantranceGuard |= IN_CONNECTION_SEND;
1510         try {
1511             SendResult sendResult;
1512             SegmentedDatagramPacketAllocator segmentedDatagramPacketAllocator =
1513                     config.getSegmentedDatagramPacketAllocator();
1514             if (segmentedDatagramPacketAllocator.maxNumSegments() > 0) {
1515                 sendResult = connectionSendSegments(conn, segmentedDatagramPacketAllocator);
1516             } else {
1517                 sendResult = connectionSendSimple(conn);
1518             }
1519 
1520             // Process / schedule all tasks that were created.
1521 
1522             Runnable task = conn.sslTask();
1523             if (task != null) {
1524                 if (runTasksDirectly()) {
1525                     // Consume all tasks
1526                     do {
1527                         task.run();
1528                         // Notify about early data ready if needed.
1529                         notifyEarlyDataReadyIfNeeded(conn);
1530                     } while ((task = conn.sslTask()) != null);
1531 
1532                     // Let's try again sending after we did process all tasks.
1533                     // We schedule this on the EventLoop as otherwise we will get into trouble with re-entrance.
1534                     eventLoop().execute(new Runnable() {
1535                         @Override
1536                         public void run() {
1537                             // Call connection send to continue handshake if needed.
1538                             if (connectionSend(conn) != SendResult.NONE) {
1539                                 forceFlushParent();
1540                             }
1541                             freeIfClosed();
1542                         }
1543                     });
1544                 } else {
1545                     runAllTaskSend(conn, task);
1546                 }
1547             } else {
1548                 // Notify about early data ready if needed.
1549                 notifyEarlyDataReadyIfNeeded(conn);
1550             }
1551 
1552             // Whenever we called connection_send we should also schedule the timer if needed.
1553             timeoutHandler.scheduleTimeout();
1554             return sendResult;
1555         } finally {
1556             reantranceGuard &= ~IN_CONNECTION_SEND;
1557         }
1558     }
1559 
1560     private final class QuicChannelUnsafe extends AbstractChannel.AbstractUnsafe {
1561 
1562         @Override
1563         protected void close(ChannelPromise promise, Throwable cause, ClosedChannelException closeCause) {
1564             final InetSocketAddress sendToAddress = remote;
1565             if (sendToAddress == null) {
1566                 super.close(promise, cause, closeCause);
1567             } else {
1568                 ChannelPromise p = newPromise();
1569                 super.close(p.addListener(f -> {
1570                     // We need to ensure all writes were done before we actually notify the close promise as otherwise
1571                     // we might not be able to write things to the underlying socket if the socket is closed as soon
1572                     // as all QuicChannel.close() ChannelFutures are completed.
1573                     parent().writeAndFlush(new DatagramPacket(Unpooled.EMPTY_BUFFER, sendToAddress))
1574                             .addListener(wf -> {
1575                                 if (f.isSuccess()) {
1576                                     promise.setSuccess();
1577                                 } else {
1578                                     promise.setFailure(f.cause());
1579                                 }
1580                             });
1581                 }), cause, closeCause);
1582             }
1583         }
1584 
1585         void connectStream(QuicStreamType type, @Nullable ChannelHandler handler,
1586                            Promise<QuicStreamChannel> promise) {
1587             if (!promise.setUncancellable()) {
1588                 return;
1589             }
1590             // Fail fast without consuming a stream id when all credits are used. Otherwise a
1591             // failed createStream(...) permanently consumes the id: quiche rejects the implicit
1592             // open by stream id position and never returns it, so once ids are allocated past
1593             // the peer's limit every future createStream(...) fails with STREAM_LIMIT_ERROR,
1594             // even after MAX_STREAMS restored the limit, while peerAllowedStreams(...) keeps
1595             // reporting capacity. Only trusted once the caches were refreshed from quiche;
1596             // before that they are 0 even though the peer may have announced credits, so we
1597             // fall through to quiche and let the rollback below handle a rejection.
1598             if (streamCreditsInitialized && peerAllowedStreams(type) <= 0) {
1599                 promise.setFailure(Quiche.convertToException(Quiche.QUICHE_ERR_STREAM_LIMIT));
1600                 return;
1601             }
1602             long streamId = idGenerator.nextStreamId(type == QuicStreamType.BIDIRECTIONAL);
1603 
1604             try {
1605                 int res = streamSend0(connection, streamId, Unpooled.EMPTY_BUFFER, false);
1606                 if (res < 0 && res != Quiche.QUICHE_ERR_DONE) {
1607                     throw Quiche.convertToException(res);
1608                 }
1609             } catch (Exception e) {
1610                 // quiche rejected the implicit open before creating any state for the stream,
1611                 // so the id can safely be given back and must be, to not permanently consume
1612                 // it (only done for STREAM_LIMIT as other errors might have left state behind).
1613                 if (e instanceof QuicException &&
1614                         ((QuicException) e).error() == QuicTransportError.STREAM_LIMIT_ERROR) {
1615                     idGenerator.rollbackStreamId(streamId, type == QuicStreamType.BIDIRECTIONAL);
1616                 }
1617                 promise.setFailure(e);
1618                 return;
1619             }
1620             if (type == QuicStreamType.UNIDIRECTIONAL) {
1621                 UNI_STREAMS_LEFT_UPDATER.decrementAndGet(QuicheQuicChannel.this);
1622             } else {
1623                 BIDI_STREAMS_LEFT_UPDATER.decrementAndGet(QuicheQuicChannel.this);
1624             }
1625             QuicheQuicStreamChannel streamChannel = addNewStreamChannel(streamId);
1626             if (handler != null) {
1627                 streamChannel.pipeline().addLast(handler);
1628             }
1629             eventLoop().register(streamChannel).addListener((ChannelFuture f) -> {
1630                 if (f.isSuccess()) {
1631                     promise.setSuccess(streamChannel);
1632                 } else {
1633                     promise.setFailure(f.cause());
1634                     streams.remove(streamId);
1635                 }
1636             });
1637         }
1638 
1639         @Override
1640         public void connect(SocketAddress remote, SocketAddress local, ChannelPromise channelPromise) {
1641             assert eventLoop().inEventLoop();
1642             if (!channelPromise.setUncancellable()) {
1643                 return;
1644             }
1645             if (server) {
1646                 channelPromise.setFailure(new UnsupportedOperationException());
1647                 return;
1648             }
1649 
1650             if (connectPromise != null) {
1651                 channelPromise.setFailure(new ConnectionPendingException());
1652                 return;
1653             }
1654 
1655             if (remote instanceof QuicConnectionAddress) {
1656                 if (!sourceConnectionIds.isEmpty()) {
1657                     // If a key is assigned we know this channel was already connected.
1658                     channelPromise.setFailure(new AlreadyConnectedException());
1659                     return;
1660                 }
1661 
1662                 connectLocalAddress = (QuicConnectionAddress) local;
1663                 connectRemoteAddress = (QuicConnectionAddress) remote;
1664                 connectPromise = channelPromise;
1665 
1666                 // Schedule connect timeout.
1667                 int connectTimeoutMillis = config().getConnectTimeoutMillis();
1668                 if (connectTimeoutMillis > 0) {
1669                     connectTimeoutFuture = eventLoop().schedule(() -> {
1670                         ChannelPromise connectPromise = QuicheQuicChannel.this.connectPromise;
1671                         if (connectPromise != null && !connectPromise.isDone()
1672                                 && connectPromise.tryFailure(new ConnectTimeoutException(
1673                                 "connection timed out: " + local + " -> " +  remote))) {
1674                             close(voidPromise());
1675                         }
1676                     }, connectTimeoutMillis, TimeUnit.MILLISECONDS);
1677                 }
1678 
1679                 connectPromise.addListener((ChannelFuture future) -> {
1680                     if (future.isCancelled()) {
1681                         if (connectTimeoutFuture != null) {
1682                             connectTimeoutFuture.cancel(false);
1683                         }
1684                         connectPromise = null;
1685                         close(voidPromise());
1686                     }
1687                 });
1688 
1689                 parent().connect(new QuicheQuicChannelAddress(QuicheQuicChannel.this))
1690                         .addListener(f -> {
1691                             ChannelPromise connectPromise = QuicheQuicChannel.this.connectPromise;
1692                             if (connectPromise != null && !f.isSuccess()) {
1693                                 connectPromise.tryFailure(f.cause());
1694                                 // close everything after notify about failure.
1695                                 unsafe().closeForcibly();
1696                             }
1697                         });
1698                 return;
1699             }
1700 
1701             channelPromise.setFailure(new UnsupportedOperationException());
1702         }
1703 
1704         private void fireConnectCloseEventIfNeeded(QuicheQuicConnection conn) {
1705             if (connectionCloseEvent == null && !conn.isFreed()) {
1706                 connectionCloseEvent = Quiche.quiche_conn_peer_error(conn.address());
1707                 if (connectionCloseEvent != null) {
1708                     pipeline().fireUserEventTriggered(connectionCloseEvent);
1709                 }
1710             }
1711         }
1712 
1713         void connectionRecv(InetSocketAddress sender, InetSocketAddress recipient, ByteBuf buffer) {
1714             QuicheQuicConnection conn = QuicheQuicChannel.this.connection;
1715             if (conn.isFreed()) {
1716                 return;
1717             }
1718             int bufferReadable = buffer.readableBytes();
1719             if (bufferReadable == 0) {
1720                 // Nothing to do here. Just return...
1721                 // See also https://github.com/cloudflare/quiche/issues/817
1722                 return;
1723             }
1724 
1725             reantranceGuard |= IN_RECV;
1726             boolean close = false;
1727             try {
1728                 ByteBuf tmpBuffer = null;
1729                 // We need to make a copy if the buffer is read only as recv(...) may modify the input buffer as well.
1730                 // See https://docs.rs/quiche/0.6.0/quiche/struct.Connection.html#method.recv
1731                 if (buffer.isReadOnly()) {
1732                     tmpBuffer = alloc().directBuffer(buffer.readableBytes());
1733                     tmpBuffer.writeBytes(buffer);
1734                     buffer = tmpBuffer;
1735                 }
1736                 long memoryAddress = Quiche.readerMemoryAddress(buffer);
1737 
1738                 ByteBuffer recvInfo = conn.nextRecvInfo();
1739                 QuicheRecvInfo.setRecvInfo(recvInfo, sender, recipient);
1740 
1741                 remote = sender;
1742                 local = recipient;
1743 
1744                 try {
1745                     do  {
1746                         // Call quiche_conn_recv(...) until we consumed all bytes or we did receive some error.
1747                         int res = Quiche.quiche_conn_recv(conn.address(), memoryAddress, bufferReadable,
1748                                 Quiche.memoryAddressWithPosition(recvInfo));
1749                         final boolean done;
1750                         if (res < 0) {
1751                             done = true;
1752                             if (res != Quiche.QUICHE_ERR_DONE) {
1753                                 close = Quiche.shouldClose(res);
1754                                 Exception e = Quiche.convertToException(res);
1755                                 if (tryFailConnectPromise(e)) {
1756                                     break;
1757                                 }
1758                                 fireExceptionEvents(conn, e);
1759                             }
1760                         } else {
1761                             done = false;
1762                         }
1763                         // Process / schedule all tasks that were created.
1764                         Runnable task = conn.sslTask();
1765                         if (task != null) {
1766                             if (runTasksDirectly()) {
1767                                 // Consume all tasks
1768                                 do {
1769                                     task.run();
1770                                 } while ((task = conn.sslTask()) != null);
1771                                 processReceived(conn);
1772                             } else {
1773                                 runAllTaskRecv(conn, task);
1774                             }
1775                         } else {
1776                             processReceived(conn);
1777                         }
1778 
1779                         if (done) {
1780                             break;
1781                         }
1782                         memoryAddress += res;
1783                         bufferReadable -= res;
1784                     } while (bufferReadable > 0 && !conn.isFreed());
1785                 } finally {
1786                     buffer.skipBytes((int) (memoryAddress - Quiche.readerMemoryAddress(buffer)));
1787                     if (tmpBuffer != null) {
1788                         tmpBuffer.release();
1789                     }
1790                 }
1791                 if (close) {
1792                     // Let's close now as there is no way to recover
1793                     unsafe().close(newPromise());
1794                 }
1795             } finally {
1796                 reantranceGuard &= ~IN_RECV;
1797             }
1798         }
1799 
1800         private void processReceived(QuicheQuicConnection conn) {
1801             // Handle pending channelActive if needed.
1802             if (handlePendingChannelActive(conn)) {
1803                 // Connection was closed right away.
1804                 return;
1805             }
1806 
1807             notifyAboutHandshakeCompletionIfNeeded(conn, null);
1808             fireConnectCloseEventIfNeeded(conn);
1809 
1810             if (conn.isFreed()) {
1811                 return;
1812             }
1813 
1814             long connAddr = conn.address();
1815             if (Quiche.quiche_conn_is_established(connAddr) ||
1816                     Quiche.quiche_conn_is_in_early_data(connAddr)) {
1817                 long uniLeftOld = uniStreamsLeft;
1818                 long bidiLeftOld = bidiStreamsLeft;
1819                 // Only fetch new stream info when we used all our credits. Also cover negative
1820                 // values: MAX_STREAMS can raise the peer's limit while the cached credits are
1821                 // still non-zero (this refresh only triggers once a direction hit 0), so the
1822                 // cache may lag behind quiche's real credits. createStream(...) then keeps
1823                 // succeeding on quiche's real credits while the cached count is decremented
1824                 // past zero, after which a == 0 check would never match again and the cached
1825                 // credits would be frozen below zero forever. The fail-fast check in
1826                 // connectStream(...) makes crossing zero impossible, so covering negatives
1827                 // here is a safety net that also recovers an already-negative cached value
1828                 // on the next received packet.
1829                 if (uniLeftOld <= 0 || bidiLeftOld <= 0) {
1830                     long uniLeft = Quiche.quiche_conn_peer_streams_left_uni(connAddr);
1831                     long bidiLeft = Quiche.quiche_conn_peer_streams_left_bidi(connAddr);
1832                     uniStreamsLeft = uniLeft;
1833                     bidiStreamsLeft = bidiLeft;
1834                     streamCreditsInitialized = true;
1835                     if (uniLeftOld != uniLeft || bidiLeftOld != bidiLeft) {
1836                         pipeline().fireUserEventTriggered(QuicStreamLimitChangedEvent.INSTANCE);
1837                     }
1838                 }
1839 
1840                 handlePathEvents(conn);
1841 
1842                 if (handleWritableStreams(conn)) {
1843                     // Some data was produced, let's flush.
1844                     flushParent();
1845                 }
1846 
1847                 datagramReadable = true;
1848                 streamReadable = true;
1849 
1850                 recvDatagram(conn);
1851                 recvStream(conn);
1852             }
1853         }
1854 
1855         private void handlePathEvents(QuicheQuicConnection conn) {
1856             long event;
1857             while (!conn.isFreed() && (event = Quiche.quiche_conn_path_event_next(conn.address())) > 0) {
1858                 try {
1859                     int type = Quiche.quiche_path_event_type(event);
1860 
1861                     if (type == Quiche.QUICHE_PATH_EVENT_NEW) {
1862                         Object[] ret = Quiche.quiche_path_event_new(event);
1863                         InetSocketAddress local = (InetSocketAddress) ret[0];
1864                         InetSocketAddress peer = (InetSocketAddress) ret[1];
1865                         pipeline().fireUserEventTriggered(new QuicPathEvent.New(local, peer));
1866                     } else if (type == Quiche.QUICHE_PATH_EVENT_VALIDATED) {
1867                         Object[] ret = Quiche.quiche_path_event_validated(event);
1868                         InetSocketAddress local = (InetSocketAddress) ret[0];
1869                         InetSocketAddress peer = (InetSocketAddress) ret[1];
1870                         pipeline().fireUserEventTriggered(new QuicPathEvent.Validated(local, peer));
1871                     } else if (type == Quiche.QUICHE_PATH_EVENT_FAILED_VALIDATION) {
1872                         Object[] ret = Quiche.quiche_path_event_failed_validation(event);
1873                         InetSocketAddress local = (InetSocketAddress) ret[0];
1874                         InetSocketAddress peer = (InetSocketAddress) ret[1];
1875                         pipeline().fireUserEventTriggered(new QuicPathEvent.FailedValidation(local, peer));
1876                     } else if (type == Quiche.QUICHE_PATH_EVENT_CLOSED) {
1877                         Object[] ret = Quiche.quiche_path_event_closed(event);
1878                         InetSocketAddress local = (InetSocketAddress) ret[0];
1879                         InetSocketAddress peer = (InetSocketAddress) ret[1];
1880                         pipeline().fireUserEventTriggered(new QuicPathEvent.Closed(local, peer));
1881                     } else if (type == Quiche.QUICHE_PATH_EVENT_REUSED_SOURCE_CONNECTION_ID) {
1882                         Object[] ret = Quiche.quiche_path_event_reused_source_connection_id(event);
1883                         Long seq = (Long) ret[0];
1884                         InetSocketAddress localOld = (InetSocketAddress) ret[1];
1885                         InetSocketAddress peerOld = (InetSocketAddress) ret[2];
1886                         InetSocketAddress local = (InetSocketAddress) ret[3];
1887                         InetSocketAddress peer = (InetSocketAddress) ret[4];
1888                         pipeline().fireUserEventTriggered(
1889                                 new QuicPathEvent.ReusedSourceConnectionId(seq, localOld, peerOld, local, peer));
1890                     } else if (type == Quiche.QUICHE_PATH_EVENT_PEER_MIGRATED) {
1891                         Object[] ret = Quiche.quiche_path_event_peer_migrated(event);
1892                         InetSocketAddress local = (InetSocketAddress) ret[0];
1893                         InetSocketAddress peer = (InetSocketAddress) ret[1];
1894                         pipeline().fireUserEventTriggered(new QuicPathEvent.PeerMigrated(local, peer));
1895                     }
1896                 } finally {
1897                     Quiche.quiche_path_event_free(event);
1898                 }
1899             }
1900         }
1901 
1902         private void runAllTaskRecv(QuicheQuicConnection conn, Runnable task) {
1903             sslTaskExecutor.execute(decorateTaskRecv(conn, task));
1904         }
1905 
1906         private Runnable decorateTaskRecv(QuicheQuicConnection conn, Runnable task) {
1907             return () -> {
1908                 try {
1909                     runAll(conn, task);
1910                 } finally {
1911                     // Move back to the EventLoop.
1912                     eventLoop().execute(() -> {
1913                         if (!conn.isFreed()) {
1914                             processReceived(conn);
1915 
1916                             // Call connection send to continue handshake if needed.
1917                             if (connectionSend(conn) != SendResult.NONE) {
1918                                 forceFlushParent();
1919                             }
1920 
1921                             freeIfClosed();
1922                         }
1923                     });
1924                 }
1925             };
1926         }
1927         void recv() {
1928             QuicheQuicConnection conn = connection;
1929             if ((reantranceGuard & IN_RECV) != 0 || conn.isFreed()) {
1930                 return;
1931             }
1932 
1933             long connAddr = conn.address();
1934             // Check if we can read anything yet.
1935             if (!Quiche.quiche_conn_is_established(connAddr) &&
1936                     !Quiche.quiche_conn_is_in_early_data(connAddr)) {
1937                 return;
1938             }
1939 
1940             reantranceGuard |= IN_RECV;
1941             try {
1942                 recvDatagram(conn);
1943                 recvStream(conn);
1944             } finally {
1945                 fireChannelReadCompleteIfNeeded();
1946                 reantranceGuard &= ~IN_RECV;
1947             }
1948         }
1949 
1950         private void recvStream(QuicheQuicConnection conn) {
1951             if (conn.isFreed()) {
1952                 return;
1953             }
1954             long connAddr = conn.address();
1955             long readableIterator = Quiche.quiche_conn_readable(connAddr);
1956             int totalReadable = 0;
1957             if (readableIterator != -1) {
1958                 try {
1959                     // For streams we always process all streams when at least on read was requested.
1960                     if (recvStreamPending && streamReadable) {
1961                         for (;;) {
1962                             int readable = Quiche.quiche_stream_iter_next(
1963                                     readableIterator, readableStreams);
1964                             for (int i = 0; i < readable; i++) {
1965                                 long streamId = readableStreams[i];
1966                                 QuicheQuicStreamChannel streamChannel = streams.get(streamId);
1967                                 if (streamChannel == null) {
1968                                     recvStreamPending = false;
1969                                     fireChannelReadCompletePending = true;
1970                                     streamChannel = addNewStreamChannel(streamId);
1971                                     streamChannel.readable();
1972                                     pipeline().fireChannelRead(streamChannel);
1973                                 } else {
1974                                     streamChannel.readable();
1975                                 }
1976                             }
1977                             if (readable < readableStreams.length) {
1978                                 // We did consume all readable streams.
1979                                 streamReadable = false;
1980                                 break;
1981                             }
1982                             if (readable > 0) {
1983                                 totalReadable += readable;
1984                             }
1985                         }
1986                     }
1987                 } finally {
1988                     Quiche.quiche_stream_iter_free(readableIterator);
1989                 }
1990                 readableStreams = growIfNeeded(readableStreams, totalReadable);
1991             }
1992         }
1993 
1994         private void recvDatagram(QuicheQuicConnection conn) {
1995             if (!supportsDatagram) {
1996                 return;
1997             }
1998             while (recvDatagramPending && datagramReadable && !conn.isFreed()) {
1999                 @SuppressWarnings("deprecation")
2000                 RecvByteBufAllocator.Handle recvHandle = recvBufAllocHandle();
2001                 recvHandle.reset(config());
2002 
2003                 int numMessagesRead = 0;
2004                 do {
2005                     long connAddr = conn.address();
2006                     int len = Quiche.quiche_conn_dgram_recv_front_len(connAddr);
2007                     if (len == Quiche.QUICHE_ERR_DONE) {
2008                         datagramReadable = false;
2009                         return;
2010                     }
2011 
2012                     ByteBuf datagramBuffer = alloc().directBuffer(len);
2013                     recvHandle.attemptedBytesRead(datagramBuffer.writableBytes());
2014                     int writerIndex = datagramBuffer.writerIndex();
2015                     long memoryAddress = Quiche.writerMemoryAddress(datagramBuffer);
2016 
2017                     int written = Quiche.quiche_conn_dgram_recv(connAddr,
2018                             memoryAddress, datagramBuffer.writableBytes());
2019                     if (written < 0) {
2020                         datagramBuffer.release();
2021                         if (written == Quiche.QUICHE_ERR_DONE) {
2022                             // We did consume all datagram packets.
2023                             datagramReadable = false;
2024                             break;
2025                         }
2026                         pipeline().fireExceptionCaught(Quiche.convertToException(written));
2027                     }
2028                     recvHandle.lastBytesRead(written);
2029                     recvHandle.incMessagesRead(1);
2030                     numMessagesRead++;
2031                     datagramBuffer.writerIndex(writerIndex + written);
2032                     recvDatagramPending = false;
2033                     fireChannelReadCompletePending = true;
2034 
2035                     pipeline().fireChannelRead(datagramBuffer);
2036                 } while (recvHandle.continueReading() && !conn.isFreed());
2037                 recvHandle.readComplete();
2038 
2039                 // Check if we produced any messages.
2040                 if (numMessagesRead > 0) {
2041                     fireChannelReadCompleteIfNeeded();
2042                 }
2043             }
2044         }
2045 
2046         private boolean handlePendingChannelActive(QuicheQuicConnection conn) {
2047             if (conn.isFreed() || state == ChannelState.CLOSED) {
2048                 return true;
2049             }
2050             if (server) {
2051                 if (state == ChannelState.OPEN && Quiche.quiche_conn_is_established(conn.address())) {
2052                     // We didn't notify before about channelActive... Update state and fire the event.
2053                     state = ChannelState.ACTIVE;
2054 
2055                     fireDatagramExtensionEvent(conn);
2056                     pipeline().fireChannelActive();
2057                     notifyAboutHandshakeCompletionIfNeeded(conn, null);
2058                 }
2059             } else if (connectPromise != null && Quiche.quiche_conn_is_established(conn.address())) {
2060                 ChannelPromise promise = connectPromise;
2061                 connectPromise = null;
2062                 state = ChannelState.ACTIVE;
2063 
2064                 boolean promiseSet = promise.trySuccess();
2065                 fireDatagramExtensionEvent(conn);
2066                 pipeline().fireChannelActive();
2067                 notifyAboutHandshakeCompletionIfNeeded(conn, null);
2068                 if (!promiseSet) {
2069                     fireConnectCloseEventIfNeeded(conn);
2070                     this.close(this.voidPromise());
2071                     return true;
2072                 }
2073             }
2074             return false;
2075         }
2076 
2077         private void fireDatagramExtensionEvent(QuicheQuicConnection conn) {
2078             if (conn.isClosed()) {
2079                 return;
2080             }
2081             long connAddr = conn.address();
2082             int len = Quiche.quiche_conn_dgram_max_writable_len(connAddr);
2083             // QUICHE_ERR_DONE means the remote peer does not support the extension.
2084             if (len != Quiche.QUICHE_ERR_DONE) {
2085                 pipeline().fireUserEventTriggered(new QuicDatagramExtensionEvent(len));
2086             }
2087         }
2088 
2089         private QuicheQuicStreamChannel addNewStreamChannel(long streamId) {
2090             QuicheQuicStreamChannel streamChannel = new QuicheQuicStreamChannel(
2091                     QuicheQuicChannel.this, streamId);
2092             QuicheQuicStreamChannel old = streams.put(streamId, streamChannel);
2093             assert old == null;
2094             streamChannel.writable(streamCapacity(streamId));
2095             return streamChannel;
2096         }
2097     }
2098 
2099     /**
2100      * Finish the connect operation of a client channel.
2101      */
2102     void finishConnect() {
2103         assert !server;
2104         assert connection != null;
2105         if (connectionSend(connection) != SendResult.NONE) {
2106             flushParent();
2107         }
2108     }
2109 
2110     private void notifyEarlyDataReadyIfNeeded(QuicheQuicConnection conn) {
2111         if (!server && !earlyDataReadyNotified &&
2112                 !conn.isFreed() && Quiche.quiche_conn_is_in_early_data(conn.address())) {
2113             earlyDataReadyNotified = true;
2114             pipeline().fireUserEventTriggered(SslEarlyDataReadyEvent.INSTANCE);
2115         }
2116     }
2117 
2118     private final class TimeoutHandler implements Runnable {
2119         private ScheduledFuture<?> timeoutFuture;
2120 
2121         @Override
2122         public void run() {
2123             QuicheQuicConnection conn = connection;
2124             if (conn.isFreed()) {
2125                 return;
2126             }
2127             if (!freeIfClosed()) {
2128                 long connAddr = conn.address();
2129                 timeoutFuture = null;
2130                 // Notify quiche there was a timeout.
2131                 Quiche.quiche_conn_on_timeout(connAddr);
2132                 if (!freeIfClosed()) {
2133                     // We need to call connectionSend when a timeout was triggered.
2134                     // See https://docs.rs/quiche/0.6.0/quiche/struct.Connection.html#method.send.
2135                     if (connectionSend(conn) != SendResult.NONE) {
2136                         flushParent();
2137                     }
2138                     boolean closed = freeIfClosed();
2139                     if (!closed) {
2140                         // The connection is alive, reschedule.
2141                         scheduleTimeout();
2142                     }
2143                 }
2144             }
2145         }
2146 
2147         // Schedule timeout.
2148         // See https://docs.rs/quiche/0.6.0/quiche/#generating-outgoing-packets
2149         void scheduleTimeout() {
2150             QuicheQuicConnection conn = connection;
2151             if (conn.isFreed()) {
2152                 cancel();
2153                 return;
2154             }
2155             if (conn.isClosed()) {
2156                 cancel();
2157                 unsafe().close(newPromise());
2158                 return;
2159             }
2160             long nanos = Quiche.quiche_conn_timeout_as_nanos(conn.address());
2161             if (nanos < 0 || nanos == Long.MAX_VALUE) {
2162                 // No timeout needed.
2163                 cancel();
2164                 return;
2165             }
2166             if (timeoutFuture == null) {
2167                 timeoutFuture = eventLoop().schedule(this,
2168                         nanos, TimeUnit.NANOSECONDS);
2169             } else {
2170                 long remaining = timeoutFuture.getDelay(TimeUnit.NANOSECONDS);
2171                 if (remaining <= 0) {
2172                     // This means the timer already elapsed. In this case just cancel the future and call run()
2173                     // directly. This will ensure we correctly call quiche_conn_on_timeout() etc.
2174                     cancel();
2175                     run();
2176                 } else if (remaining > nanos) {
2177                     // The new timeout is smaller then what was scheduled before. Let's cancel the old timeout
2178                     // and schedule a new one.
2179                     cancel();
2180                     timeoutFuture = eventLoop().schedule(this, nanos, TimeUnit.NANOSECONDS);
2181                 }
2182             }
2183         }
2184 
2185         void cancel() {
2186             if (timeoutFuture != null) {
2187                 timeoutFuture.cancel(false);
2188                 timeoutFuture = null;
2189             }
2190         }
2191     }
2192 
2193     @Override
2194     public Future<QuicConnectionStats> collectStats(Promise<QuicConnectionStats> promise) {
2195         if (eventLoop().inEventLoop()) {
2196             collectStats0(promise);
2197         } else {
2198             eventLoop().execute(() -> collectStats0(promise));
2199         }
2200         return promise;
2201     }
2202 
2203     private void collectStats0(Promise<QuicConnectionStats> promise) {
2204         QuicheQuicConnection conn = connection;
2205         if (conn.isFreed()) {
2206             promise.setSuccess(statsAtClose);
2207             return;
2208         }
2209 
2210         collectStats0(connection, promise);
2211     }
2212 
2213     @Nullable
2214     private QuicConnectionStats collectStats0(QuicheQuicConnection connection, Promise<QuicConnectionStats> promise) {
2215         final long[] stats = Quiche.quiche_conn_stats(connection.address());
2216         if (stats == null) {
2217             promise.setFailure(new IllegalStateException("native quiche_conn_stats(...) failed"));
2218             return null;
2219         }
2220 
2221         final QuicheQuicConnectionStats connStats =
2222             new QuicheQuicConnectionStats(stats);
2223         promise.setSuccess(connStats);
2224         return connStats;
2225     }
2226 
2227     @Override
2228     public Future<QuicConnectionPathStats> collectPathStats(int pathIdx, Promise<QuicConnectionPathStats> promise) {
2229         if (eventLoop().inEventLoop()) {
2230             collectPathStats0(pathIdx, promise);
2231         } else {
2232             eventLoop().execute(() -> collectPathStats0(pathIdx, promise));
2233         }
2234         return promise;
2235     }
2236 
2237     private void collectPathStats0(int pathIdx, Promise<QuicConnectionPathStats> promise) {
2238         QuicheQuicConnection conn = connection;
2239         if (conn.isFreed()) {
2240             promise.setFailure(new IllegalStateException("Connection is closed"));
2241             return;
2242         }
2243 
2244         final Object[] stats = Quiche.quiche_conn_path_stats(connection.address(), pathIdx);
2245         if (stats == null) {
2246             promise.setFailure(new IllegalStateException("native quiche_conn_path_stats(...) failed"));
2247             return;
2248         }
2249         promise.setSuccess(new QuicheQuicConnectionPathStats(stats));
2250     }
2251 
2252     @Override
2253     public QuicTransportParameters peerTransportParameters() {
2254         return connection.peerParameters();
2255     }
2256 }