1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
62
63
64 private ChannelPromise connectPromise;
65 private Future<?> connectTimeoutFuture;
66 private SocketAddress requestedRemoteAddress;
67
68
69
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
90
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
101
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
131
132
133 final void fastOpenDataSent(ChannelOutboundBuffer in, Object data, long bytes) {
134 fastOpenOutboundBuffer = in;
135 fastOpenData = data;
136 fastOpenBytes = bytes;
137 }
138
139
140
141
142
143
144
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
166
167 doDeregister();
168
169 active = false;
170
171
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
204
205 readFilterEnabled = false;
206 writeFilterEnabled = false;
207 }
208
209 void unregisterFilters() throws Exception {
210
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
223 final AbstractKQueueUnsafe unsafe = (AbstractKQueueUnsafe) unsafe();
224 unsafe.readPending = true;
225
226
227
228
229 readFilter(true);
230 }
231
232 @Override
233 protected void doRegister() throws Exception {
234
235
236
237 readReadyRunnablePending = false;
238
239 registration = ((KQueueEventLoop) eventLoop()).add(this);
240
241
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
259
260 protected final ByteBuf newDirectBuffer(ByteBuf buf) {
261 return newDirectBuffer(buf, buf);
262 }
263
264
265
266
267
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
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
358 if (isRegistered()) {
359 final EventLoop loop = eventLoop();
360 final AbstractKQueueUnsafe unsafe = (AbstractKQueueUnsafe) unsafe();
361 if (loop.inEventLoop()) {
362 unsafe.clearReadFilter0();
363 } else {
364
365 loop.execute(new Runnable() {
366 @Override
367 public void run() {
368 if (!unsafe.readPending && !config().isAutoRead()) {
369
370 unsafe.clearReadFilter0();
371 }
372 }
373 });
374 }
375 } else {
376
377
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
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
426
427
428
429
430
431 return !readPending && !config.isAutoRead();
432 }
433
434 final boolean failConnectPromise(Throwable cause) {
435 if (connectPromise != null) {
436
437
438
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
453 finishConnect();
454 } else if (!socket.isOutputShutdown()) {
455
456 super.flush0();
457 }
458 }
459
460
461
462
463 void shutdownInput(boolean readEOF) {
464
465
466
467
468
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
478
479 fireEventAndClose(ChannelInputShutdownEvent.INSTANCE);
480 return;
481 } catch (NotYetConnectedException ignore) {
482
483
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
502 final KQueueRecvByteAllocatorHandle allocHandle = recvBufAllocHandle();
503 allocHandle.readEOF();
504
505
506
507
508 if (connectPromise != null) {
509 finishConnect();
510 }
511
512 if (isActive()) {
513
514
515
516 readReady(allocHandle);
517 } else {
518
519 shutdownInput(true);
520 }
521
522
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
538
539
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
552
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
567
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
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
605
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
625 return;
626 }
627 active = true;
628
629
630
631 boolean active = isActive();
632
633
634 boolean promiseSet = promise.trySuccess();
635
636
637
638 if (!wasActive && active) {
639 pipeline().fireChannelActive();
640 }
641
642
643
644 if (removeFastOpenData()) {
645 flush0();
646 }
647
648
649 if (!promiseSet) {
650 close(voidPromise());
651 }
652 }
653
654 private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) {
655
656
657 removeFastOpenData();
658 if (promise == null) {
659
660 return;
661 }
662
663
664 promise.tryFailure(cause);
665 closeIfClosed();
666 }
667
668 private void finishConnect() {
669
670
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
687
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
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
735
736
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
750
751
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 }