View Javadoc
1   /*
2    * Copyright 2016 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.channel.kqueue;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.buffer.ByteBufUtil;
21  import io.netty.buffer.Unpooled;
22  import io.netty.channel.AbstractChannel;
23  import io.netty.channel.Channel;
24  import io.netty.channel.ChannelConfig;
25  import io.netty.channel.ChannelException;
26  import io.netty.channel.ChannelFuture;
27  import io.netty.channel.ChannelFutureListener;
28  import io.netty.channel.ChannelMetadata;
29  import io.netty.channel.ChannelOutboundBuffer;
30  import io.netty.channel.ChannelPromise;
31  import io.netty.channel.ConnectTimeoutException;
32  import io.netty.channel.EventLoop;
33  import io.netty.channel.RecvByteBufAllocator;
34  import io.netty.channel.socket.ChannelInputShutdownEvent;
35  import io.netty.channel.socket.ChannelInputShutdownReadComplete;
36  import io.netty.channel.socket.SocketChannelConfig;
37  import io.netty.channel.unix.FileDescriptor;
38  import io.netty.channel.unix.UnixChannel;
39  import io.netty.util.ReferenceCountUtil;
40  import io.netty.util.concurrent.Future;
41  import io.netty.util.internal.UnstableApi;
42  
43  import java.io.IOException;
44  import java.net.ConnectException;
45  import java.net.InetSocketAddress;
46  import java.net.SocketAddress;
47  import java.nio.ByteBuffer;
48  import java.nio.channels.AlreadyConnectedException;
49  import java.nio.channels.ConnectionPendingException;
50  import java.nio.channels.NotYetConnectedException;
51  import java.nio.channels.UnresolvedAddressException;
52  import java.util.concurrent.TimeUnit;
53  
54  import static io.netty.channel.internal.ChannelUtils.WRITE_STATUS_SNDBUF_FULL;
55  import static io.netty.channel.unix.UnixChannelUtil.computeRemoteAddr;
56  import static io.netty.util.internal.ObjectUtil.checkNotNull;
57  
58  abstract class AbstractKQueueChannel extends AbstractChannel implements UnixChannel {
59      private static final ChannelMetadata METADATA = new ChannelMetadata(false);
60      /**
61       * The future of the current connection attempt.  If not null, subsequent
62       * connection attempts will fail.
63       */
64      private ChannelPromise connectPromise;
65      private Future<?> connectTimeoutFuture;
66      private SocketAddress requestedRemoteAddress;
67  
68      // The initial data that was sent by a TCP_FASTOPEN_CONNECT. Its bytes are only removed from the
69      // ChannelOutboundBuffer once the connect is complete, so listeners of the initial write see an active channel.
70      private ChannelOutboundBuffer fastOpenOutboundBuffer;
71      private Object fastOpenData;
72      private long fastOpenBytes;
73  
74      final BsdSocket socket;
75      private boolean readFilterEnabled;
76      private boolean writeFilterEnabled;
77      KQueueEventLoop.KQueueRegistration registration;
78      boolean readReadyRunnablePending;
79      boolean inputClosedSeenErrorOnRead;
80      protected volatile boolean active;
81      private volatile SocketAddress local;
82      private volatile SocketAddress remote;
83  
84      AbstractKQueueChannel(Channel parent, BsdSocket fd, boolean active) {
85          super(parent);
86          socket = checkNotNull(fd, "fd");
87          this.active = active;
88          if (active) {
89              // Directly cache the remote and local addresses
90              // See https://github.com/netty/netty/issues/2359
91              local = fd.localAddress();
92              remote = fd.remoteAddress();
93          }
94      }
95  
96      AbstractKQueueChannel(Channel parent, BsdSocket fd, SocketAddress remote) {
97          super(parent);
98          socket = checkNotNull(fd, "fd");
99          active = true;
100         // Directly cache the remote and local addresses
101         // See https://github.com/netty/netty/issues/2359
102         this.remote = remote;
103         local = fd.localAddress();
104     }
105 
106     static boolean isSoErrorZero(BsdSocket fd) {
107         try {
108             return fd.getSoError() == 0;
109         } catch (IOException e) {
110             throw new ChannelException(e);
111         }
112     }
113 
114     @Override
115     public final FileDescriptor fd() {
116         return socket;
117     }
118 
119     @Override
120     public boolean isActive() {
121         return active;
122     }
123 
124     @Override
125     public ChannelMetadata metadata() {
126         return METADATA;
127     }
128 
129     /**
130      * Remember that {@code bytes} of {@code data}, the current message of {@code in}, were sent by a
131      * TCP_FASTOPEN_CONNECT.
132      */
133     final void fastOpenDataSent(ChannelOutboundBuffer in, Object data, long bytes) {
134         fastOpenOutboundBuffer = in;
135         fastOpenData = data;
136         fastOpenBytes = bytes;
137     }
138 
139     /**
140      * Removes the bytes that were sent by a TCP_FASTOPEN_CONNECT from the {@link ChannelOutboundBuffer} if the
141      * channel was connected, and forgets about them otherwise. Must be called before the
142      * {@link ChannelOutboundBuffer} is written or its messages are failed.
143      *
144      * @return {@code true} if bytes were removed.
145      */
146     final boolean removeFastOpenData() {
147         ChannelOutboundBuffer in = fastOpenOutboundBuffer;
148         if (in == null) {
149             return false;
150         }
151         Object data = fastOpenData;
152         long bytes = fastOpenBytes;
153         fastOpenOutboundBuffer = null;
154         fastOpenData = null;
155         fastOpenBytes = 0;
156         if (!isActive() || in.current() != data) {
157             return false;
158         }
159         in.removeBytes(bytes);
160         return true;
161     }
162 
163     @Override
164     protected void doClose() throws Exception {
165         // Clear kqueue registrations *before* we close the file descriptor.
166         // Otherwise, the filter removals might hit a reused file descriptor.
167         doDeregister();
168 
169         active = false;
170         // Even if we allow half closed sockets we should give up on reading. Otherwise we may allow a read attempt on a
171         // socket which has not even been connected yet. This has been observed to block during unit tests.
172         inputClosedSeenErrorOnRead = true;
173         socket.close();
174     }
175 
176     @Override
177     protected void doDisconnect() throws Exception {
178         doClose();
179     }
180 
181     void resetCachedAddresses() {
182         local = socket.localAddress();
183         remote = socket.remoteAddress();
184     }
185 
186     @Override
187     protected boolean isCompatible(EventLoop loop) {
188         return loop instanceof KQueueEventLoop;
189     }
190 
191     @Override
192     public boolean isOpen() {
193         return socket.isOpen();
194     }
195 
196     @Override
197     protected void doDeregister() throws Exception {
198         if (registration != null) {
199             registration.remove();
200             registration = null;
201         }
202 
203         // As unregisteredFilters() may have not been called because isOpen() returned false we just set both filters
204         // to false to ensure a consistent state in all cases.
205         readFilterEnabled = false;
206         writeFilterEnabled = false;
207     }
208 
209     void unregisterFilters() throws Exception {
210         // Make sure we unregister our filters from kqueue!
211         readFilter(false);
212         writeFilter(false);
213         clearRdHup0();
214     }
215 
216     private void clearRdHup0() {
217         evSet0(Native.EVFILT_SOCK, Native.EV_DELETE_DISABLE, Native.NOTE_RDHUP);
218     }
219 
220     @Override
221     protected final void doBeginRead() throws Exception {
222         // Channel.read() or ChannelHandlerContext.read() was called
223         final AbstractKQueueUnsafe unsafe = (AbstractKQueueUnsafe) unsafe();
224         unsafe.readPending = true;
225 
226         // We must set the read flag here as it is possible the user didn't read in the last read loop, the
227         // executeReadReadyRunnable could read nothing, and if the user doesn't explicitly call read they will
228         // never get data after this.
229         readFilter(true);
230     }
231 
232     @Override
233     protected void doRegister() throws Exception {
234         // Just in case the previous EventLoop was shutdown abruptly, or an event is still pending on the old EventLoop
235         // make sure the readReadyRunnablePending variable is reset so we will be able to execute the Runnable on the
236         // new EventLoop.
237         readReadyRunnablePending = false;
238 
239         registration = ((KQueueEventLoop) eventLoop()).add(this);
240 
241         // Add the write event first so we get notified of connection refused on the client side!
242         if (writeFilterEnabled) {
243             evSet0(Native.EVFILT_WRITE, Native.EV_ADD_ENABLE);
244         }
245         if (readFilterEnabled) {
246             evSet0(Native.EVFILT_READ, Native.EV_ADD_ENABLE);
247         }
248         evSet0(Native.EVFILT_SOCK, Native.EV_ADD, Native.NOTE_RDHUP);
249     }
250 
251     @Override
252     protected abstract AbstractKQueueUnsafe newUnsafe();
253 
254     @Override
255     public abstract KQueueChannelConfig config();
256 
257     /**
258      * Returns an off-heap copy of the specified {@link ByteBuf}, and releases the original one.
259      */
260     protected final ByteBuf newDirectBuffer(ByteBuf buf) {
261         return newDirectBuffer(buf, buf);
262     }
263 
264     /**
265      * Returns an off-heap copy of the specified {@link ByteBuf}, and releases the specified holder.
266      * The caller must ensure that the holder releases the original {@link ByteBuf} when the holder is released by
267      * this method.
268      */
269     protected final ByteBuf newDirectBuffer(Object holder, ByteBuf buf) {
270         final int readableBytes = buf.readableBytes();
271         if (readableBytes == 0) {
272             ReferenceCountUtil.release(holder);
273             return Unpooled.EMPTY_BUFFER;
274         }
275 
276         final ByteBufAllocator alloc = alloc();
277         if (alloc.isDirectBufferPooled()) {
278             return newDirectBuffer0(holder, buf, alloc, readableBytes);
279         }
280 
281         final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer();
282         if (directBuf == null) {
283             return newDirectBuffer0(holder, buf, alloc, readableBytes);
284         }
285 
286         directBuf.writeBytes(buf, buf.readerIndex(), readableBytes);
287         ReferenceCountUtil.safeRelease(holder);
288         return directBuf;
289     }
290 
291     private static ByteBuf newDirectBuffer0(Object holder, ByteBuf buf, ByteBufAllocator alloc, int capacity) {
292         final ByteBuf directBuf = alloc.directBuffer(capacity);
293         directBuf.writeBytes(buf, buf.readerIndex(), capacity);
294         ReferenceCountUtil.safeRelease(holder);
295         return directBuf;
296     }
297 
298     protected static void checkResolvable(InetSocketAddress addr) {
299         if (addr.isUnresolved()) {
300             throw new UnresolvedAddressException();
301         }
302     }
303 
304     /**
305      * Read bytes into the given {@link ByteBuf} and return the amount.
306      */
307     protected final int doReadBytes(ByteBuf byteBuf) throws Exception {
308         int writerIndex = byteBuf.writerIndex();
309         int localReadAmount;
310         unsafe().recvBufAllocHandle().attemptedBytesRead(byteBuf.writableBytes());
311         if (byteBuf.hasMemoryAddress()) {
312             localReadAmount = socket.readAddress(byteBuf.memoryAddress(), writerIndex, byteBuf.capacity());
313         } else {
314             ByteBuffer buf = byteBuf.internalNioBuffer(writerIndex, byteBuf.writableBytes());
315             localReadAmount = socket.read(buf, buf.position(), buf.limit());
316         }
317         if (localReadAmount > 0) {
318             byteBuf.writerIndex(writerIndex + localReadAmount);
319         }
320         return localReadAmount;
321     }
322 
323     protected final int doWriteBytes(ChannelOutboundBuffer in, ByteBuf buf) throws Exception {
324         if (buf.hasMemoryAddress()) {
325             int localFlushedAmount = socket.writeAddress(buf.memoryAddress(), buf.readerIndex(), buf.writerIndex());
326             if (localFlushedAmount > 0) {
327                 in.removeBytes(localFlushedAmount);
328                 return 1;
329             }
330         } else {
331             final ByteBuffer nioBuf = buf.nioBufferCount() == 1?
332                     buf.internalNioBuffer(buf.readerIndex(), buf.readableBytes()) : buf.nioBuffer();
333             int localFlushedAmount = socket.write(nioBuf, nioBuf.position(), nioBuf.limit());
334             if (localFlushedAmount > 0) {
335                 nioBuf.position(nioBuf.position() + localFlushedAmount);
336                 in.removeBytes(localFlushedAmount);
337                 return 1;
338             }
339         }
340         return WRITE_STATUS_SNDBUF_FULL;
341     }
342 
343     final boolean shouldBreakReadReady(ChannelConfig config) {
344         return socket.isInputShutdown() && (inputClosedSeenErrorOnRead || !isAllowHalfClosure(config));
345     }
346 
347     private static boolean isAllowHalfClosure(ChannelConfig config) {
348         if (config instanceof KQueueDomainSocketChannelConfig) {
349             return ((KQueueDomainSocketChannelConfig) config).isAllowHalfClosure();
350         }
351 
352         return config instanceof SocketChannelConfig &&
353                 ((SocketChannelConfig) config).isAllowHalfClosure();
354     }
355 
356     final void clearReadFilter() {
357         // Only clear if registered with an EventLoop as otherwise
358         if (isRegistered()) {
359             final EventLoop loop = eventLoop();
360             final AbstractKQueueUnsafe unsafe = (AbstractKQueueUnsafe) unsafe();
361             if (loop.inEventLoop()) {
362                 unsafe.clearReadFilter0();
363             } else {
364                 // schedule a task to clear the EPOLLIN as it is not safe to modify it directly
365                 loop.execute(new Runnable() {
366                     @Override
367                     public void run() {
368                         if (!unsafe.readPending && !config().isAutoRead()) {
369                             // Still no read triggered so clear it now
370                             unsafe.clearReadFilter0();
371                         }
372                     }
373                 });
374             }
375         } else  {
376             // The EventLoop is not registered atm so just update the flags so the correct value
377             // will be used once the channel is registered
378             readFilterEnabled = false;
379         }
380     }
381 
382     void readFilter(boolean readFilterEnabled) throws IOException {
383         if (this.readFilterEnabled != readFilterEnabled) {
384             this.readFilterEnabled = readFilterEnabled;
385             evSet(Native.EVFILT_READ, readFilterEnabled ? Native.EV_ADD_ENABLE : Native.EV_DELETE_DISABLE);
386         }
387     }
388 
389     void writeFilter(boolean writeFilterEnabled) throws IOException {
390         if (this.writeFilterEnabled != writeFilterEnabled) {
391             this.writeFilterEnabled = writeFilterEnabled;
392             evSet(Native.EVFILT_WRITE, writeFilterEnabled ? Native.EV_ADD_ENABLE : Native.EV_DELETE_DISABLE);
393         }
394     }
395 
396     private void evSet(short filter, short flags) {
397         if (isRegistered()) {
398             evSet0(filter, flags);
399         }
400     }
401 
402     private void evSet0(short filter, short flags) {
403         evSet0(filter, flags, 0);
404     }
405 
406     private void evSet0(short filter, short flags, int fflags) {
407         // Only try to add to changeList if the FD is still open, if not we already closed it in the meantime.
408         if (isOpen() && registration != null) {
409             registration.evSet(filter, flags, fflags, 0);
410         }
411     }
412 
413     @UnstableApi
414     public abstract class AbstractKQueueUnsafe extends AbstractUnsafe {
415         boolean readPending;
416         private KQueueRecvByteAllocatorHandle allocHandle;
417 
418         void readReady() {
419             readReady(recvBufAllocHandle());
420         }
421 
422         abstract void readReady(KQueueRecvByteAllocatorHandle allocHandle);
423 
424         final boolean shouldStopReading(ChannelConfig config) {
425             // Check if there is a readPending which was not processed yet.
426             // This could be for two reasons:
427             // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
428             // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method
429             //
430             // See https://github.com/netty/netty/issues/2254
431             return !readPending && !config.isAutoRead();
432         }
433 
434         final boolean failConnectPromise(Throwable cause) {
435             if (connectPromise != null) {
436                 // SO_ERROR has been shown to return 0 on macOS if detect an error via read() and the write filter was
437                 // not set before calling connect. This means finishConnect will not detect any error and would
438                 // successfully complete the connectPromise and update the channel state to active (which is incorrect).
439                 ChannelPromise connectPromise = AbstractKQueueChannel.this.connectPromise;
440                 AbstractKQueueChannel.this.connectPromise = null;
441                 if (connectPromise.tryFailure((cause instanceof ConnectException) ? cause
442                                 : new ConnectException("failed to connect").initCause(cause))) {
443                     closeIfClosed();
444                     return true;
445                 }
446             }
447             return false;
448         }
449 
450         final void writeReady() {
451             if (connectPromise != null) {
452                 // pending connect which is now complete so handle it.
453                 finishConnect();
454             } else if (!socket.isOutputShutdown()) {
455                 // directly call super.flush0() to force a flush now
456                 super.flush0();
457             }
458         }
459 
460         /**
461          * Shutdown the input side of the channel.
462          */
463         void shutdownInput(boolean readEOF) {
464             // We need to take special care of calling finishConnect() if readEOF is true and we not
465             // fulfilled the connectPromise yet. If we fail to do so the connectPromise will be failed
466             // with a ClosedChannelException as a close() will happen and so the FD is closed before we
467             // have a chance to call finishConnect() later on. Calling finishConnect() here will ensure
468             // we observe the correct exception in case of a connect failure.
469             if (readEOF && connectPromise != null) {
470                 finishConnect();
471             }
472             if (!socket.isInputShutdown()) {
473                 if (isAllowHalfClosure(config())) {
474                     try {
475                         socket.shutdown(true, false);
476                     } catch (IOException ignored) {
477                         // We attempted to shutdown and failed, which means the input has already effectively been
478                         // shutdown.
479                         fireEventAndClose(ChannelInputShutdownEvent.INSTANCE);
480                         return;
481                     } catch (NotYetConnectedException ignore) {
482                         // We attempted to shutdown and failed, which means the input has already effectively been
483                         // shutdown.
484                     }
485                     if (shouldStopReading(config())) {
486                         clearReadFilter0();
487                     }
488                     pipeline().fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE);
489                 } else {
490                     close(voidPromise());
491                     return;
492                 }
493             }
494             if (!readEOF && !inputClosedSeenErrorOnRead) {
495                 inputClosedSeenErrorOnRead = true;
496                 pipeline().fireUserEventTriggered(ChannelInputShutdownReadComplete.INSTANCE);
497             }
498         }
499 
500         final void readEOF() {
501             // This must happen before we attempt to read. This will ensure reading continues until an error occurs.
502             final KQueueRecvByteAllocatorHandle allocHandle = recvBufAllocHandle();
503             allocHandle.readEOF();
504 
505             // kqueue reports each filter as its own event, so the EOF may be processed before the EVFILT_WRITE event
506             // that completes the connect. Finish the connect first so the data that the remote peer sent before it
507             // closed the connection is read, and not dropped by shutting down the input.
508             if (connectPromise != null) {
509                 finishConnect();
510             }
511 
512             if (isActive()) {
513                 // If it is still active, we need to call readReady as otherwise we may miss to
514                 // read pending data from the underlying file descriptor.
515                 // See https://github.com/netty/netty/issues/3709
516                 readReady(allocHandle);
517             } else {
518                 // Just to be safe make sure the input marked as closed.
519                 shutdownInput(true);
520             }
521 
522             // Clear the RDHUP flag to prevent continuously getting woken up on this event.
523             clearRdHup0();
524         }
525 
526         @Override
527         public KQueueRecvByteAllocatorHandle recvBufAllocHandle() {
528             if (allocHandle == null) {
529                 allocHandle = new KQueueRecvByteAllocatorHandle(
530                         (RecvByteBufAllocator.ExtendedHandle) super.recvBufAllocHandle());
531             }
532             return allocHandle;
533         }
534 
535         @Override
536         protected final void flush0() {
537             // Flush immediately only when there's no pending flush.
538             // If there's a pending flush operation, event loop will call forceFlush() later,
539             // and thus there's no need to call it now.
540             if (!writeFilterEnabled) {
541                 super.flush0();
542             }
543         }
544 
545         protected final void clearReadFilter0() {
546             assert eventLoop().inEventLoop();
547             try {
548                 readPending = false;
549                 readFilter(false);
550             } catch (IOException e) {
551                 // When this happens there is something completely wrong with either the filedescriptor or epoll,
552                 // so fire the exception through the pipeline and close the Channel.
553                 pipeline().fireExceptionCaught(e);
554                 unsafe().close(unsafe().voidPromise());
555             }
556         }
557 
558         private void fireEventAndClose(Object evt) {
559             pipeline().fireUserEventTriggered(evt);
560             close(voidPromise());
561         }
562 
563         @Override
564         public void connect(
565                 final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {
566             // Don't mark the connect promise as uncancellable as in fact we can cancel it as it is using
567             // non-blocking io.
568             if (promise.isDone() || !ensureOpen(promise)) {
569                 return;
570             }
571 
572             try {
573                 if (connectPromise != null) {
574                     throw new ConnectionPendingException();
575                 }
576 
577                 boolean wasActive = isActive();
578                 if (doConnect(remoteAddress, localAddress)) {
579                     fulfillConnectPromise(promise, wasActive);
580                 } else {
581                     connectPromise = promise;
582                     requestedRemoteAddress = remoteAddress;
583 
584                     // Schedule connect timeout.
585                     final int connectTimeoutMillis = config().getConnectTimeoutMillis();
586                     if (connectTimeoutMillis > 0) {
587                         connectTimeoutFuture = eventLoop().schedule(new Runnable() {
588                             @Override
589                             public void run() {
590                                 ChannelPromise connectPromise = AbstractKQueueChannel.this.connectPromise;
591                                 if (connectPromise != null && !connectPromise.isDone()
592                                         && connectPromise.tryFailure(new ConnectTimeoutException(
593                                                 "connection timed out after " + connectTimeoutMillis + " ms: " +
594                                                         remoteAddress))) {
595                                     close(voidPromise());
596                                 }
597                             }
598                         }, connectTimeoutMillis, TimeUnit.MILLISECONDS);
599                     }
600 
601                     promise.addListener(new ChannelFutureListener() {
602                         @Override
603                         public void operationComplete(ChannelFuture future) {
604                             // If the connect future is cancelled we also cancel the timeout and close the
605                             // underlying socket.
606                             if (future.isCancelled()) {
607                                 if (connectTimeoutFuture != null) {
608                                     connectTimeoutFuture.cancel(false);
609                                 }
610                                 connectPromise = null;
611                                 close(voidPromise());
612                             }
613                         }
614                     });
615                 }
616             } catch (Throwable t) {
617                 closeIfClosed();
618                 promise.tryFailure(annotateConnectException(t, remoteAddress));
619             }
620         }
621 
622         private void fulfillConnectPromise(ChannelPromise promise, boolean wasActive) {
623             if (promise == null) {
624                 // Closed via cancellation and the promise has been notified already.
625                 return;
626             }
627             active = true;
628 
629             // Get the state as trySuccess() may trigger an ChannelFutureListener that will close the Channel.
630             // We still need to ensure we call fireChannelActive() in this case.
631             boolean active = isActive();
632 
633             // trySuccess() will return false if a user cancelled the connection attempt.
634             boolean promiseSet = promise.trySuccess();
635 
636             // Regardless if the connection attempt was cancelled, channelActive() event should be triggered,
637             // because what happened is what happened.
638             if (!wasActive && active) {
639                 pipeline().fireChannelActive();
640             }
641 
642             // The connect is complete, so remove the initial data that was sent by TCP_FASTOPEN_CONNECT now and
643             // write what is left of it.
644             if (removeFastOpenData()) {
645                 flush0();
646             }
647 
648             // If a user cancelled the connection attempt, close the channel, which is followed by channelInactive().
649             if (!promiseSet) {
650                 close(voidPromise());
651             }
652         }
653 
654         private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) {
655             // The connect failed, so we don't know if the initial data that was sent by TCP_FASTOPEN_CONNECT
656             // was received.
657             removeFastOpenData();
658             if (promise == null) {
659                 // Closed via cancellation and the promise has been notified already.
660                 return;
661             }
662 
663             // Use tryFailure() instead of setFailure() to avoid the race against cancel().
664             promise.tryFailure(cause);
665             closeIfClosed();
666         }
667 
668         private void finishConnect() {
669             // Note this method is invoked by the event loop only if the connection attempt was
670             // neither cancelled nor timed out.
671 
672             assert eventLoop().inEventLoop();
673 
674             boolean connectStillInProgress = false;
675             try {
676                 boolean wasActive = isActive();
677                 if (!doFinishConnect()) {
678                     connectStillInProgress = true;
679                     return;
680                 }
681                 fulfillConnectPromise(connectPromise, wasActive);
682             } catch (Throwable t) {
683                 fulfillConnectPromise(connectPromise, annotateConnectException(t, requestedRemoteAddress));
684             } finally {
685                 if (!connectStillInProgress) {
686                     // Check for null as the connectTimeoutFuture is only created if a connectTimeoutMillis > 0 is used
687                     // See https://github.com/netty/netty/issues/1770
688                     if (connectTimeoutFuture != null) {
689                         connectTimeoutFuture.cancel(false);
690                     }
691                     connectPromise = null;
692                 }
693             }
694         }
695 
696         private boolean doFinishConnect() throws Exception {
697             if (socket.finishConnect()) {
698                 writeFilter(false);
699                 if (requestedRemoteAddress instanceof InetSocketAddress) {
700                     remote = computeRemoteAddr((InetSocketAddress) requestedRemoteAddress, socket.remoteAddress());
701                 }
702                 requestedRemoteAddress = null;
703                 return true;
704             }
705             writeFilter(true);
706             return false;
707         }
708     }
709 
710     @Override
711     protected void doBind(SocketAddress local) throws Exception {
712         if (local instanceof InetSocketAddress) {
713             checkResolvable((InetSocketAddress) local);
714         }
715         socket.bind(local);
716         this.local = socket.localAddress();
717     }
718 
719     /**
720      * Connect to the remote peer
721      */
722     protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
723         if (localAddress instanceof InetSocketAddress) {
724             checkResolvable((InetSocketAddress) localAddress);
725         }
726 
727         InetSocketAddress remoteSocketAddr = remoteAddress instanceof InetSocketAddress
728                 ? (InetSocketAddress) remoteAddress : null;
729         if (remoteSocketAddr != null) {
730             checkResolvable(remoteSocketAddr);
731         }
732 
733         if (remote != null) {
734             // Check if already connected before trying to connect. This is needed as connect(...) will not return -1
735             // and set errno to EISCONN if a previous connect(...) attempt was setting errno to EINPROGRESS and finished
736             // later.
737             throw new AlreadyConnectedException();
738         }
739 
740         if (localAddress != null) {
741             socket.bind(localAddress);
742         }
743 
744         boolean connected = doConnect0(remoteAddress, localAddress);
745         if (connected) {
746             remote = remoteSocketAddr == null?
747                     remoteAddress : computeRemoteAddr(remoteSocketAddr, socket.remoteAddress());
748         }
749         // We always need to set the localAddress even if not connected yet as the bind already took place.
750         //
751         // See https://github.com/netty/netty/issues/3463
752         local = socket.localAddress();
753         return connected;
754     }
755 
756     protected boolean doConnect0(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
757         boolean success = false;
758         try {
759             boolean connected = socket.connect(remoteAddress);
760             if (!connected) {
761                 writeFilter(true);
762             }
763             success = true;
764             return connected;
765         } finally {
766             if (!success) {
767                 doClose();
768             }
769         }
770     }
771 
772     @Override
773     protected SocketAddress localAddress0() {
774         return local;
775     }
776 
777     @Override
778     protected SocketAddress remoteAddress0() {
779         return remote;
780     }
781 }