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  * @build MulticastSendReceiveTests NetworkConfiguration
  28  * @run main MulticastSendReceiveTests
  29  * @run main/othervm -Djava.net.preferIPv4Stack=true MulticastSendReceiveTests
  30  */
  31 
  32 import java.nio.ByteBuffer;
  33 import java.nio.channels.*;
  34 import java.net.*;
  35 import static java.net.StandardProtocolFamily.*;
  36 import java.util.*;
  37 import java.io.IOException;
  38 
  39 public class MulticastSendReceiveTests {
  40 
  41     static final Random rand = new Random();
  42 
  43     static final ProtocolFamily UNSPEC = new ProtocolFamily() {
  44         public String name() {
  45             return "UNSPEC";
  46         }
  47     };
  48 
  49     /**
  50      * Send datagram from given local address to given multicast
  51      * group.
  52      */
  53     static int sendDatagram(InetAddress local,
  54                             NetworkInterface nif,
  55                             InetAddress group,
  56                             int port)
  57         throws IOException
  58     {
  59         ProtocolFamily family = (group instanceof Inet6Address) ?
  60             StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
  61         DatagramChannel dc = DatagramChannel.open(family)
  62             .bind(new InetSocketAddress(local, 0))
  63             .setOption(StandardSocketOptions.IP_MULTICAST_IF, nif);
  64         int id = rand.nextInt();
  65         byte[] msg = Integer.toString(id).getBytes("UTF-8");
  66         ByteBuffer buf = ByteBuffer.wrap(msg);
  67         System.out.format("Send message from %s -> group %s (id=0x%x)\n",
  68             local.getHostAddress(), group.getHostAddress(), id);
  69         dc.send(buf, new InetSocketAddress(group, port));
  70         dc.close();
  71         return id;
  72     }
  73 
  74     /**
  75      * Wait (with timeout) for datagram.
  76      *
  77      * @param   expectedSender - expected sender address, or
  78      *                           null if no datagram expected
  79      * @param   id - expected id of datagram
  80      */
  81     static void receiveDatagram(DatagramChannel dc,
  82                                 InetAddress expectedSender,
  83                                 int id)
  84         throws IOException
  85     {
  86         Selector sel = Selector.open();
  87         dc.configureBlocking(false);
  88         dc.register(sel, SelectionKey.OP_READ);
  89         ByteBuffer buf = ByteBuffer.allocateDirect(100);
  90 
  91         try {
  92             for (;;) {
  93                 System.out.println("Waiting to receive message");
  94                 sel.select(5*1000);
  95                 SocketAddress sa = dc.receive(buf);
  96 
  97                 // no datagram received
  98                 if (sa == null) {
  99                     if (expectedSender != null) {
 100                         throw new RuntimeException("Expected message not received");
 101                     }
 102                     System.out.println("No message received (correct)");
 103                     return;
 104                 }
 105 
 106                 // datagram received
 107 
 108                 InetAddress sender = ((InetSocketAddress)sa).getAddress();
 109                 buf.flip();
 110                 byte[] bytes = new byte[buf.remaining()];
 111                 buf.get(bytes);
 112                 String s = new String(bytes, "UTF-8");
 113                 int receivedId = -1;
 114                 try {
 115                     receivedId = Integer.parseInt(s);
 116                     System.out.format("Received message from %s (id=0x%x)\n",
 117                             sender, receivedId);
 118                 } catch (NumberFormatException x) {
 119                     System.out.format("Received message from %s (msg=%s)\n", sender, s);
 120                 }
 121 
 122                 if (expectedSender == null) {
 123                     if (receivedId == id)
 124                         throw new RuntimeException("Message not expected");
 125                     System.out.println("Message ignored (has wrong id)");
 126                 } else {
 127                     if (sender.equals(expectedSender)) {
 128                         System.out.println("Message expected");
 129                         return;
 130                     }
 131                     System.out.println("Message ignored (wrong sender)");
 132                 }
 133 
 134                 sel.selectedKeys().clear();
 135                 buf.rewind();
 136             }
 137         } finally {
 138             sel.close();
 139         }
 140     }
 141 
 142 
 143     /**
 144      * Exercise multicast send/receive on given group/interface
 145      */
 146     static void test(ProtocolFamily family,
 147                      NetworkInterface nif,
 148                      InetAddress group,
 149                      InetAddress source)
 150         throws IOException
 151     {
 152         System.out.format("\nTest DatagramChannel to %s socket\n", family.name());
 153         try (DatagramChannel dc = (family == UNSPEC) ?
 154                 DatagramChannel.open() : DatagramChannel.open(family)) {
 155             dc.setOption(StandardSocketOptions.SO_REUSEADDR, true)
 156               .bind(new InetSocketAddress(0));
 157 
 158             // join group
 159             System.out.format("join %s @ %s\n", group.getHostAddress(),
 160                 nif.getName());
 161             MembershipKey key;
 162             try {
 163                 key = dc.join(group, nif);
 164             } catch (IllegalArgumentException iae) {
 165                 if (family == UNSPEC) {
 166                     System.out.println("Not supported");
 167                     return;
 168                 }
 169                 throw iae;
 170             }
 171 
 172             // send message to group
 173             int port = ((InetSocketAddress)dc.getLocalAddress()).getPort();
 174             int id = sendDatagram(source, nif, group, port);
 175 
 176             // receive message and check id matches
 177             receiveDatagram(dc, source, id);
 178 
 179             // exclude-mode filtering
 180 
 181             try {
 182                 System.out.format("block %s\n", source.getHostAddress());
 183 
 184                 // may throw UOE
 185                 key.block(source);
 186                 id = sendDatagram(source, nif, group, port);
 187                 receiveDatagram(dc, null, id);
 188 
 189                 // unblock source, send message, message should be received
 190                 System.out.format("unblock %s\n", source.getHostAddress());
 191                 key.unblock(source);
 192                 id = sendDatagram(source, nif, group, port);
 193                 receiveDatagram(dc, source, id);
 194             } catch (UnsupportedOperationException x) {
 195                 String os = System.getProperty("os.name");
 196                 // Exclude-mode filtering supported on these platforms so UOE should never be thrown
 197                 if (os.equals("SunOS") || os.equals("Linux"))
 198                     throw x;
 199                 System.out.println("Exclude-mode filtering not supported!");
 200             }
 201 
 202             key.drop();
 203 
 204             // include-mode filtering
 205 
 206             InetAddress bogus = (group instanceof Inet6Address) ?
 207                 InetAddress.getByName("fe80::1234") :
 208                 InetAddress.getByName("1.2.3.4");
 209             System.out.format("join %s @ %s only-source %s\n", group.getHostAddress(),
 210                 nif.getName(), bogus.getHostAddress());
 211             try {
 212                 // may throw UOE
 213                 key = dc.join(group, nif, bogus);
 214 
 215                 id = sendDatagram(source, nif, group, port);
 216                 receiveDatagram(dc, null, id);
 217 
 218                 System.out.format("join %s @ %s only-source %s\n", group.getHostAddress(),
 219                     nif.getName(), source.getHostAddress());
 220                 key = dc.join(group, nif, source);
 221 
 222                 id = sendDatagram(source, nif, group, port);
 223                 receiveDatagram(dc, source, id);
 224             } catch (UnsupportedOperationException x) {
 225                 String os = System.getProperty("os.name");
 226                 // Include-mode filtering supported on these platforms so UOE should never be thrown
 227                 if (os.equals("SunOS") || os.equals("Linux"))
 228                     throw x;
 229                 System.out.println("Include-mode filtering not supported!");
 230             }
 231         }
 232     }
 233 
 234     public static void main(String[] args) throws IOException {
 235         NetworkConfiguration config = NetworkConfiguration.probe();
 236 
 237         // multicast groups used for the test
 238         InetAddress ip4Group = InetAddress.getByName("225.4.5.6");
 239         InetAddress ip6Group = InetAddress.getByName("ff02::a");
 240 
 241         for (NetworkInterface nif: config.ip4Interfaces()) {
 242             InetAddress source = config.ip4Addresses(nif).iterator().next();
 243             test(INET,   nif, ip4Group, source);
 244             test(UNSPEC, nif, ip4Group, source);
 245         }
 246 
 247         for (NetworkInterface nif: config.ip6Interfaces()) {
 248             InetAddress source = config.ip6Addresses(nif).iterator().next();
 249             test(INET6,  nif, ip6Group, source);
 250             test(UNSPEC, nif, ip6Group, source);
 251         }
 252     }
 253 }