Java Code Examples for javax.net.ssl.SSLSocket#connect()
The following examples show how to use
javax.net.ssl.SSLSocket#connect() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BasicOpenSSLEngineTest.java From wildfly-openssl with Apache License 2.0 | 6 votes |
@Test public void openSslLotsOfDataTest() throws IOException, NoSuchAlgorithmException, InterruptedException { try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) { final AtomicReference<byte[]> sessionID = new AtomicReference<>(); final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLSv1"); EchoRunnable target = new EchoRunnable(serverSocket, sslContext, sessionID); Thread acceptThread = new Thread(target); acceptThread.start(); final SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); socket.connect(SSLTestUtils.createSocketAddress()); String message = generateMessage(1000); socket.getOutputStream().write(message.getBytes(StandardCharsets.US_ASCII)); socket.getOutputStream().write(new byte[]{0}); Assert.assertEquals(message, new String(SSLTestUtils.readData(socket.getInputStream()))); Assert.assertArrayEquals(socket.getSession().getId(), sessionID.get()); serverSocket.close(); acceptThread.join(); } }
Example 2
Source File: EasySSLSocketFactory.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, * java.lang.String, int, java.net.InetAddress, int, * org.apache.http.params.HttpParams) */ @Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
Example 3
Source File: EasySSLSocketFactory.java From panoramagl with Apache License 2.0 | 6 votes |
/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(Socket, * String, int, InetAddress, int, * HttpParams) */ public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
Example 4
Source File: EasyHttpClient.java From mobilecloud-15 with Apache License 2.0 | 6 votes |
/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, * java.lang.String, int, java.net.InetAddress, int, * org.apache.http.params.HttpParams) */ public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
Example 5
Source File: BasicOpenSSLEngineTest.java From wildfly-openssl with Apache License 2.0 | 6 votes |
@Test(expected = SSLException.class) public void testWrongClientSideTrustManagerFailsValidation() throws IOException, NoSuchAlgorithmException, InterruptedException { try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) { final AtomicReference<byte[]> sessionID = new AtomicReference<>(); final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLSv1"); Thread acceptThread = new Thread(new EchoRunnable(serverSocket, sslContext, sessionID)); acceptThread.start(); final SSLSocket socket = (SSLSocket) SSLTestUtils.createSSLContext("openssl.TLSv1").getSocketFactory().createSocket(); socket.setSSLParameters(socket.getSSLParameters()); socket.connect(SSLTestUtils.createSocketAddress()); socket.getOutputStream().write(MESSAGE.getBytes(StandardCharsets.US_ASCII)); socket.getSession().invalidate(); socket.close(); serverSocket.close(); acceptThread.join(); } }
Example 6
Source File: BasicOpenSSLEngineTest.java From wildfly-openssl with Apache License 2.0 | 6 votes |
@Test public void basicOpenSSLTest() throws IOException, NoSuchAlgorithmException, InterruptedException { try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) { final AtomicReference<byte[]> sessionID = new AtomicReference<>(); final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLSv1"); Thread acceptThread = new Thread(new EchoRunnable(serverSocket, sslContext, sessionID)); acceptThread.start(); final SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); socket.connect(SSLTestUtils.createSocketAddress()); socket.getOutputStream().write(MESSAGE.getBytes(StandardCharsets.US_ASCII)); byte[] data = new byte[100]; int read = socket.getInputStream().read(data); Assert.assertEquals(MESSAGE, new String(data, 0, read)); Assert.assertArrayEquals(socket.getSession().getId(), sessionID.get()); socket.getSession().invalidate(); socket.close(); serverSocket.close(); acceptThread.join(); } }
Example 7
Source File: BasicOpenSSLEngineTest.java From wildfly-openssl with Apache License 2.0 | 5 votes |
@Test public void testNoExplicitEnabledProtocols() throws IOException, InterruptedException { try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) { final AtomicReference<byte[]> sessionID = new AtomicReference<>(); final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLS"); final AtomicReference<SSLEngine> engineRef = new AtomicReference<>(); EchoRunnable echo = new EchoRunnable(serverSocket, sslContext, sessionID, (engine -> { engineRef.set(engine); try { return engine; } catch (Exception e) { throw new RuntimeException(e); } })); Thread acceptThread = new Thread(echo); acceptThread.start(); final SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); socket.connect(SSLTestUtils.createSocketAddress()); socket.getOutputStream().write(MESSAGE.getBytes(StandardCharsets.US_ASCII)); byte[] data = new byte[100]; int read = socket.getInputStream().read(data); Assert.assertEquals(MESSAGE, new String(data, 0, read)); Assert.assertArrayEquals(socket.getSession().getId(), sessionID.get()); Assert.assertEquals("TLSv1.2", socket.getSession().getProtocol()); socket.getSession().invalidate(); socket.close(); serverSocket.close(); acceptThread.join(); } }
Example 8
Source File: BasicOpenSSLEngineTest.java From wildfly-openssl with Apache License 2.0 | 5 votes |
@Test public void testSingleEnabledProtocol() throws IOException, InterruptedException { final String[] protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }; for (String protocol : protocols) { try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) { final AtomicReference<byte[]> sessionID = new AtomicReference<>(); final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLS"); final AtomicReference<SSLEngine> engineRef = new AtomicReference<>(); EchoRunnable echo = new EchoRunnable(serverSocket, sslContext, sessionID, (engine -> { engineRef.set(engine); try { engine.setEnabledProtocols(new String[]{ protocol }); // only one protocol enabled on server side return engine; } catch (Exception e) { throw new RuntimeException(e); } })); Thread acceptThread = new Thread(echo); acceptThread.start(); final SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); socket.connect(SSLTestUtils.createSocketAddress()); socket.getOutputStream().write(MESSAGE.getBytes(StandardCharsets.US_ASCII)); byte[] data = new byte[100]; int read = socket.getInputStream().read(data); Assert.assertEquals(MESSAGE, new String(data, 0, read)); Assert.assertArrayEquals(socket.getSession().getId(), sessionID.get()); Assert.assertEquals(protocol, socket.getSession().getProtocol()); Assert.assertArrayEquals(new String[]{ SSL_PROTO_SSLv2Hello, protocol }, engineRef.get().getEnabledProtocols()); socket.getSession().invalidate(); socket.close(); serverSocket.close(); acceptThread.join(); } } }
Example 9
Source File: BasicOpenSSLEngineTest.java From wildfly-openssl with Apache License 2.0 | 5 votes |
@Test public void testMultipleEnabledProtocolsWithClientProtocolWithinEnabledRange() throws IOException, InterruptedException { final String[] protocols = new String[] { "TLSv1", "TLSv1.2" }; try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) { final AtomicReference<byte[]> sessionID = new AtomicReference<>(); final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLS"); final AtomicReference<SSLEngine> engineRef = new AtomicReference<>(); EchoRunnable echo = new EchoRunnable(serverSocket, sslContext, sessionID, (engine -> { engineRef.set(engine); try { engine.setEnabledProtocols(protocols); return engine; } catch (Exception e) { throw new RuntimeException(e); } })); Thread acceptThread = new Thread(echo); acceptThread.start(); SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); socket.setEnabledProtocols(new String[] { "TLSv1.1" }); socket.connect(SSLTestUtils.createSocketAddress()); socket.getOutputStream().write(MESSAGE.getBytes(StandardCharsets.US_ASCII)); byte[] data = new byte[100]; int read = socket.getInputStream().read(data); Assert.assertEquals(MESSAGE, new String(data, 0, read)); Assert.assertArrayEquals(socket.getSession().getId(), sessionID.get()); Assert.assertEquals("TLSv1.1", socket.getSession().getProtocol()); Assert.assertArrayEquals(new String[]{ SSL_PROTO_SSLv2Hello, "TLSv1", "TLSv1.1", "TLSv1.2" }, engineRef.get().getEnabledProtocols()); socket.getSession().invalidate(); socket.close(); serverSocket.close(); acceptThread.join(); } }
Example 10
Source File: CoreSocketFactory.java From cloud-sql-jdbc-socket-factory with Apache License 2.0 | 5 votes |
/** * Creates a secure socket representing a connection to a Cloud SQL instance. * * @param instanceName Name of the Cloud SQL instance. * @param ipTypes Preferred type of IP to use ("PRIVATE", "PUBLIC") * @return the newly created Socket. * @throws IOException if error occurs during socket creation. */ // TODO(berezv): separate creating socket and performing connection to make it easier to test @VisibleForTesting Socket createSslSocket(String instanceName, List<String> ipTypes) throws IOException { CloudSqlInstance instance = instances.computeIfAbsent( instanceName, k -> new CloudSqlInstance(k, adminApi, executor, localKeyPair)); try { SSLSocket socket = instance.createSslSocket(); // TODO(kvg): Support all socket related options listed here: // https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html socket.setKeepAlive(true); socket.setTcpNoDelay(true); String instanceIp = instance.getPreferredIp(ipTypes); socket.connect(new InetSocketAddress(instanceIp, serverProxyPort)); socket.startHandshake(); return socket; } catch (Exception ex) { // TODO(kvg): Let user know about the rate limit instance.forceRefresh(); throw ex; } }
Example 11
Source File: ApacheConnectionManagerFactory.java From ibm-cos-sdk-java with Apache License 2.0 | 5 votes |
@Override public Socket connectSocket(int connectTimeout, Socket sock, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException { SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket(context)); if (localAddress != null) sslsock.bind(localAddress); sslsock.connect(remoteAddress, connectTimeout); // socket timeout is set internally by the // PoolingHttpClientConnectionManager. return sslsock; }
Example 12
Source File: BasicOpenSSLSocketDSATest.java From wildfly-openssl with Apache License 2.0 | 5 votes |
@Test public void basicOpenSSLTest1() throws IOException, NoSuchAlgorithmException, InterruptedException { try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) { final AtomicReference<byte[]> sessionID = new AtomicReference<>(); Thread acceptThread = new Thread(new EchoRunnable(serverSocket, SSLTestUtils.createDSASSLContext("TLSv1.2"), sessionID, engine -> { engine.setEnabledCipherSuites(new String[] {"TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"}); return engine; })); acceptThread.start(); final SSLContext sslContext = SSLTestUtils.createClientDSASSLContext("openssl.TLSv1.2"); final SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(); socket.setEnabledCipherSuites(new String[] {"TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"}); socket.connect(SSLTestUtils.createSocketAddress()); socket.getOutputStream().write("hello world".getBytes(StandardCharsets.US_ASCII)); socket.getOutputStream().flush(); byte[] data = new byte[100]; int read = socket.getInputStream().read(data); Assert.assertEquals("hello world", new String(data, 0, read)); //TODO: fix client session id //Assert.assertArrayEquals(socket.getSession().getId(), sessionID.get()); serverSocket.close(); acceptThread.join(); } }
Example 13
Source File: SslSocketManager.java From logging-log4j2 with Apache License 2.0 | 5 votes |
static Socket createSocket(final InetSocketAddress socketAddress, final int connectTimeoutMillis, final SslConfiguration sslConfiguration, final SocketOptions socketOptions) throws IOException { final SSLSocketFactory socketFactory = createSslSocketFactory(sslConfiguration); final SSLSocket socket = (SSLSocket) socketFactory.createSocket(); if (socketOptions != null) { // Not sure which options must be applied before or after the connect() call. socketOptions.apply(socket); } socket.connect(socketAddress, connectTimeoutMillis); if (socketOptions != null) { // Not sure which options must be applied before or after the connect() call. socketOptions.apply(socket); } return socket; }
Example 14
Source File: Connection.java From deskcon-android with GNU General Public License v3.0 | 5 votes |
public static SSLSocket createSSLSocket(Context context, String host, int port) throws UnknownHostException, IOException { // init SSL Context SSLContext sslcontext = null; try { sslcontext = initSSLContext(context); } catch (Exception e) { e.printStackTrace(); } // make secure Connection SSLSocketFactory factory = (SSLSocketFactory) sslcontext.getSocketFactory(); SSLSocket sslsocket = (SSLSocket) factory.createSocket(); sslsocket.setUseClientMode(true); sslsocket.connect(new InetSocketAddress(host, port), 500); if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ) { sslsocket.setEnabledProtocols(new String[] {"TLSv1","TLSv1.1","TLSv1.2"}); } else { sslsocket.setEnabledProtocols(new String[] {"TLSv1"}); } Log.d("Connection: ", "using Protocol "+sslsocket.getSession().getProtocol()); Log.d("Connection: ", "Session valid "+sslsocket.getSession().isValid()); return sslsocket; }
Example 15
Source File: HandshakeCompletedEventTest.java From j2objc with Apache License 2.0 | 5 votes |
public void run() { try { KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null; TrustManager[] trustManagers = new TrustManager[] { trustManager }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket(); socket.connect(serverSocket.getLocalSocketAddress()); socket.addHandshakeCompletedListener(listener); socket.startHandshake(); OutputStream ostream = socket.getOutputStream(); for (int i = 0; i < 256; i++) { ostream.write(i); } ostream.flush(); ostream.close(); InputStream istream = socket.getInputStream(); for (int i = 0; i < 256; i++) { int j = istream.read(); assertEquals(i, j); } istream.close(); socket.close(); } catch (Exception ex) { exception = ex; } }
Example 16
Source File: SSLSocketTest.java From j2objc with Apache License 2.0 | 5 votes |
public void test_SSLSocket_SNIHostName() throws Exception { TestSSLContext c = TestSSLContext.create(); final SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(); SSLParameters clientParams = client.getSSLParameters(); clientParams.setServerNames(Collections.singletonList( (SNIServerName) new SNIHostName("www.example.com"))); client.setSSLParameters(clientParams); SSLParameters serverParams = c.serverSocket.getSSLParameters(); serverParams.setSNIMatchers(Collections.singletonList( SNIHostName.createSNIMatcher("www\\.example\\.com"))); c.serverSocket.setSSLParameters(serverParams); client.connect(new InetSocketAddress(c.host, c.port)); final SSLSocket server = (SSLSocket) c.serverSocket.accept(); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Void> future = executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { client.startHandshake(); return null; } }); executor.shutdown(); server.startHandshake(); SSLSession serverSession = server.getSession(); assertTrue(serverSession instanceof ExtendedSSLSession); ExtendedSSLSession extendedServerSession = (ExtendedSSLSession) serverSession; List<SNIServerName> requestedNames = extendedServerSession.getRequestedServerNames(); assertNotNull(requestedNames); assertEquals(1, requestedNames.size()); SNIServerName serverName = requestedNames.get(0); assertEquals(StandardConstants.SNI_HOST_NAME, serverName.getType()); assertTrue(serverName instanceof SNIHostName); SNIHostName serverHostName = (SNIHostName) serverName; assertEquals("www.example.com", serverHostName.getAsciiName()); }
Example 17
Source File: EasySSLConnectionSocketFactory.java From lorne_core with Apache License 2.0 | 5 votes |
@Override public Socket connectSocket(int connectTimeout, Socket sock, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException { SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket(context)); if (localAddress != null) { InetSocketAddress isa = new InetSocketAddress(localAddress.getAddress(), localAddress.getPort()); sslsock.bind(isa); } sslsock.connect(remoteAddress, connectTimeout); return sslsock; }
Example 18
Source File: SslCiphersTest.java From wildfly-openssl with Apache License 2.0 | 4 votes |
@Test public void testAvailableProtocols() throws Exception { final AtomicReference<byte[]> sessionID = new AtomicReference<>(); final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLSv1.2"); //we only test a subset of ciphers //TODO: figure out which ones we need to support, and what sort of cert we need for each String[] suites = new String[]{ //"TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_GCM_SHA256", //"TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_128_CBC_SHA", //"TLS_RSA_WITH_AES_256_CBC_SHA" }; for (String suite : suites) { final AtomicReference<SSLEngine> engineRef = new AtomicReference<>(); ServerSocket serverSocket = SSLTestUtils.createServerSocket(); EchoRunnable echo = new EchoRunnable(serverSocket, sslContext, sessionID, (engine -> { engineRef.set(engine); try { engine.setEnabledCipherSuites(new String[]{suite}); return engine; } catch (Exception e) { throw new RuntimeException(e); } })); Thread acceptThread = new Thread(echo); acceptThread.start(); final SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); socket.setEnabledCipherSuites(new String[]{suite}); socket.connect(SSLTestUtils.createSocketAddress()); socket.getOutputStream().write("hello world".getBytes(StandardCharsets.US_ASCII)); byte[] data = new byte[100]; int read = socket.getInputStream().read(data); Assert.assertEquals("hello world", new String(data, 0, read)); //make sure the names match String cipherSuite = socket.getSession().getCipherSuite(); SSLEngine sslEngine = engineRef.get(); SSLSession session = sslEngine.getSession(); // SSL is an alias for TLS, Windows and IBM J9 seem to use SSL for simplicity we'll just replace SSL with // TLS to match what we're expecting if(cipherSuite.startsWith("SSL")) { cipherSuite = cipherSuite.replace("SSL", "TLS"); } Assert.assertEquals(session.getCipherSuite(), cipherSuite); Assert.assertEquals(session.getCipherSuite(), suite); Assert.assertArrayEquals(socket.getSession().getId(), sessionID.get()); socket.getSession().invalidate(); socket.close(); echo.stop(); serverSocket.close(); acceptThread.join(); } }
Example 19
Source File: SSLSocketFactory.java From Popeens-DSub with GNU General Public License v3.0 | 4 votes |
/** * @since 4.1 */ public Socket connectSocket( final Socket sock, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } SSLSocket sslsock = (SSLSocket) (sock != null ? sock : createSocket()); if (localAddress != null) { // sslsock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sslsock.bind(localAddress); } setHostName(sslsock, remoteAddress.getHostName()); int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); try { sslsock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out"); } sslsock.setSoTimeout(soTimeout); if (this.hostnameVerifier != null) { try { this.hostnameVerifier.verify(remoteAddress.getHostName(), sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } } return sslsock; }
Example 20
Source File: SSLSocketTest.java From j2objc with Apache License 2.0 | 4 votes |
public void test_SSLSocket_setSoWriteTimeout() throws Exception { if (StandardNames.IS_RI) { // RI does not support write timeout on sockets return; } final TestSSLContext c = TestSSLContext.create(); SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(); // Try to make the client SO_SNDBUF size as small as possible // (it can default to 512k or even megabytes). Note that // socket(7) says that the kernel will double the request to // leave room for its own book keeping and that the minimal // value will be 2048. Also note that tcp(7) says the value // needs to be set before connect(2). int sendBufferSize = 1024; client.setSendBufferSize(sendBufferSize); sendBufferSize = client.getSendBufferSize(); // In jb-mr2 it was found that we need to also set SO_RCVBUF // to a minimal size or the write would not block. While // tcp(2) says the value has to be set before listen(2), it // seems fine to set it before accept(2). final int recvBufferSize = 128; c.serverSocket.setReceiveBufferSize(recvBufferSize); client.connect(new InetSocketAddress(c.host, c.port)); final SSLSocket server = (SSLSocket) c.serverSocket.accept(); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Void> future = executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { server.startHandshake(); return null; } }); executor.shutdown(); client.startHandshake(); // Reflection is used so this can compile on the RI String expectedClassName = "com.android.org.conscrypt.OpenSSLSocketImpl"; Class actualClass = client.getClass(); assertEquals(expectedClassName, actualClass.getName()); Method setSoWriteTimeout = actualClass.getMethod("setSoWriteTimeout", new Class[] { Integer.TYPE }); setSoWriteTimeout.invoke(client, 1); try { // Add extra space to the write to exceed the send buffer // size and cause the write to block. final int extra = 1; client.getOutputStream().write(new byte[sendBufferSize + extra]); fail(); } catch (SocketTimeoutException expected) { } future.get(); client.close(); server.close(); c.close(); }