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