Search in sources :

Example 6 with HandshakeCompletedListener

use of javax.net.ssl.HandshakeCompletedListener in project XobotOS by xamarin.

the class IOHandler method sendBytes.

/**
     * Send an array of bytes.
     * 
     * @param receiverAddress -- inet address
     * @param contactPort -- port to connect to.
     * @param transport -- tcp or udp.
     * @param retry -- retry to connect if the other end closed connection
     * @throws IOException -- if there is an IO exception sending message.
     */
public Socket sendBytes(InetAddress senderAddress, InetAddress receiverAddress, int contactPort, String transport, byte[] bytes, boolean retry, MessageChannel messageChannel) throws IOException {
    int retry_count = 0;
    int max_retry = retry ? 2 : 1;
    // Server uses TCP transport. TCP client sockets are cached
    int length = bytes.length;
    if (sipStack.isLoggingEnabled()) {
        sipStack.getStackLogger().logDebug("sendBytes " + transport + " inAddr " + receiverAddress.getHostAddress() + " port = " + contactPort + " length = " + length);
    }
    if (sipStack.isLoggingEnabled() && sipStack.isLogStackTraceOnMessageSend()) {
        sipStack.getStackLogger().logStackTrace(StackLogger.TRACE_INFO);
    }
    if (transport.compareToIgnoreCase(TCP) == 0) {
        String key = makeKey(receiverAddress, contactPort);
        try {
            boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS);
            if (!retval) {
                throw new IOException("Could not acquire IO Semaphore after 10 seconds -- giving up ");
            }
        } catch (InterruptedException ex) {
            throw new IOException("exception in acquiring sem");
        }
        Socket clientSock = getSocket(key);
        try {
            while (retry_count < max_retry) {
                if (clientSock == null) {
                    if (sipStack.isLoggingEnabled()) {
                        sipStack.getStackLogger().logDebug("inaddr = " + receiverAddress);
                        sipStack.getStackLogger().logDebug("port = " + contactPort);
                    }
                    // note that the IP Address for stack may not be
                    // assigned.
                    // sender address is the address of the listening point.
                    // in version 1.1 all listening points have the same IP
                    // address (i.e. that of the stack). In version 1.2
                    // the IP address is on a per listening point basis.
                    clientSock = sipStack.getNetworkLayer().createSocket(receiverAddress, contactPort, senderAddress);
                    OutputStream outputStream = clientSock.getOutputStream();
                    writeChunks(outputStream, bytes, length);
                    putSocket(key, clientSock);
                    break;
                } else {
                    try {
                        OutputStream outputStream = clientSock.getOutputStream();
                        writeChunks(outputStream, bytes, length);
                        break;
                    } catch (IOException ex) {
                        if (sipStack.isLoggingEnabled())
                            sipStack.getStackLogger().logDebug("IOException occured retryCount " + retry_count);
                        // old connection is bad.
                        // remove from our table.
                        removeSocket(key);
                        try {
                            clientSock.close();
                        } catch (Exception e) {
                        }
                        clientSock = null;
                        retry_count++;
                    }
                }
            }
        } finally {
            ioSemaphore.release();
        }
        if (clientSock == null) {
            if (sipStack.isLoggingEnabled()) {
                sipStack.getStackLogger().logDebug(this.socketTable.toString());
                sipStack.getStackLogger().logError("Could not connect to " + receiverAddress + ":" + contactPort);
            }
            throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort);
        } else
            return clientSock;
    // Added by Daniel J. Martinez Manzano <dani@dif.um.es>
    // Copied and modified from the former section for TCP
    } else if (transport.compareToIgnoreCase(TLS) == 0) {
        String key = makeKey(receiverAddress, contactPort);
        try {
            boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS);
            if (!retval)
                throw new IOException("Timeout acquiring IO SEM");
        } catch (InterruptedException ex) {
            throw new IOException("exception in acquiring sem");
        }
        Socket clientSock = getSocket(key);
        try {
            while (retry_count < max_retry) {
                if (clientSock == null) {
                    if (sipStack.isLoggingEnabled()) {
                        sipStack.getStackLogger().logDebug("inaddr = " + receiverAddress);
                        sipStack.getStackLogger().logDebug("port = " + contactPort);
                    }
                    clientSock = sipStack.getNetworkLayer().createSSLSocket(receiverAddress, contactPort, senderAddress);
                    SSLSocket sslsock = (SSLSocket) clientSock;
                    HandshakeCompletedListener listner = new HandshakeCompletedListenerImpl((TLSMessageChannel) messageChannel);
                    ((TLSMessageChannel) messageChannel).setHandshakeCompletedListener(listner);
                    sslsock.addHandshakeCompletedListener(listner);
                    sslsock.setEnabledProtocols(sipStack.getEnabledProtocols());
                    sslsock.startHandshake();
                    OutputStream outputStream = clientSock.getOutputStream();
                    writeChunks(outputStream, bytes, length);
                    putSocket(key, clientSock);
                    break;
                } else {
                    try {
                        OutputStream outputStream = clientSock.getOutputStream();
                        writeChunks(outputStream, bytes, length);
                        break;
                    } catch (IOException ex) {
                        if (sipStack.isLoggingEnabled())
                            sipStack.getStackLogger().logException(ex);
                        // old connection is bad.
                        // remove from our table.
                        removeSocket(key);
                        try {
                            clientSock.close();
                        } catch (Exception e) {
                        }
                        clientSock = null;
                        retry_count++;
                    }
                }
            }
        } finally {
            ioSemaphore.release();
        }
        if (clientSock == null) {
            throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort);
        } else
            return clientSock;
    } else {
        // This is a UDP transport...
        DatagramSocket datagramSock = sipStack.getNetworkLayer().createDatagramSocket();
        datagramSock.connect(receiverAddress, contactPort);
        DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length, receiverAddress, contactPort);
        datagramSock.send(dgPacket);
        datagramSock.close();
        return null;
    }
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) SSLSocket(javax.net.ssl.SSLSocket)

Example 7 with HandshakeCompletedListener

use of javax.net.ssl.HandshakeCompletedListener in project robovm by robovm.

the class SSLSocketTest method test_SSLSocket_HandshakeCompletedListener_RuntimeException.

public void test_SSLSocket_HandshakeCompletedListener_RuntimeException() throws Exception {
    final Thread self = Thread.currentThread();
    final UncaughtExceptionHandler original = self.getUncaughtExceptionHandler();
    final RuntimeException expectedException = new RuntimeException("expected");
    final TestUncaughtExceptionHandler test = new TestUncaughtExceptionHandler();
    self.setUncaughtExceptionHandler(test);
    final TestSSLContext c = TestSSLContext.create();
    final SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(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.addHandshakeCompletedListener(new HandshakeCompletedListener() {

        public void handshakeCompleted(HandshakeCompletedEvent event) {
            throw expectedException;
        }
    });
    client.startHandshake();
    future.get();
    client.close();
    server.close();
    c.close();
    assertSame(expectedException, test.actualException);
    self.setUncaughtExceptionHandler(original);
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) ExecutorService(java.util.concurrent.ExecutorService) UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)

Example 8 with HandshakeCompletedListener

use of javax.net.ssl.HandshakeCompletedListener in project robovm by robovm.

the class SSLSocketTest method test_removeHandshakeCompletedListener.

/**
     * javax.net.ssl.SSLSocket#removeHandshakeCompletedListener(HandshakeCompletedListener listener)
     */
public void test_removeHandshakeCompletedListener() throws IOException {
    SSLSocket ssl = getSSLSocket();
    HandshakeCompletedListener ls = new HandshakeCL();
    try {
        ssl.removeHandshakeCompletedListener(null);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
        ssl.removeHandshakeCompletedListener(ls);
    } catch (IllegalArgumentException expected) {
    }
    ssl.addHandshakeCompletedListener(ls);
    ssl.removeHandshakeCompletedListener(ls);
    ssl.close();
}
Also used : HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) SSLSocket(javax.net.ssl.SSLSocket)

Example 9 with HandshakeCompletedListener

use of javax.net.ssl.HandshakeCompletedListener in project kdeconnect-android by KDE.

the class LanLinkProvider method identityPackageReceived.

private void identityPackageReceived(final NetworkPackage identityPackage, final Socket socket, final LanLink.ConnectionStarted connectionStarted) {
    String myId = DeviceHelper.getDeviceId(context);
    final String deviceId = identityPackage.getString("deviceId");
    if (deviceId.equals(myId)) {
        Log.e("KDE/LanLinkProvider", "Somehow I'm connected to myself, ignoring. This should not happen.");
        return;
    }
    // If I'm the TCP server I will be the SSL client and viceversa.
    final boolean clientMode = (connectionStarted == LanLink.ConnectionStarted.Locally);
    // Add ssl handler if device uses new protocol
    try {
        if (identityPackage.getInt("protocolVersion") >= MIN_VERSION_WITH_SSL_SUPPORT) {
            SharedPreferences preferences = context.getSharedPreferences("trusted_devices", Context.MODE_PRIVATE);
            boolean isDeviceTrusted = preferences.getBoolean(deviceId, false);
            if (isDeviceTrusted && !SslHelper.isCertificateStored(context, deviceId)) {
                //Device paired with and old version, we can't use it as we lack the certificate
                BackgroundService.RunCommand(context, new BackgroundService.InstanceCallback() {

                    @Override
                    public void onServiceStart(BackgroundService service) {
                        Device device = service.getDevice(deviceId);
                        if (device == null)
                            return;
                        device.unpair();
                        //Retry as unpaired
                        identityPackageReceived(identityPackage, socket, connectionStarted);
                    }
                });
            }
            Log.i("KDE/LanLinkProvider", "Starting SSL handshake with " + identityPackage.getString("deviceName") + " trusted:" + isDeviceTrusted);
            final SSLSocket sslsocket = SslHelper.convertToSslSocket(context, socket, deviceId, isDeviceTrusted, clientMode);
            sslsocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {

                @Override
                public void handshakeCompleted(HandshakeCompletedEvent event) {
                    String mode = clientMode ? "client" : "server";
                    try {
                        Certificate certificate = event.getPeerCertificates()[0];
                        identityPackage.set("certificate", Base64.encodeToString(certificate.getEncoded(), 0));
                        Log.i("KDE/LanLinkProvider", "Handshake as " + mode + " successful with " + identityPackage.getString("deviceName") + " secured with " + event.getCipherSuite());
                        addLink(identityPackage, sslsocket, connectionStarted);
                    } catch (Exception e) {
                        Log.e("KDE/LanLinkProvider", "Handshake as " + mode + " failed with " + identityPackage.getString("deviceName"));
                        e.printStackTrace();
                        BackgroundService.RunCommand(context, new BackgroundService.InstanceCallback() {

                            @Override
                            public void onServiceStart(BackgroundService service) {
                                Device device = service.getDevice(deviceId);
                                if (device == null)
                                    return;
                                device.unpair();
                            }
                        });
                    }
                }
            });
            //Handshake is blocking, so do it on another thread and free this thread to keep receiving new connection
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        sslsocket.startHandshake();
                    } catch (Exception e) {
                        Log.e("KDE/LanLinkProvider", "Handshake failed with " + identityPackage.getString("deviceName"));
                        e.printStackTrace();
                    //String[] ciphers = sslsocket.getSupportedCipherSuites();
                    //for (String cipher : ciphers) {
                    //    Log.i("SupportedCiphers","cipher: " + cipher);
                    //}
                    }
                }
            }).start();
        } else {
            addLink(identityPackage, socket, connectionStarted);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : BackgroundService(org.kde.kdeconnect.BackgroundService) SharedPreferences(android.content.SharedPreferences) Device(org.kde.kdeconnect.Device) SSLSocket(javax.net.ssl.SSLSocket) SocketException(java.net.SocketException) IOException(java.io.IOException) HandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener) HandshakeCompletedEvent(javax.net.ssl.HandshakeCompletedEvent) Certificate(java.security.cert.Certificate)

Aggregations

HandshakeCompletedListener (javax.net.ssl.HandshakeCompletedListener)9 SSLSocket (javax.net.ssl.SSLSocket)8 HandshakeCompletedEvent (javax.net.ssl.HandshakeCompletedEvent)6 IOException (java.io.IOException)4 SocketException (java.net.SocketException)4 SocketTimeoutException (java.net.SocketTimeoutException)2 CertificateException (java.security.cert.CertificateException)2 ExecutorService (java.util.concurrent.ExecutorService)2 SSLException (javax.net.ssl.SSLException)2 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)2 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)2 SSLProtocolException (javax.net.ssl.SSLProtocolException)2 SSLServerSocket (javax.net.ssl.SSLServerSocket)2 SharedPreferences (android.content.SharedPreferences)1 AndroidOnly (dalvik.annotation.AndroidOnly)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 UncaughtExceptionHandler (java.lang.Thread.UncaughtExceptionHandler)1 InetAddress (java.net.InetAddress)1 InetSocketAddress (java.net.InetSocketAddress)1