1 /*
   2  * Copyright (c) 2013, 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 8014377
  26  * @summary Test for interference when two sockets are bound to the same
  27  *   port but joined to different multicast groups
  28  * @build Promiscuous  NetworkConfiguration
  29  * @run main Promiscuous
  30  * @run main/othervm -Djava.net.preferIPv4Stack=true Promiscuous
  31  */
  32 
  33 import java.nio.ByteBuffer;
  34 import java.nio.channels.*;
  35 import java.net.*;
  36 import static java.net.StandardProtocolFamily.*;
  37 import java.util.*;
  38 import java.io.IOException;
  39 
  40 public class Promiscuous {
  41 
  42     static final Random rand = new Random();
  43 
  44     static final ProtocolFamily UNSPEC = new ProtocolFamily() {
  45         public String name() {
  46             return "UNSPEC";
  47         }
  48     };
  49 
  50     /**
  51      * Sends a datagram to the given multicast group
  52      */
  53     static int sendDatagram(NetworkInterface nif,
  54                             InetAddress group,
  55                             int port)
  56         throws IOException
  57     {
  58         ProtocolFamily family = (group instanceof Inet6Address) ?
  59             StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
  60         DatagramChannel dc = DatagramChannel.open(family)
  61             .setOption(StandardSocketOptions.IP_MULTICAST_IF, nif);
  62         int id = rand.nextInt();
  63         byte[] msg = Integer.toString(id).getBytes("UTF-8");
  64         ByteBuffer buf = ByteBuffer.wrap(msg);
  65         System.out.format("Send message -> group %s (id=0x%x)\n",
  66             group.getHostAddress(), id);
  67         dc.send(buf, new InetSocketAddress(group, port));
  68         dc.close();
  69         return id;
  70     }
  71 
  72     /**
  73      * Wait (with timeout) for datagram. The {@code datagramExepcted}
  74      * parameter indicates whether a datagram is expected, and if
  75      * {@true} then {@code id} is the identifier in the payload.
  76      */
  77     static void receiveDatagram(DatagramChannel dc,
  78                                 String name,
  79                                 boolean datagramExepcted,
  80                                 int id)
  81         throws IOException
  82     {
  83         System.out.println("Checking if received by " + name);
  84 
  85         Selector sel = Selector.open();
  86         dc.configureBlocking(false);
  87         dc.register(sel, SelectionKey.OP_READ);
  88         ByteBuffer buf = ByteBuffer.allocateDirect(100);
  89 
  90         try {
  91             for (;;) {
  92                 System.out.println("Waiting to receive message");
  93                 sel.select(5*1000);
  94                 SocketAddress sa = dc.receive(buf);
  95 
  96                 // no datagram received
  97                 if (sa == null) {
  98                     if (datagramExepcted) {
  99                         throw new RuntimeException("Expected message not recieved");
 100                     }
 101                     System.out.println("No message received (correct)");
 102                     return;
 103                 }
 104 
 105                 // datagram received
 106 
 107                 InetAddress sender = ((InetSocketAddress)sa).getAddress();
 108                 buf.flip();
 109                 byte[] bytes = new byte[buf.remaining()];
 110                 buf.get(bytes);
 111                 int receivedId = Integer.parseInt(new String(bytes));
 112 
 113                 System.out.format("Received message from %s (id=0x%x)\n",
 114                     sender, receivedId);
 115 
 116                 if (!datagramExepcted) {
 117                     if (receivedId == id)
 118                         throw new RuntimeException("Message not expected");
 119                     System.out.println("Message ignored (has wrong id)");
 120                 } else {
 121                     if (receivedId == id) {
 122                         System.out.println("Message expected");
 123                         return;
 124                     }
 125                     System.out.println("Message ignored (wrong sender)");
 126                 }
 127 
 128                 sel.selectedKeys().clear();
 129                 buf.rewind();
 130             }
 131         } finally {
 132             sel.close();
 133         }
 134     }
 135 
 136     static void test(ProtocolFamily family,
 137                      NetworkInterface nif,
 138                      InetAddress group1,
 139                      InetAddress group2)
 140         throws IOException
 141     {
 142 
 143         System.out.format("%nTest family=%s%n", family.name());
 144 
 145         DatagramChannel dc1 = (family == UNSPEC) ?
 146             DatagramChannel.open() : DatagramChannel.open(family);
 147         DatagramChannel dc2 = (family == UNSPEC) ?
 148             DatagramChannel.open() : DatagramChannel.open(family);
 149 
 150         try {
 151             dc1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
 152             dc2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
 153 
 154             dc1.bind(new InetSocketAddress(0));
 155             int port = dc1.socket().getLocalPort();
 156             dc2.bind(new InetSocketAddress(port));
 157 
 158             System.out.format("dc1 joining [%s]:%d @ %s\n",
 159                 group1.getHostAddress(), port, nif.getName());
 160             System.out.format("dc2 joining [%s]:%d @ %s\n",
 161                 group2.getHostAddress(), port, nif.getName());
 162 
 163             dc1.join(group1, nif);
 164             dc2.join(group2, nif);
 165 
 166             int id = sendDatagram(nif, group1, port);
 167 
 168             receiveDatagram(dc1, "dc1", true, id);
 169             receiveDatagram(dc2, "dc2", false, id);
 170 
 171             id = sendDatagram(nif, group2, port);
 172 
 173             receiveDatagram(dc1, "dc1", false, id);
 174             receiveDatagram(dc2, "dc2", true, id);
 175 
 176         } finally {
 177             dc1.close();
 178             dc2.close();
 179         }
 180     }
 181 
 182     public static void main(String[] args) throws IOException {
 183         String os = System.getProperty("os.name");
 184 
 185         // Requires IP_MULTICAST_ALL on Linux (new since 2.6.31) so skip
 186         // on older kernels. Note that we skip on <= version 3 to keep the
 187         // parsing simple
 188         if (os.equals("Linux")) {
 189             String osversion = System.getProperty("os.version");
 190             String[] vers = osversion.split("\\.", 0);
 191             int major = Integer.parseInt(vers[0]);
 192             if (major < 3) {
 193                 System.out.format("Kernel version is %s, test skipped%n", osversion);
 194                 return;
 195             }
 196         }
 197 
 198         // get local network configuration to use
 199         NetworkConfiguration config = NetworkConfiguration.probe();
 200 
 201         // multicast groups used for the test
 202         InetAddress ip4Group1 = InetAddress.getByName("225.4.5.6");
 203         InetAddress ip4Group2 = InetAddress.getByName("225.4.6.6");
 204 
 205         for (NetworkInterface nif: config.ip4Interfaces()) {
 206             InetAddress source = config.ip4Addresses(nif).iterator().next();
 207             test(INET, nif, ip4Group1, ip4Group2);
 208 
 209             // Solaris and Linux allow IPv6 sockets join IPv4 multicast groups
 210             if (os.equals("SunOS") || os.equals("Linux"))
 211                 test(UNSPEC, nif, ip4Group1, ip4Group2);
 212         }
 213     }
 214 }