View Javadoc
1   /*
2    * Copyright 2021 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.channel.AddressedEnvelope;
21  import io.netty.channel.ChannelPipeline;
22  import io.netty.channel.DefaultAddressedEnvelope;
23  import io.netty.channel.unix.DomainDatagramChannel;
24  import io.netty.channel.unix.DomainDatagramChannelConfig;
25  import io.netty.channel.unix.DomainDatagramPacket;
26  import io.netty.channel.unix.DomainDatagramSocketAddress;
27  import io.netty.channel.unix.DomainSocketAddress;
28  import io.netty.channel.unix.IovArray;
29  import io.netty.channel.unix.PeerCredentials;
30  import io.netty.channel.unix.UnixChannelUtil;
31  import io.netty.util.CharsetUtil;
32  import io.netty.util.UncheckedBooleanSupplier;
33  import io.netty.util.internal.StringUtil;
34  
35  import java.io.IOException;
36  import java.net.SocketAddress;
37  import java.nio.ByteBuffer;
38  
39  import static io.netty.channel.kqueue.BsdSocket.newSocketDomainDgram;
40  
41  public final class KQueueDomainDatagramChannel extends AbstractKQueueDatagramChannel implements DomainDatagramChannel {
42  
43      private static final String EXPECTED_TYPES =
44              " (expected: " +
45                      StringUtil.simpleClassName(DomainDatagramPacket.class) + ", " +
46                      StringUtil.simpleClassName(AddressedEnvelope.class) + '<' +
47                      StringUtil.simpleClassName(ByteBuf.class) + ", " +
48                      StringUtil.simpleClassName(DomainSocketAddress.class) + ">, " +
49                      StringUtil.simpleClassName(ByteBuf.class) + ')';
50  
51      private volatile boolean connected;
52      private volatile DomainSocketAddress local;
53      private volatile DomainSocketAddress remote;
54  
55      private final KQueueDomainDatagramChannelConfig config;
56  
57      public KQueueDomainDatagramChannel() {
58          this(newSocketDomainDgram(), false);
59      }
60  
61      public KQueueDomainDatagramChannel(int fd) {
62          this(new BsdSocket(fd), true);
63      }
64  
65      private KQueueDomainDatagramChannel(BsdSocket socket, boolean active) {
66          super(null, socket, active);
67          config = new KQueueDomainDatagramChannelConfig(this);
68      }
69  
70      @Override
71      public KQueueDomainDatagramChannelConfig config() {
72          return config;
73      }
74  
75      @Override
76      protected void doBind(SocketAddress localAddress) throws Exception {
77          super.doBind(localAddress);
78          local = (DomainSocketAddress) localAddress;
79          active = true;
80      }
81  
82      @Override
83      protected void doClose() throws Exception {
84          super.doClose();
85          connected = active = false;
86          local = null;
87          remote = null;
88      }
89  
90      @Override
91      protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
92          if (super.doConnect(remoteAddress, localAddress)) {
93              if (localAddress != null) {
94                  local = (DomainSocketAddress) localAddress;
95              }
96              remote = (DomainSocketAddress) remoteAddress;
97              connected = true;
98              return true;
99          }
100         return false;
101     }
102 
103     @Override
104     protected void doDisconnect() throws Exception {
105         doClose();
106     }
107 
108     @Override
109     protected boolean doWriteMessage(Object msg) throws Exception {
110         final ByteBuf data;
111         DomainSocketAddress remoteAddress;
112         if (msg instanceof AddressedEnvelope) {
113             @SuppressWarnings("unchecked")
114             AddressedEnvelope<ByteBuf, DomainSocketAddress> envelope =
115                     (AddressedEnvelope<ByteBuf, DomainSocketAddress>) msg;
116             data = envelope.content();
117             remoteAddress = envelope.recipient();
118         } else {
119             data = (ByteBuf) msg;
120             remoteAddress = null;
121         }
122 
123         final int dataLen = data.readableBytes();
124         final long writtenBytes;
125         if (data.hasMemoryAddress()) {
126             long memoryAddress = data.memoryAddress();
127             if (remoteAddress == null) {
128                 writtenBytes = socket.writeAddress(memoryAddress, data.readerIndex(), data.writerIndex());
129             } else {
130                 writtenBytes = socket.sendToAddressDomainSocket(memoryAddress, data.readerIndex(), data.writerIndex(),
131                         remoteAddress.path().getBytes(CharsetUtil.UTF_8));
132             }
133         } else if (data.nioBufferCount() > 1) {
134             IovArray array = ((KQueueEventLoop) eventLoop()).cleanArray();
135             array.add(data, data.readerIndex(), data.readableBytes());
136             int cnt = array.count();
137             assert cnt != 0;
138 
139             if (remoteAddress == null) {
140                 writtenBytes = socket.writevAddresses(array.memoryAddress(0), cnt);
141             } else {
142                 writtenBytes = socket.sendToAddressesDomainSocket(array.memoryAddress(0), cnt,
143                         remoteAddress.path().getBytes(CharsetUtil.UTF_8));
144             }
145         } else {
146             ByteBuffer nioData = data.internalNioBuffer(data.readerIndex(), data.readableBytes());
147             if (remoteAddress == null) {
148                 writtenBytes = socket.write(nioData, nioData.position(), nioData.limit());
149             } else {
150                 writtenBytes = socket.sendToDomainSocket(nioData, nioData.position(), nioData.limit(),
151                         remoteAddress.path().getBytes(CharsetUtil.UTF_8));
152             }
153         }
154 
155         // A zero-length datagram is valid; sendto() returns 0 for it.
156         return writtenBytes > 0 || dataLen == 0;
157     }
158 
159     @Override
160     protected Object filterOutboundMessage(Object msg) {
161         if (msg instanceof DomainDatagramPacket) {
162             DomainDatagramPacket packet = (DomainDatagramPacket) msg;
163             ByteBuf content = packet.content();
164             return UnixChannelUtil.isBufferCopyNeededForWrite(content) ?
165                     new DomainDatagramPacket(newDirectBuffer(packet, content), packet.recipient()) : msg;
166         }
167 
168         if (msg instanceof ByteBuf) {
169             ByteBuf buf = (ByteBuf) msg;
170             return UnixChannelUtil.isBufferCopyNeededForWrite(buf) ? newDirectBuffer(buf) : buf;
171         }
172 
173         if (msg instanceof AddressedEnvelope) {
174             @SuppressWarnings("unchecked")
175             AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg;
176             if (e.content() instanceof ByteBuf &&
177                     (e.recipient() == null || e.recipient() instanceof DomainSocketAddress)) {
178 
179                 ByteBuf content = (ByteBuf) e.content();
180                 return UnixChannelUtil.isBufferCopyNeededForWrite(content) ?
181                         new DefaultAddressedEnvelope<ByteBuf, DomainSocketAddress>(
182                                 newDirectBuffer(e, content), (DomainSocketAddress) e.recipient()) : e;
183             }
184         }
185 
186         throw new UnsupportedOperationException(
187                 "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
188     }
189 
190     @Override
191     public boolean isActive() {
192         return socket.isOpen() && (config.getActiveOnOpen() && isRegistered() || active);
193     }
194 
195     @Override
196     public boolean isConnected() {
197         return connected;
198     }
199 
200     @Override
201     public DomainSocketAddress localAddress() {
202         return (DomainSocketAddress) super.localAddress();
203     }
204 
205     @Override
206     protected DomainSocketAddress localAddress0() {
207         return local;
208     }
209 
210     @Override
211     protected AbstractKQueueUnsafe newUnsafe() {
212         return new KQueueDomainDatagramChannelUnsafe();
213     }
214 
215     /**
216      * Returns the unix credentials (uid, gid, pid) of the peer
217      * <a href=https://man7.org/linux/man-pages/man7/socket.7.html>SO_PEERCRED</a>
218      */
219     public PeerCredentials peerCredentials() throws IOException {
220         return socket.getPeerCredentials();
221     }
222 
223     @Override
224     public DomainSocketAddress remoteAddress() {
225         return (DomainSocketAddress) super.remoteAddress();
226     }
227 
228     @Override
229     protected DomainSocketAddress remoteAddress0() {
230         return remote;
231     }
232 
233     final class KQueueDomainDatagramChannelUnsafe extends AbstractKQueueUnsafe {
234 
235         @Override
236         void readReady(KQueueRecvByteAllocatorHandle allocHandle) {
237             assert eventLoop().inEventLoop();
238             final DomainDatagramChannelConfig config = config();
239             if (shouldBreakReadReady(config)) {
240                 clearReadFilter0();
241                 return;
242             }
243             final ChannelPipeline pipeline = pipeline();
244             final ByteBufAllocator allocator = config.getAllocator();
245             allocHandle.reset(config);
246 
247             Throwable exception = null;
248             try {
249                 ByteBuf byteBuf = null;
250                 try {
251                     boolean connected = isConnected();
252                     do {
253                         byteBuf = allocHandle.allocate(allocator);
254                         allocHandle.attemptedBytesRead(byteBuf.writableBytes());
255 
256                         final DomainDatagramPacket packet;
257                         if (connected) {
258                             allocHandle.lastBytesRead(doReadBytes(byteBuf));
259                             if (allocHandle.lastBytesRead() <= 0) {
260                                 // nothing was read, release the buffer.
261                                 byteBuf.release();
262                                 break;
263                             }
264                             packet = new DomainDatagramPacket(byteBuf, (DomainSocketAddress) localAddress(),
265                                     (DomainSocketAddress) remoteAddress());
266                         } else {
267                             final DomainDatagramSocketAddress remoteAddress;
268                             if (byteBuf.hasMemoryAddress()) {
269                                 // has a memory address so use optimized call
270                                 remoteAddress = socket.recvFromAddressDomainSocket(byteBuf.memoryAddress(),
271                                         byteBuf.writerIndex(), byteBuf.capacity());
272                             } else {
273                                 ByteBuffer nioData = byteBuf.internalNioBuffer(
274                                         byteBuf.writerIndex(), byteBuf.writableBytes());
275                                 remoteAddress =
276                                         socket.recvFromDomainSocket(nioData, nioData.position(), nioData.limit());
277                             }
278 
279                             if (remoteAddress == null) {
280                                 allocHandle.lastBytesRead(-1);
281                                 byteBuf.release();
282                                 break;
283                             }
284                             DomainSocketAddress localAddress = remoteAddress.localAddress();
285                             if (localAddress == null) {
286                                 localAddress = (DomainSocketAddress) localAddress();
287                             }
288                             final int receivedAmount = remoteAddress.receivedAmount();
289                             // Avoid signalling end-of-data for zero-sized datagrams, otherwise continueReading(...)
290                             // may stop the loop and leave the remaining datagrams unread.
291                             allocHandle.lastBytesRead(Math.max(1, receivedAmount));
292                             byteBuf.writerIndex(byteBuf.writerIndex() + receivedAmount);
293 
294                             packet = new DomainDatagramPacket(byteBuf, localAddress, remoteAddress);
295                         }
296 
297                         allocHandle.incMessagesRead(1);
298 
299                         readPending = false;
300                         pipeline.fireChannelRead(packet);
301 
302                         byteBuf = null;
303 
304                         // We use the TRUE_SUPPLIER as it is also ok to read less then what we did try to read (as long
305                         // as we read anything).
306                     } while (allocHandle.continueReading(UncheckedBooleanSupplier.TRUE_SUPPLIER));
307                 } catch (Throwable t) {
308                     if (byteBuf != null) {
309                         byteBuf.release();
310                     }
311                     exception = t;
312                 }
313 
314                 allocHandle.readComplete();
315                 pipeline.fireChannelReadComplete();
316 
317                 if (exception != null) {
318                     pipeline.fireExceptionCaught(exception);
319                 }
320             } finally {
321                 if (shouldStopReading(config)) {
322                     clearReadFilter0();
323                 }
324             }
325         }
326     }
327 }