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  * @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 
  41 public class Promiscuous {
  42 
  43     static final Random rand = new Random();
  44 
  45     static final ProtocolFamily UNSPEC = new ProtocolFamily() {
  46         public String name() {
  47             return "UNSPEC";
  48         }
  49     };
  50 
  51     /**
  52      * Sends a datagram to the given multicast group
  53      */
  54     static int sendDatagram(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             .setOption(StandardSocketOptions.IP_MULTICAST_IF, nif);
  63         int id = rand.nextInt();
  64         byte[] msg = Integer.toString(id).getBytes("UTF-8");
  65         ByteBuffer buf = ByteBuffer.wrap(msg);
  66         System.out.format("Send message -> group %s (id=0x%x)\n",
  67             group.getHostAddress(), id);
  68         dc.send(buf, new InetSocketAddress(group, port));
  69         dc.close();
  70         return id;
  71     }
  72 
  73     /**
  74      * Wait (with timeout) for datagram. The {@code datagramExepcted}
  75      * parameter indicates whether a datagram is expected, and if
  76      * {@true} then {@code id} is the identifier in the payload.
  77      */
  78     static void receiveDatagram(DatagramChannel dc,
  79                                 String name,
  80                                 boolean datagramExepcted,
  81                                 int id)
  82         throws IOException
  83     {
  84         System.out.println("Checking if received by " + name);
  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 (datagramExepcted) {
 100                         throw new RuntimeException("Expected message not recieved");
 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                 int receivedId = Integer.parseInt(new String(bytes));
 113 
 114                 System.out.format("Received message from %s (id=0x%x)\n",
 115                     sender, receivedId);
 116 
 117                 if (!datagramExepcted) {
 118                     if (receivedId == id)
 119                         throw new RuntimeException("Message not expected");
 120                     System.out.println("Message ignored (has wrong id)");
 121                 } else {
 122                     if (receivedId == id) {
 123                         System.out.println("Message expected");
 124                         return;
 125                     }
 126                     System.out.println("Message ignored (wrong sender)");
 127                 }
 128 
 129                 sel.selectedKeys().clear();
 130                 buf.rewind();
 131             }
 132         } finally {
 133             sel.close();
 134         }
 135     }
 136 
 137     static void test(ProtocolFamily family,
 138                      NetworkInterface nif,
 139                      InetAddress group1,
 140                      InetAddress group2)
 141         throws IOException
 142     {
 143 
 144         System.out.format("%nTest family=%s%n", family.name());
 145 
 146         DatagramChannel dc1 = (family == UNSPEC) ?
 147             DatagramChannel.open() : DatagramChannel.open(family);
 148         DatagramChannel dc2 = (family == UNSPEC) ?
 149             DatagramChannel.open() : DatagramChannel.open(family);
 150 
 151         try {
 152             dc1.setOption(StandardSocketOptions.SO_REUSEADDR, true);
 153             dc2.setOption(StandardSocketOptions.SO_REUSEADDR, true);
 154 
 155             dc1.bind(new InetSocketAddress(0));
 156             int port = dc1.socket().getLocalPort();
 157             dc2.bind(new InetSocketAddress(port));
 158 
 159             System.out.format("dc1 joining [%s]:%d @ %s\n",
 160                 group1.getHostAddress(), port, nif.getName());
 161             System.out.format("dc2 joining [%s]:%d @ %s\n",
 162                 group2.getHostAddress(), port, nif.getName());
 163 
 164             dc1.join(group1, nif);
 165             dc2.join(group2, nif);
 166 
 167             int id = sendDatagram(nif, group1, port);
 168 
 169             receiveDatagram(dc1, "dc1", true, id);
 170             receiveDatagram(dc2, "dc2", false, id);
 171 
 172             id = sendDatagram(nif, group2, port);
 173 
 174             receiveDatagram(dc1, "dc1", false, id);
 175             receiveDatagram(dc2, "dc2", true, id);
 176 
 177         } finally {
 178             dc1.close();
 179             dc2.close();
 180         }
 181     }
 182 
 183     public static void main(String[] args) throws IOException {
 184         String os = System.getProperty("os.name");
 185 
 186         // Requires IP_MULTICAST_ALL on Linux (new since 2.6.31) so skip
 187         // on older kernels. Note that we skip on <= version 3 to keep the
 188         // parsing simple
 189         if (os.equals("Linux")) {
 190             String osversion = System.getProperty("os.version");
 191             String[] vers = osversion.split("\\.", 0);
 192             int major = Integer.parseInt(vers[0]);
 193             if (major < 3) {
 194                 System.out.format("Kernel version is %s, test skipped%n", osversion);
 195                 return;
 196             }
 197         }
 198 
 199         // get local network configuration to use
 200         NetworkConfiguration config = NetworkConfiguration.probe();
 201 
 202         // multicast groups used for the test
 203         InetAddress ip4Group1 = InetAddress.getByName("225.4.5.6");
 204         InetAddress ip4Group2 = InetAddress.getByName("225.4.6.6");
 205 
 206         for (NetworkInterface nif: config.ip4Interfaces()) {
 207             InetAddress source = config.ip4Addresses(nif).iterator().next();
 208             test(INET, nif, ip4Group1, ip4Group2);
 209 
 210             // Solaris and Linux allow IPv6 sockets join IPv4 multicast groups
 211             if (os.equals("SunOS") || os.equals("Linux"))
 212                 test(UNSPEC, nif, ip4Group1, ip4Group2);
 213         }
 214     }
 215 }