1 /*
   2  * Copyright (c) 2009, 2014, 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 4927640
  26  * @summary Tests the SCTP protocol implementation
  27  * @author chegar
  28  */
  29 
  30 import java.io.IOException;
  31 import java.net.InetSocketAddress;
  32 import java.net.SocketAddress;
  33 import java.util.Iterator;
  34 import java.util.Set;
  35 import java.util.List;
  36 import java.util.Arrays;
  37 import java.nio.ByteBuffer;
  38 import java.nio.channels.ClosedChannelException;
  39 import com.sun.nio.sctp.AbstractNotificationHandler;
  40 import com.sun.nio.sctp.Association;
  41 import com.sun.nio.sctp.AssociationChangeNotification;
  42 import com.sun.nio.sctp.AssociationChangeNotification.AssocChangeEvent;
  43 import com.sun.nio.sctp.HandlerResult;
  44 import com.sun.nio.sctp.MessageInfo;
  45 import com.sun.nio.sctp.SctpChannel;
  46 import com.sun.nio.sctp.SctpMultiChannel;
  47 import com.sun.nio.sctp.SctpServerChannel;
  48 import com.sun.nio.sctp.SctpSocketOption;
  49 import java.security.AccessController;
  50 import java.security.PrivilegedAction;
  51 import static com.sun.nio.sctp.SctpStandardSocketOptions.*;
  52 import static java.lang.System.out;
  53 
  54 public class SocketOptionTests {
  55     final String osName = AccessController.doPrivileged(
  56                     (PrivilegedAction<String>)() -> System.getProperty("os.name"));
  57 
  58     <T> void checkOption(SctpMultiChannel smc, SctpSocketOption<T> name,
  59             T expectedValue) throws IOException {
  60         T value = smc.getOption(name, null);
  61         check(value.equals(expectedValue), name + ": value (" + value +
  62                 ") not as expected (" + expectedValue + ")");
  63        }
  64 
  65     <T> void optionalSupport(SctpMultiChannel smc, SctpSocketOption<T> name,
  66             T value) {
  67         try {
  68             smc.setOption(name, value, null);
  69             checkOption(smc, name, value);
  70         } catch (IOException e) {
  71             /* Informational only, not all options have native support */
  72             out.println(name + " not supported. " + e);
  73         }
  74     }
  75 
  76     void test(String[] args) {
  77         if (!Util.isSCTPSupported()) {
  78             out.println("SCTP protocol is not supported");
  79             out.println("Test cannot be run");
  80             return;
  81         }
  82 
  83         try {
  84             SctpMultiChannel smc = SctpMultiChannel.open();
  85 
  86             /* check supported options */
  87             Set<SctpSocketOption<?>> options = smc.supportedOptions();
  88             List<? extends SctpSocketOption<?>> expected = Arrays.<SctpSocketOption<?>>asList(
  89                     SCTP_DISABLE_FRAGMENTS, SCTP_EXPLICIT_COMPLETE,
  90                     SCTP_FRAGMENT_INTERLEAVE, SCTP_INIT_MAXSTREAMS,
  91                     SCTP_NODELAY, SCTP_PRIMARY_ADDR, SCTP_SET_PEER_PRIMARY_ADDR,
  92                     SO_SNDBUF, SO_RCVBUF, SO_LINGER);
  93 
  94             for (SctpSocketOption opt: expected) {
  95                 if (!options.contains(opt))
  96                     fail(opt.name() + " should be supported");
  97             }
  98 
  99             InitMaxStreams streams = InitMaxStreams.create(1024, 1024);
 100             smc.setOption(SCTP_INIT_MAXSTREAMS, streams, null);
 101             checkOption(smc, SCTP_INIT_MAXSTREAMS, streams);
 102             streams = smc.getOption(SCTP_INIT_MAXSTREAMS, null);
 103             check(streams.maxInStreams() == 1024, "Max in streams: value: "
 104                     + streams.maxInStreams() + ", expected 1024 ");
 105             check(streams.maxOutStreams() == 1024, "Max out streams: value: "
 106                     + streams.maxOutStreams() + ", expected 1024 ");
 107 
 108             optionalSupport(smc, SCTP_DISABLE_FRAGMENTS, true);
 109             optionalSupport(smc, SCTP_EXPLICIT_COMPLETE, true);
 110             optionalSupport(smc, SCTP_FRAGMENT_INTERLEAVE, 1);
 111 
 112             smc.setOption(SCTP_NODELAY, true, null);
 113             checkOption(smc, SCTP_NODELAY, true);
 114             smc.setOption(SO_SNDBUF, 16*1024, null);
 115             smc.setOption(SO_RCVBUF, 16*1024, null);
 116 
 117             checkOption(smc, SO_LINGER, -1);  /* default should be negative */
 118 
 119             /* Setting SO_LINGER not support for one-to-many on Solaris */
 120             if (!"SunOS".equals(osName)) {
 121                 smc.setOption(SO_LINGER, 2000, null);
 122                 checkOption(smc, SO_LINGER, 2000);
 123             }
 124 
 125             /* SCTP_PRIMARY_ADDR */
 126             sctpPrimaryAddr();
 127 
 128             /* NullPointerException */
 129             try {
 130                 smc.setOption(null, "value", null);
 131                 fail("NullPointerException not thrown for setOption");
 132             } catch (NullPointerException unused) {
 133                 pass();
 134             }
 135             try {
 136                smc.getOption(null, null);
 137                fail("NullPointerException not thrown for getOption");
 138             } catch (NullPointerException unused) {
 139                pass();
 140             }
 141 
 142             /* ClosedChannelException */
 143             smc.close();
 144             try {
 145                smc.setOption(SCTP_INIT_MAXSTREAMS, streams, null);
 146                fail("ClosedChannelException not thrown");
 147             } catch (ClosedChannelException unused) {
 148                 pass();
 149             }
 150         } catch (IOException ioe) {
 151             unexpected(ioe);
 152         }
 153     }
 154 
 155     /* SCTP_PRIMARY_ADDR */
 156     void sctpPrimaryAddr() throws IOException {
 157         ByteBuffer buffer = ByteBuffer.allocate(Util.SMALL_BUFFER);
 158 
 159         System.out.println("TESTING SCTP_PRIMARY_ADDR");
 160 
 161         /* create listening channel */
 162         SctpServerChannel ssc = SctpServerChannel.open().bind(null);
 163         Set<SocketAddress> addrs = ssc.getAllLocalAddresses();
 164         if (addrs.isEmpty())
 165             debug("addrs should not be empty");
 166 
 167         InetSocketAddress serverAddr = (InetSocketAddress) addrs.iterator().next();
 168 
 169         /* setup an association implicitly by sending a small message */
 170         int streamNumber = 0;
 171         debug("sending to " + serverAddr + " on stream number: " + streamNumber);
 172         MessageInfo info = MessageInfo.createOutgoing(serverAddr, streamNumber);
 173         buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
 174         buffer.flip();
 175 
 176         debug("sending small message: " + buffer);
 177         SctpMultiChannel smc = SctpMultiChannel.open();
 178         int sent = smc.send(buffer, info);
 179 
 180         /* Receive the COMM_UP */
 181         buffer.clear();
 182         SOTNotificationHandler handler = new SOTNotificationHandler();
 183         info = smc.receive(buffer, null, handler);
 184         check(handler.receivedCommUp(), "COMM_UP no received");
 185         Set<Association> associations = smc.associations();
 186         check(!associations.isEmpty(),"There should be some associations");
 187         Association assoc = associations.iterator().next();
 188 
 189         SctpChannel peerChannel = ssc.accept();
 190         ssc.close();
 191         Set<SocketAddress> remoteAddresses = smc.getRemoteAddresses(assoc);
 192         debug("Remote Addresses: ");
 193         for (Iterator<SocketAddress> it = remoteAddresses.iterator(); it.hasNext(); ) {
 194             InetSocketAddress addr = (InetSocketAddress)it.next();
 195             debug("\t" + addr);
 196         }
 197 
 198         /* retrieval of SCTP_PRIMARY_ADDR is not supported on Solaris */
 199         if ("SunOS".equals(osName)) {
 200             /* For now do not set this option. There is a bug on Solaris 10 pre Update 5
 201              * where setting this option returns Invalid argument */
 202             //debug("Set SCTP_PRIMARY_ADDR with " + addrToSet);
 203             //smc.setOption(SCTP_PRIMARY_ADDR, addrToSet, assoc);
 204             return;
 205         } else { /* Linux */
 206             SocketAddress primaryAddr = smc.getOption(SCTP_PRIMARY_ADDR, assoc);
 207             System.out.println("SCTP_PRIMARY_ADDR returned: " + primaryAddr);
 208             /* Verify that this is one of the remote addresses */
 209             check(remoteAddresses.contains(primaryAddr), "SCTP_PRIMARY_ADDR returned bogus address!");
 210 
 211             for (Iterator<SocketAddress> it = remoteAddresses.iterator(); it.hasNext(); ) {
 212                 InetSocketAddress addrToSet = (InetSocketAddress) it.next();
 213                 System.out.println("SCTP_PRIMARY_ADDR try set to: " + addrToSet);
 214                 smc.setOption(SCTP_PRIMARY_ADDR, addrToSet, assoc);
 215                 System.out.println("SCTP_PRIMARY_ADDR set to    : " + addrToSet);
 216                 primaryAddr = smc.getOption(SCTP_PRIMARY_ADDR, assoc);
 217                 System.out.println("SCTP_PRIMARY_ADDR returned  : " + primaryAddr);
 218                 check(addrToSet.equals(primaryAddr), "SCTP_PRIMARY_ADDR not set correctly");
 219             }
 220         }
 221         smc.close();
 222         peerChannel.close();
 223     }
 224 
 225     class SOTNotificationHandler extends AbstractNotificationHandler<Object>
 226     {
 227         boolean receivedCommUp;  // false
 228 
 229         boolean receivedCommUp() {
 230             return receivedCommUp;
 231         }
 232 
 233         @Override
 234         public HandlerResult handleNotification(
 235                 AssociationChangeNotification notification, Object attachment) {
 236             AssocChangeEvent event = notification.event();
 237             debug("AssociationChangeNotification");
 238             debug("  Association: " + notification.association());
 239             debug("  Event: " + event);
 240 
 241             if (event.equals(AssocChangeEvent.COMM_UP))
 242                 receivedCommUp = true;
 243 
 244             return HandlerResult.RETURN;
 245         }
 246     }
 247 
 248             //--------------------- Infrastructure ---------------------------
 249     boolean debug = true;
 250     volatile int passed = 0, failed = 0;
 251     void pass() {passed++;}
 252     void fail() {failed++; Thread.dumpStack();}
 253     void fail(String msg) {System.err.println(msg); fail();}
 254     void unexpected(Throwable t) {failed++; t.printStackTrace();}
 255     void check(boolean cond) {if (cond) pass(); else fail();}
 256     void check(boolean cond, String failMessage) {if (cond) pass(); else fail(failMessage);}
 257     void debug(String message) {if(debug) { System.out.println(message); }  }
 258     public static void main(String[] args) throws Throwable {
 259         Class<?> k = new Object(){}.getClass().getEnclosingClass();
 260         try {k.getMethod("instanceMain",String[].class)
 261                 .invoke( k.newInstance(), (Object) args);}
 262         catch (Throwable e) {throw e.getCause();}}
 263     public void instanceMain(String[] args) throws Throwable {
 264         try {test(args);} catch (Throwable t) {unexpected(t);}
 265         System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
 266         if (failed > 0) throw new AssertionError("Some tests failed");}
 267 }