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