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