1 /*
   2  * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /* @test
  25  * @bug 4527345 7026376 6633549
  26  * @summary Unit test for DatagramChannel's multicast support
  27  * @library /test/lib
  28  * @build MulticastSendReceiveTests
  29  * @run main MulticastSendReceiveTests
  30  * @run main/othervm -Djava.net.preferIPv4Stack=true MulticastSendReceiveTests
  31  * @key randomness
  32  */
  33 
  34 import java.nio.ByteBuffer;
  35 import java.nio.channels.*;
  36 import java.net.*;
  37 import static java.net.StandardProtocolFamily.*;
  38 import java.util.*;
  39 import java.io.IOException;
  40 import java.util.stream.Collectors;
  41 
  42 import jdk.test.lib.NetworkConfiguration;
  43 
  44 public class MulticastSendReceiveTests {
  45 
  46     static final Random rand = new Random();
  47 
  48     static final ProtocolFamily UNSPEC = new ProtocolFamily() {
  49         public String name() {
  50             return "UNSPEC";
  51         }
  52     };
  53 
  54     /**
  55      * Send datagram from given local address to given multicast
  56      * group.
  57      */
  58     static int sendDatagram(InetAddress local,
  59                             NetworkInterface nif,
  60                             InetAddress group,
  61                             int port)
  62         throws IOException
  63     {
  64         ProtocolFamily family = (group instanceof Inet6Address) ?
  65             StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
  66         DatagramChannel dc = DatagramChannel.open(family)
  67             .bind(new InetSocketAddress(local, 0))
  68             .setOption(StandardSocketOptions.IP_MULTICAST_IF, nif);
  69         int id = rand.nextInt();
  70         byte[] msg = Integer.toString(id).getBytes("UTF-8");
  71         ByteBuffer buf = ByteBuffer.wrap(msg);
  72         System.out.format("Send message from %s -> group %s (id=0x%x)\n",
  73             local.getHostAddress(), group.getHostAddress(), id);
  74         dc.send(buf, new InetSocketAddress(group, port));
  75         dc.close();
  76         return id;
  77     }
  78 
  79     /**
  80      * Wait (with timeout) for datagram.
  81      *
  82      * @param   expectedSender - expected sender address, or
  83      *                           null if no datagram expected
  84      * @param   id - expected id of datagram
  85      */
  86     static void receiveDatagram(DatagramChannel dc,
  87                                 InetAddress expectedSender,
  88                                 int id)
  89         throws IOException
  90     {
  91         Selector sel = Selector.open();
  92         dc.configureBlocking(false);
  93         dc.register(sel, SelectionKey.OP_READ);
  94         ByteBuffer buf = ByteBuffer.allocateDirect(100);
  95 
  96         try {
  97             for (;;) {
  98                 System.out.println("Waiting to receive message");
  99                 sel.select(5*1000);
 100                 SocketAddress sa = dc.receive(buf);
 101 
 102                 // no datagram received
 103                 if (sa == null) {
 104                     if (expectedSender != null) {
 105                         throw new RuntimeException("Expected message not received");
 106                     }
 107                     System.out.println("No message received (correct)");
 108                     return;
 109                 }
 110 
 111                 // datagram received
 112 
 113                 InetAddress sender = ((InetSocketAddress)sa).getAddress();
 114                 buf.flip();
 115                 byte[] bytes = new byte[buf.remaining()];
 116                 buf.get(bytes);
 117                 String s = new String(bytes, "UTF-8");
 118                 int receivedId = -1;
 119                 try {
 120                     receivedId = Integer.parseInt(s);
 121                     System.out.format("Received message from %s (id=0x%x)\n",
 122                             sender, receivedId);
 123                 } catch (NumberFormatException x) {
 124                     System.out.format("Received message from %s (msg=%s)\n", sender, s);
 125                 }
 126 
 127                 if (expectedSender == null) {
 128                     if (receivedId == id)
 129                         throw new RuntimeException("Message not expected");
 130                     System.out.println("Message ignored (has wrong id)");
 131                 } else {
 132                     if (sender.equals(expectedSender)) {
 133                         System.out.println("Message expected");
 134                         return;
 135                     }
 136                     System.out.println("Message ignored (wrong sender)");
 137                 }
 138 
 139                 sel.selectedKeys().clear();
 140                 buf.rewind();
 141             }
 142         } finally {
 143             sel.close();
 144         }
 145     }
 146 
 147 
 148     /**
 149      * Exercise multicast send/receive on given group/interface
 150      */
 151     static void test(ProtocolFamily family,
 152                      NetworkInterface nif,
 153                      InetAddress group,
 154                      InetAddress source)
 155         throws IOException
 156     {
 157         System.out.format("\nTest DatagramChannel to %s socket\n", family.name());
 158         try (DatagramChannel dc = (family == UNSPEC) ?
 159                 DatagramChannel.open() : DatagramChannel.open(family)) {
 160             dc.setOption(StandardSocketOptions.SO_REUSEADDR, true)
 161               .bind(new InetSocketAddress(0));
 162 
 163             // join group
 164             System.out.format("join %s @ %s\n", group.getHostAddress(),
 165                 nif.getName());
 166             MembershipKey key;
 167             try {
 168                 key = dc.join(group, nif);
 169             } catch (IllegalArgumentException iae) {
 170                 if (family == UNSPEC) {
 171                     System.out.println("Not supported");
 172                     return;
 173                 }
 174                 throw iae;
 175             }
 176 
 177             // send message to group
 178             int port = ((InetSocketAddress)dc.getLocalAddress()).getPort();
 179             int id = sendDatagram(source, nif, group, port);
 180 
 181             // receive message and check id matches
 182             receiveDatagram(dc, source, id);
 183 
 184             // exclude-mode filtering
 185 
 186             try {
 187                 System.out.format("block %s\n", source.getHostAddress());
 188 
 189                 // may throw UOE
 190                 key.block(source);
 191                 id = sendDatagram(source, nif, group, port);
 192                 receiveDatagram(dc, null, id);
 193 
 194                 // unblock source, send message, message should be received
 195                 System.out.format("unblock %s\n", source.getHostAddress());
 196                 key.unblock(source);
 197                 id = sendDatagram(source, nif, group, port);
 198                 receiveDatagram(dc, source, id);
 199             } catch (UnsupportedOperationException x) {
 200                 String os = System.getProperty("os.name");
 201                 // Exclude-mode filtering supported on these platforms so UOE should never be thrown
 202                 if (os.equals("SunOS") || os.equals("Linux"))
 203                     throw x;
 204                 System.out.println("Exclude-mode filtering not supported!");
 205             }
 206 
 207             key.drop();
 208 
 209             // include-mode filtering
 210 
 211             InetAddress bogus = (group instanceof Inet6Address) ?
 212                 InetAddress.getByName("fe80::1234") :
 213                 InetAddress.getByName("1.2.3.4");
 214             System.out.format("join %s @ %s only-source %s\n", group.getHostAddress(),
 215                 nif.getName(), bogus.getHostAddress());
 216             try {
 217                 // may throw UOE
 218                 key = dc.join(group, nif, bogus);
 219 
 220                 id = sendDatagram(source, nif, group, port);
 221                 receiveDatagram(dc, null, id);
 222 
 223                 System.out.format("join %s @ %s only-source %s\n", group.getHostAddress(),
 224                     nif.getName(), source.getHostAddress());
 225                 key = dc.join(group, nif, source);
 226 
 227                 id = sendDatagram(source, nif, group, port);
 228                 receiveDatagram(dc, source, id);
 229             } catch (UnsupportedOperationException x) {
 230                 String os = System.getProperty("os.name");
 231                 // Include-mode filtering supported on these platforms so UOE should never be thrown
 232                 if (os.equals("SunOS") || os.equals("Linux"))
 233                     throw x;
 234                 System.out.println("Include-mode filtering not supported!");
 235             }
 236         }
 237     }
 238 
 239     public static void main(String[] args) throws IOException {
 240         NetworkConfiguration config = NetworkConfiguration.probe();
 241 
 242         // multicast groups used for the test
 243         InetAddress ip4Group = InetAddress.getByName("225.4.5.6");
 244         InetAddress ip6Group = InetAddress.getByName("ff02::a");
 245         for (NetworkInterface nif: config.ip4MulticastInterfaces()
 246                                          .collect(Collectors.toList())) {
 247             InetAddress source = config.ip4Addresses(nif).iterator().next();
 248             test(INET,   nif, ip4Group, source);
 249             test(UNSPEC, nif, ip4Group, source);
 250         }
 251 
 252         for (NetworkInterface nif: config.ip6MulticastInterfaces()
 253                                          .collect(Collectors.toList())) {
 254             InetAddress source = config.ip6Addresses(nif).iterator().next();
 255             test(INET6,  nif, ip6Group, source);
 256             test(UNSPEC, nif, ip6Group, source);
 257         }
 258     }
 259 }