View Javadoc
1   /*
2    * Copyright 2012 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.socket.nio;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.AddressedEnvelope;
20  import io.netty.channel.Channel;
21  import io.netty.channel.ChannelException;
22  import io.netty.channel.ChannelFuture;
23  import io.netty.channel.ChannelMetadata;
24  import io.netty.channel.ChannelOption;
25  import io.netty.channel.ChannelOutboundBuffer;
26  import io.netty.channel.ChannelPromise;
27  import io.netty.channel.DefaultAddressedEnvelope;
28  import io.netty.channel.RecvByteBufAllocator;
29  import io.netty.channel.nio.AbstractNioMessageChannel;
30  import io.netty.channel.socket.DatagramChannelConfig;
31  import io.netty.channel.socket.DatagramPacket;
32  import io.netty.channel.socket.InternetProtocolFamily;
33  import io.netty.channel.socket.SocketProtocolFamily;
34  import io.netty.util.UncheckedBooleanSupplier;
35  import io.netty.util.internal.ObjectUtil;
36  import io.netty.util.internal.PlatformDependent;
37  import io.netty.util.internal.SocketUtils;
38  import io.netty.util.internal.StringUtil;
39  
40  import java.io.IOException;
41  import java.net.InetAddress;
42  import java.net.InetSocketAddress;
43  import java.net.NetworkInterface;
44  import java.net.SocketAddress;
45  import java.net.SocketException;
46  import java.nio.ByteBuffer;
47  import java.nio.channels.DatagramChannel;
48  import java.nio.channels.MembershipKey;
49  import java.nio.channels.SelectionKey;
50  import java.nio.channels.UnresolvedAddressException;
51  import java.nio.channels.spi.SelectorProvider;
52  import java.util.ArrayList;
53  import java.util.HashMap;
54  import java.util.Iterator;
55  import java.util.List;
56  import java.util.Map;
57  
58  /**
59   * An NIO datagram {@link Channel} that sends and receives an
60   * {@link AddressedEnvelope AddressedEnvelope<ByteBuf, SocketAddress>}.
61   *
62   * @see AddressedEnvelope
63   * @see DatagramPacket
64   */
65  public final class NioDatagramChannel
66          extends AbstractNioMessageChannel implements io.netty.channel.socket.DatagramChannel {
67  
68      private static final ChannelMetadata METADATA = new ChannelMetadata(true, 16);
69      private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();
70      private static final String EXPECTED_TYPES =
71              " (expected: " + StringUtil.simpleClassName(DatagramPacket.class) + ", " +
72              StringUtil.simpleClassName(AddressedEnvelope.class) + '<' +
73              StringUtil.simpleClassName(ByteBuf.class) + ", " +
74              StringUtil.simpleClassName(SocketAddress.class) + ">, " +
75              StringUtil.simpleClassName(ByteBuf.class) + ')';
76  
77      private final DatagramChannelConfig config;
78  
79      private Map<InetAddress, List<MembershipKey>> memberships;
80  
81      /**
82       *  Use the {@link SelectorProvider} to open {@link DatagramChannel} and so remove condition in
83       *  {@link SelectorProvider#provider()} which is called by each DatagramChannel.open() otherwise.
84       * <p>
85       *  See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
86       */
87      private static DatagramChannel newSocket(SelectorProvider provider) {
88          try {
89              return provider.openDatagramChannel();
90          } catch (IOException e) {
91              throw new ChannelException("Failed to open a socket.", e);
92          }
93      }
94  
95      private static DatagramChannel newSocket(SelectorProvider provider, SocketProtocolFamily ipFamily) {
96          if (ipFamily == null) {
97              return newSocket(provider);
98          }
99  
100         try {
101             return provider.openDatagramChannel(ipFamily.toJdkFamily());
102         } catch (IOException e) {
103             throw new ChannelException("Failed to open a socket.", e);
104         }
105     }
106 
107     /**
108      * Create a new instance which will use the Operation Systems default {@link SocketProtocolFamily}.
109      */
110     public NioDatagramChannel() {
111         this(newSocket(DEFAULT_SELECTOR_PROVIDER));
112     }
113 
114     /**
115      * Create a new instance using the given {@link SelectorProvider}
116      * which will use the Operation Systems default {@link SocketProtocolFamily}.
117      */
118     public NioDatagramChannel(SelectorProvider provider) {
119         this(newSocket(provider));
120     }
121 
122     /**
123      * Create a new instance using the given {@link InternetProtocolFamily}. If {@code null} is used it will depend
124      * on the Operation Systems default which will be chosen.
125      *
126      * @deprecated use {@link NioDatagramChannel#NioDatagramChannel(SocketProtocolFamily)}
127      */
128     @Deprecated
129     public NioDatagramChannel(InternetProtocolFamily ipFamily) {
130         this(ipFamily == null ? null : ipFamily.toSocketProtocolFamily());
131     }
132 
133     /**
134      * Create a new instance using the given {@link SocketProtocolFamily}. If {@code null} is used it will depend
135      * on the Operation Systems default which will be chosen.
136      */
137     public NioDatagramChannel(SocketProtocolFamily protocolFamily) {
138         this(newSocket(DEFAULT_SELECTOR_PROVIDER, protocolFamily));
139     }
140 
141     /**
142      * Create a new instance using the given {@link SelectorProvider} and {@link InternetProtocolFamily}.
143      * If {@link InternetProtocolFamily} is {@code null} it will depend on the Operation Systems default
144      * which will be chosen.
145      *
146      * @deprecated use {@link NioDatagramChannel#NioDatagramChannel(SelectorProvider, SocketProtocolFamily)}
147      */
148     @Deprecated
149     public NioDatagramChannel(SelectorProvider provider, InternetProtocolFamily ipFamily) {
150         this(provider, ipFamily == null ? null : ipFamily.toSocketProtocolFamily());
151     }
152 
153     /**
154      * Create a new instance using the given {@link SelectorProvider} and {@link SocketProtocolFamily}.
155      * If {@link SocketProtocolFamily} is {@code null} it will depend on the Operation Systems default
156      * which will be chosen.
157      */
158     public NioDatagramChannel(SelectorProvider provider, SocketProtocolFamily protocolFamily) {
159         this(newSocket(provider, protocolFamily));
160     }
161 
162     /**
163      * Create a new instance from the given {@link DatagramChannel}.
164      */
165     public NioDatagramChannel(DatagramChannel socket) {
166         super(null, socket, SelectionKey.OP_READ);
167         config = new NioDatagramChannelConfig(this, socket);
168     }
169 
170     @Override
171     public ChannelMetadata metadata() {
172         return METADATA;
173     }
174 
175     @Override
176     public DatagramChannelConfig config() {
177         return config;
178     }
179 
180     @Override
181     @SuppressWarnings("deprecation")
182     public boolean isActive() {
183         DatagramChannel ch = javaChannel();
184         return ch.isOpen() && (
185                 config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered()
186                 || ch.socket().isBound());
187     }
188 
189     @Override
190     public boolean isConnected() {
191         return javaChannel().isConnected();
192     }
193 
194     @Override
195     protected DatagramChannel javaChannel() {
196         return (DatagramChannel) super.javaChannel();
197     }
198 
199     @Override
200     protected SocketAddress localAddress0() {
201         return javaChannel().socket().getLocalSocketAddress();
202     }
203 
204     @Override
205     protected SocketAddress remoteAddress0() {
206         return javaChannel().socket().getRemoteSocketAddress();
207     }
208 
209     @Override
210     protected void doBind(SocketAddress localAddress) throws Exception {
211         doBind0(localAddress);
212     }
213 
214     private void doBind0(SocketAddress localAddress) throws Exception {
215         SocketUtils.bind(javaChannel(), localAddress);
216     }
217 
218     @Override
219     protected boolean doConnect(SocketAddress remoteAddress,
220             SocketAddress localAddress) throws Exception {
221         if (localAddress != null) {
222             doBind0(localAddress);
223         }
224 
225         boolean success = false;
226         try {
227             javaChannel().connect(remoteAddress);
228             success = true;
229             return true;
230         } finally {
231             if (!success) {
232                 doClose();
233             }
234         }
235     }
236 
237     @Override
238     protected void doFinishConnect() throws Exception {
239         throw new UnsupportedOperationException("finishConnect is not supported for " + getClass().getName());
240     }
241 
242     @Override
243     protected void doDisconnect() throws Exception {
244         javaChannel().disconnect();
245     }
246 
247     @Override
248     protected void doClose() throws Exception {
249         javaChannel().close();
250     }
251 
252     @Override
253     protected int doReadMessages(List<Object> buf) throws Exception {
254         DatagramChannel ch = javaChannel();
255         DatagramChannelConfig config = config();
256         RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
257 
258         ByteBuf data = allocHandle.allocate(config.getAllocator());
259         allocHandle.attemptedBytesRead(data.writableBytes());
260         boolean free = true;
261         try {
262             ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes());
263             int pos = nioData.position();
264             InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData);
265             if (remoteAddress == null) {
266                 return 0;
267             }
268 
269             allocHandle.lastBytesRead(nioData.position() - pos);
270             buf.add(new DatagramPacket(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()),
271                     localAddress(), remoteAddress));
272             free = false;
273             return 1;
274         } catch (Throwable cause) {
275             PlatformDependent.throwException(cause);
276             return -1;
277         }  finally {
278             if (free) {
279                 data.release();
280             }
281         }
282     }
283 
284     @Override
285     protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
286         final SocketAddress remoteAddress;
287         final ByteBuf data;
288         if (msg instanceof AddressedEnvelope) {
289             @SuppressWarnings("unchecked")
290             AddressedEnvelope<ByteBuf, SocketAddress> envelope = (AddressedEnvelope<ByteBuf, SocketAddress>) msg;
291             remoteAddress = envelope.recipient();
292             data = envelope.content();
293         } else {
294             data = (ByteBuf) msg;
295             remoteAddress = null;
296         }
297 
298         final int dataLen = data.readableBytes();
299         final ByteBuffer nioData = data.nioBufferCount() == 1 ? data.internalNioBuffer(data.readerIndex(), dataLen)
300                                                               : data.nioBuffer(data.readerIndex(), dataLen);
301         final int writtenBytes;
302         if (remoteAddress != null) {
303             writtenBytes = javaChannel().send(nioData, remoteAddress);
304         } else {
305             writtenBytes = javaChannel().write(nioData);
306         }
307         // A zero-length datagram is valid; send() and write() return 0 for it.
308         return writtenBytes > 0 || dataLen == 0;
309     }
310 
311     private static void checkUnresolved(AddressedEnvelope<?, ?> envelope) {
312         if (envelope.recipient() instanceof InetSocketAddress
313                 && (((InetSocketAddress) envelope.recipient()).isUnresolved())) {
314             throw new UnresolvedAddressException();
315         }
316     }
317 
318     @Override
319     protected Object filterOutboundMessage(Object msg) {
320         if (msg instanceof DatagramPacket) {
321             DatagramPacket p = (DatagramPacket) msg;
322             checkUnresolved(p);
323             ByteBuf content = p.content();
324             if (isSingleDirectBuffer(content)) {
325                 return p;
326             }
327             return new DatagramPacket(newDirectBuffer(p, content), p.recipient());
328         }
329 
330         if (msg instanceof ByteBuf) {
331             ByteBuf buf = (ByteBuf) msg;
332             if (isSingleDirectBuffer(buf)) {
333                 return buf;
334             }
335             return newDirectBuffer(buf);
336         }
337 
338         if (msg instanceof AddressedEnvelope) {
339             @SuppressWarnings("unchecked")
340             AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg;
341             checkUnresolved(e);
342             if (e.content() instanceof ByteBuf) {
343                 ByteBuf content = (ByteBuf) e.content();
344                 if (isSingleDirectBuffer(content)) {
345                     return e;
346                 }
347                 return new DefaultAddressedEnvelope<ByteBuf, SocketAddress>(newDirectBuffer(e, content), e.recipient());
348             }
349         }
350 
351         throw new UnsupportedOperationException(
352                 "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
353     }
354 
355     /**
356      * Checks if the specified buffer is a direct buffer and is composed of a single NIO buffer.
357      * (We check this because otherwise we need to make it a non-composite buffer.)
358      */
359     private static boolean isSingleDirectBuffer(ByteBuf buf) {
360         return buf.isDirect() && buf.nioBufferCount() == 1;
361     }
362 
363     @Override
364     protected boolean continueOnWriteError() {
365         // Continue on write error as a DatagramChannel can write to multiple remote peers
366         //
367         // See https://github.com/netty/netty/issues/2665
368         return true;
369     }
370 
371     @Override
372     public InetSocketAddress localAddress() {
373         return (InetSocketAddress) super.localAddress();
374     }
375 
376     @Override
377     public InetSocketAddress remoteAddress() {
378         return (InetSocketAddress) super.remoteAddress();
379     }
380 
381     @Override
382     public ChannelFuture joinGroup(InetAddress multicastAddress) {
383         return joinGroup(multicastAddress, newPromise());
384     }
385 
386     @Override
387     public ChannelFuture joinGroup(InetAddress multicastAddress, ChannelPromise promise) {
388         final NetworkInterface iface;
389         try {
390             iface = defaultMulticastInterface();
391         } catch (SocketException e) {
392             return promise.setFailure(e);
393         }
394         return joinGroup(multicastAddress, iface, null, promise);
395     }
396 
397     /**
398      * Returns the interface to use when none was given: the one set via
399      * {@link io.netty.channel.ChannelOption#IP_MULTICAST_IF} or, if unset, the interface of the local address.
400      */
401     private NetworkInterface defaultMulticastInterface() throws SocketException {
402         NetworkInterface iface = config.getNetworkInterface();
403         if (iface == null) {
404             iface = NetworkInterface.getByInetAddress(localAddress().getAddress());
405         }
406         return iface;
407     }
408 
409     @Override
410     public ChannelFuture joinGroup(
411             InetSocketAddress multicastAddress, NetworkInterface networkInterface) {
412         return joinGroup(multicastAddress, networkInterface, newPromise());
413     }
414 
415     @Override
416     public ChannelFuture joinGroup(
417             InetSocketAddress multicastAddress, NetworkInterface networkInterface,
418             ChannelPromise promise) {
419         return joinGroup(multicastAddress.getAddress(), networkInterface, null, promise);
420     }
421 
422     @Override
423     public ChannelFuture joinGroup(
424             InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source) {
425         return joinGroup(multicastAddress, networkInterface, source, newPromise());
426     }
427 
428     @Override
429     public ChannelFuture joinGroup(
430             InetAddress multicastAddress, NetworkInterface networkInterface,
431             InetAddress source, ChannelPromise promise) {
432 
433         ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
434         ObjectUtil.checkNotNull(networkInterface, "networkInterface");
435 
436         try {
437             MembershipKey key;
438             if (source == null) {
439                 key = javaChannel().join(multicastAddress, networkInterface);
440             } else {
441                 key = javaChannel().join(multicastAddress, networkInterface, source);
442             }
443 
444             synchronized (this) {
445                 List<MembershipKey> keys = null;
446                 if (memberships == null) {
447                     memberships = new HashMap<InetAddress, List<MembershipKey>>();
448                 } else {
449                     keys = memberships.get(multicastAddress);
450                 }
451                 if (keys == null) {
452                     keys = new ArrayList<MembershipKey>();
453                     memberships.put(multicastAddress, keys);
454                 }
455                 keys.add(key);
456             }
457 
458             promise.setSuccess();
459         } catch (Throwable e) {
460             promise.setFailure(e);
461         }
462 
463         return promise;
464     }
465 
466     @Override
467     public ChannelFuture leaveGroup(InetAddress multicastAddress) {
468         return leaveGroup(multicastAddress, newPromise());
469     }
470 
471     @Override
472     public ChannelFuture leaveGroup(InetAddress multicastAddress, ChannelPromise promise) {
473         try {
474             return leaveGroup(multicastAddress, defaultMulticastInterface(), null, promise);
475         } catch (SocketException e) {
476             promise.setFailure(e);
477         }
478         return promise;
479     }
480 
481     @Override
482     public ChannelFuture leaveGroup(
483             InetSocketAddress multicastAddress, NetworkInterface networkInterface) {
484         return leaveGroup(multicastAddress, networkInterface, newPromise());
485     }
486 
487     @Override
488     public ChannelFuture leaveGroup(
489             InetSocketAddress multicastAddress,
490             NetworkInterface networkInterface, ChannelPromise promise) {
491         return leaveGroup(multicastAddress.getAddress(), networkInterface, null, promise);
492     }
493 
494     @Override
495     public ChannelFuture leaveGroup(
496             InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source) {
497         return leaveGroup(multicastAddress, networkInterface, source, newPromise());
498     }
499 
500     @Override
501     public ChannelFuture leaveGroup(
502             InetAddress multicastAddress, NetworkInterface networkInterface, InetAddress source,
503             ChannelPromise promise) {
504 
505         ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
506         ObjectUtil.checkNotNull(networkInterface, "networkInterface");
507 
508         synchronized (this) {
509             if (memberships != null) {
510                 List<MembershipKey> keys = memberships.get(multicastAddress);
511                 if (keys != null) {
512                     Iterator<MembershipKey> keyIt = keys.iterator();
513 
514                     while (keyIt.hasNext()) {
515                         MembershipKey key = keyIt.next();
516                         if (networkInterface.equals(key.networkInterface())) {
517                            if (source == null && key.sourceAddress() == null ||
518                                source != null && source.equals(key.sourceAddress())) {
519                                key.drop();
520                                keyIt.remove();
521                            }
522                         }
523                     }
524                     if (keys.isEmpty()) {
525                         memberships.remove(multicastAddress);
526                     }
527                 }
528             }
529         }
530 
531         promise.setSuccess();
532         return promise;
533     }
534 
535     /**
536      * Block the given sourceToBlock address for the given multicastAddress on the given networkInterface
537      */
538     @Override
539     public ChannelFuture block(
540             InetAddress multicastAddress, NetworkInterface networkInterface,
541             InetAddress sourceToBlock) {
542         return block(multicastAddress, networkInterface, sourceToBlock, newPromise());
543     }
544 
545     /**
546      * Block the given sourceToBlock address for the given multicastAddress on the given networkInterface
547      */
548     @Override
549     public ChannelFuture block(
550             InetAddress multicastAddress, NetworkInterface networkInterface,
551             InetAddress sourceToBlock, ChannelPromise promise) {
552 
553         ObjectUtil.checkNotNull(multicastAddress, "multicastAddress");
554         ObjectUtil.checkNotNull(sourceToBlock, "sourceToBlock");
555         ObjectUtil.checkNotNull(networkInterface, "networkInterface");
556 
557         synchronized (this) {
558             if (memberships != null) {
559                 List<MembershipKey> keys = memberships.get(multicastAddress);
560                 for (MembershipKey key: keys) {
561                     if (networkInterface.equals(key.networkInterface())) {
562                         try {
563                             key.block(sourceToBlock);
564                         } catch (Throwable e) {
565                             return promise.setFailure(e);
566                         }
567                     }
568                 }
569             }
570         }
571         promise.setSuccess();
572         return promise;
573     }
574 
575     /**
576      * Block the given sourceToBlock address for the given multicastAddress
577      *
578      */
579     @Override
580     public ChannelFuture block(InetAddress multicastAddress, InetAddress sourceToBlock) {
581         return block(multicastAddress, sourceToBlock, newPromise());
582     }
583 
584     /**
585      * Block the given sourceToBlock address for the given multicastAddress
586      *
587      */
588     @Override
589     public ChannelFuture block(
590             InetAddress multicastAddress, InetAddress sourceToBlock, ChannelPromise promise) {
591         final NetworkInterface iface;
592         try {
593             iface = defaultMulticastInterface();
594         } catch (SocketException e) {
595             return promise.setFailure(e);
596         }
597         return block(multicastAddress, iface, sourceToBlock, promise);
598     }
599 
600     @Override
601     @Deprecated
602     protected void setReadPending(boolean readPending) {
603         super.setReadPending(readPending);
604     }
605 
606     void clearReadPending0() {
607         clearReadPending();
608     }
609 
610     @Override
611     protected boolean closeOnReadError(Throwable cause) {
612         // We do not want to close on SocketException when using DatagramChannel as we usually can continue receiving.
613         // See https://github.com/netty/netty/issues/5893
614         if (cause instanceof SocketException) {
615             return false;
616         }
617         return super.closeOnReadError(cause);
618     }
619 
620     @Override
621     protected boolean continueReading(RecvByteBufAllocator.Handle allocHandle) {
622         if (allocHandle instanceof RecvByteBufAllocator.ExtendedHandle) {
623             // We use the TRUE_SUPPLIER as it is also ok to read less then what we did try to read (as long
624             // as we read anything).
625             return ((RecvByteBufAllocator.ExtendedHandle) allocHandle)
626                     .continueReading(UncheckedBooleanSupplier.TRUE_SUPPLIER);
627         }
628         return allocHandle.continueReading();
629     }
630 }