Search in sources :

Example 66 with SocketAddress

use of java.net.SocketAddress in project Openfire by igniterealtime.

the class NIOConnection method getHostAddress.

@Override
public String getHostAddress() throws UnknownHostException {
    final SocketAddress remoteAddress = ioSession.getRemoteAddress();
    if (remoteAddress == null)
        throw new UnknownHostException();
    final InetSocketAddress socketAddress = (InetSocketAddress) remoteAddress;
    final InetAddress inetAddress = socketAddress.getAddress();
    return inetAddress.getHostAddress();
}
Also used : UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress)

Example 67 with SocketAddress

use of java.net.SocketAddress in project k-9 by k9mail.

the class ImapConnection method connectToAddress.

private Socket connectToAddress(InetAddress address) throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException {
    String host = settings.getHost();
    int port = settings.getPort();
    String clientCertificateAlias = settings.getClientCertificateAlias();
    if (K9MailLib.isDebug() && DEBUG_PROTOCOL_IMAP) {
        Log.d(LOG_TAG, "Connecting to " + host + " as " + address);
    }
    SocketAddress socketAddress = new InetSocketAddress(address, port);
    Socket socket;
    if (settings.getConnectionSecurity() == ConnectionSecurity.SSL_TLS_REQUIRED) {
        socket = socketFactory.createSocket(null, host, port, clientCertificateAlias);
    } else {
        socket = new Socket();
    }
    socket.connect(socketAddress, socketConnectTimeout);
    return socket;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Socket(java.net.Socket)

Example 68 with SocketAddress

use of java.net.SocketAddress in project k-9 by k9mail.

the class SmtpTransport method open.

@Override
public void open() throws MessagingException {
    try {
        boolean secureConnection = false;
        InetAddress[] addresses = InetAddress.getAllByName(mHost);
        for (int i = 0; i < addresses.length; i++) {
            try {
                SocketAddress socketAddress = new InetSocketAddress(addresses[i], mPort);
                if (mConnectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) {
                    mSocket = mTrustedSocketFactory.createSocket(null, mHost, mPort, mClientCertificateAlias);
                    mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
                    secureConnection = true;
                } else {
                    mSocket = new Socket();
                    mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
                }
            } catch (SocketException e) {
                if (i < (addresses.length - 1)) {
                    // there are still other addresses for that host to try
                    continue;
                }
                throw new MessagingException("Cannot connect to host", e);
            }
            // connection success
            break;
        }
        // RFC 1047
        mSocket.setSoTimeout(SOCKET_READ_TIMEOUT);
        mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024));
        mOut = new BufferedOutputStream(mSocket.getOutputStream(), 1024);
        // Eat the banner
        executeCommand(null);
        InetAddress localAddress = mSocket.getLocalAddress();
        String localHost = getCanonicalHostName(localAddress);
        String ipAddr = localAddress.getHostAddress();
        if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) {
            // characters (see issue 2143), so use IP address.
            if (!ipAddr.equals("")) {
                if (localAddress instanceof Inet6Address) {
                    localHost = "[IPv6:" + ipAddr + "]";
                } else {
                    localHost = "[" + ipAddr + "]";
                }
            } else {
                // If the IP address is no good, set a sane default (see issue 2750).
                localHost = "android";
            }
        }
        Map<String, String> extensions = sendHello(localHost);
        m8bitEncodingAllowed = extensions.containsKey("8BITMIME");
        mEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES");
        if (mConnectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) {
            if (extensions.containsKey("STARTTLS")) {
                executeCommand("STARTTLS");
                mSocket = mTrustedSocketFactory.createSocket(mSocket, mHost, mPort, mClientCertificateAlias);
                mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024));
                mOut = new BufferedOutputStream(mSocket.getOutputStream(), 1024);
                /*
                     * Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
                     * Exim.
                     */
                extensions = sendHello(localHost);
                secureConnection = true;
            } else {
                /*
                     * This exception triggers a "Certificate error"
                     * notification that takes the user to the incoming
                     * server settings for review. This might be needed if
                     * the account was configured with an obsolete
                     * "STARTTLS (if available)" setting.
                     */
                throw new CertificateValidationException("STARTTLS connection security not available");
            }
        }
        boolean authLoginSupported = false;
        boolean authPlainSupported = false;
        boolean authCramMD5Supported = false;
        boolean authExternalSupported = false;
        boolean authXoauth2Supported = false;
        if (extensions.containsKey("AUTH")) {
            List<String> saslMech = Arrays.asList(extensions.get("AUTH").split(" "));
            authLoginSupported = saslMech.contains("LOGIN");
            authPlainSupported = saslMech.contains("PLAIN");
            authCramMD5Supported = saslMech.contains("CRAM-MD5");
            authExternalSupported = saslMech.contains("EXTERNAL");
            authXoauth2Supported = saslMech.contains("XOAUTH2");
        }
        parseOptionalSizeValue(extensions);
        if (!TextUtils.isEmpty(mUsername) && (!TextUtils.isEmpty(mPassword) || AuthType.EXTERNAL == mAuthType || AuthType.XOAUTH2 == mAuthType)) {
            switch(mAuthType) {
                /*
                 * LOGIN is an obsolete option which is unavailable to users,
                 * but it still may exist in a user's settings from a previous
                 * version, or it may have been imported.
                 */
                case LOGIN:
                case PLAIN:
                    // try saslAuthPlain first, because it supports UTF-8 explicitly
                    if (authPlainSupported) {
                        saslAuthPlain(mUsername, mPassword);
                    } else if (authLoginSupported) {
                        saslAuthLogin(mUsername, mPassword);
                    } else {
                        throw new MessagingException("Authentication methods SASL PLAIN and LOGIN are unavailable.");
                    }
                    break;
                case CRAM_MD5:
                    if (authCramMD5Supported) {
                        saslAuthCramMD5(mUsername, mPassword);
                    } else {
                        throw new MessagingException("Authentication method CRAM-MD5 is unavailable.");
                    }
                    break;
                case XOAUTH2:
                    if (authXoauth2Supported && oauthTokenProvider != null) {
                        saslXoauth2(mUsername);
                    } else {
                        throw new MessagingException("Authentication method XOAUTH2 is unavailable.");
                    }
                    break;
                case EXTERNAL:
                    if (authExternalSupported) {
                        saslAuthExternal(mUsername);
                    } else {
                        /*
                         * Some SMTP servers are known to provide no error
                         * indication when a client certificate fails to
                         * validate, other than to not offer the AUTH EXTERNAL
                         * capability.
                         *
                         * So, we treat it is an error to not offer AUTH
                         * EXTERNAL when using client certificates. That way, the
                         * user can be notified of a problem during account setup.
                         */
                        throw new CertificateValidationException(MissingCapability);
                    }
                    break;
                /*
                 * AUTOMATIC is an obsolete option which is unavailable to users,
                 * but it still may exist in a user's settings from a previous
                 * version, or it may have been imported.
                 */
                case AUTOMATIC:
                    if (secureConnection) {
                        // try saslAuthPlain first, because it supports UTF-8 explicitly
                        if (authPlainSupported) {
                            saslAuthPlain(mUsername, mPassword);
                        } else if (authLoginSupported) {
                            saslAuthLogin(mUsername, mPassword);
                        } else if (authCramMD5Supported) {
                            saslAuthCramMD5(mUsername, mPassword);
                        } else {
                            throw new MessagingException("No supported authentication methods available.");
                        }
                    } else {
                        if (authCramMD5Supported) {
                            saslAuthCramMD5(mUsername, mPassword);
                        } else {
                            /*
                             * We refuse to insecurely transmit the password
                             * using the obsolete AUTOMATIC setting because of
                             * the potential for a MITM attack. Affected users
                             * must choose a different setting.
                             */
                            throw new MessagingException("Update your outgoing server authentication setting. AUTOMATIC auth. is unavailable.");
                        }
                    }
                    break;
                default:
                    throw new MessagingException("Unhandled authentication method found in the server settings (bug).");
            }
        }
    } catch (MessagingException e) {
        close();
        throw e;
    } catch (SSLException e) {
        close();
        throw new CertificateValidationException(e.getMessage(), e);
    } catch (GeneralSecurityException gse) {
        close();
        throw new MessagingException("Unable to open connection to SMTP server due to security error.", gse);
    } catch (IOException ioe) {
        close();
        throw new MessagingException("Unable to open connection to SMTP server.", ioe);
    }
}
Also used : SocketException(java.net.SocketException) MessagingException(com.fsck.k9.mail.MessagingException) InetSocketAddress(java.net.InetSocketAddress) GeneralSecurityException(java.security.GeneralSecurityException) PeekableInputStream(com.fsck.k9.mail.filter.PeekableInputStream) Inet6Address(java.net.Inet6Address) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) BufferedInputStream(java.io.BufferedInputStream) CertificateValidationException(com.fsck.k9.mail.CertificateValidationException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) BufferedOutputStream(java.io.BufferedOutputStream) Socket(java.net.Socket)

Example 69 with SocketAddress

use of java.net.SocketAddress in project flink by apache.

the class PartitionRequestClientHandler method decodeMsg.

private boolean decodeMsg(Object msg, boolean isStagedBuffer) throws Throwable {
    final Class<?> msgClazz = msg.getClass();
    // ---- Buffer --------------------------------------------------------
    if (msgClazz == NettyMessage.BufferResponse.class) {
        NettyMessage.BufferResponse bufferOrEvent = (NettyMessage.BufferResponse) msg;
        RemoteInputChannel inputChannel = inputChannels.get(bufferOrEvent.receiverId);
        if (inputChannel == null) {
            bufferOrEvent.releaseBuffer();
            cancelRequestFor(bufferOrEvent.receiverId);
            return true;
        }
        return decodeBufferOrEvent(inputChannel, bufferOrEvent, isStagedBuffer);
    } else // ---- Error ---------------------------------------------------------
    if (msgClazz == NettyMessage.ErrorResponse.class) {
        NettyMessage.ErrorResponse error = (NettyMessage.ErrorResponse) msg;
        SocketAddress remoteAddr = ctx.channel().remoteAddress();
        if (error.isFatalError()) {
            notifyAllChannelsOfErrorAndClose(new RemoteTransportException("Fatal error at remote task manager '" + remoteAddr + "'.", remoteAddr, error.cause));
        } else {
            RemoteInputChannel inputChannel = inputChannels.get(error.receiverId);
            if (inputChannel != null) {
                if (error.cause.getClass() == PartitionNotFoundException.class) {
                    inputChannel.onFailedPartitionRequest();
                } else {
                    inputChannel.onError(new RemoteTransportException("Error at remote task manager '" + remoteAddr + "'.", remoteAddr, error.cause));
                }
            }
        }
    } else {
        throw new IllegalStateException("Received unknown message from producer: " + msg.getClass());
    }
    return true;
}
Also used : RemoteTransportException(org.apache.flink.runtime.io.network.netty.exception.RemoteTransportException) PartitionNotFoundException(org.apache.flink.runtime.io.network.partition.PartitionNotFoundException) SocketAddress(java.net.SocketAddress) RemoteInputChannel(org.apache.flink.runtime.io.network.partition.consumer.RemoteInputChannel)

Example 70 with SocketAddress

use of java.net.SocketAddress in project flink by apache.

the class PartitionRequestClientHandler method exceptionCaught.

/**
	 * Called on exceptions in the client handler pipeline.
	 *
	 * <p> Remote exceptions are received as regular payload.
	 */
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (cause instanceof TransportException) {
        notifyAllChannelsOfErrorAndClose(cause);
    } else {
        final SocketAddress remoteAddr = ctx.channel().remoteAddress();
        final TransportException tex;
        // Improve on the connection reset by peer error message
        if (cause instanceof IOException && cause.getMessage().equals("Connection reset by peer")) {
            tex = new RemoteTransportException("Lost connection to task manager '" + remoteAddr + "'. This indicates " + "that the remote task manager was lost.", remoteAddr, cause);
        } else {
            tex = new LocalTransportException(cause.getMessage(), ctx.channel().localAddress(), cause);
        }
        notifyAllChannelsOfErrorAndClose(tex);
    }
}
Also used : RemoteTransportException(org.apache.flink.runtime.io.network.netty.exception.RemoteTransportException) LocalTransportException(org.apache.flink.runtime.io.network.netty.exception.LocalTransportException) IOException(java.io.IOException) SocketAddress(java.net.SocketAddress) TransportException(org.apache.flink.runtime.io.network.netty.exception.TransportException) LocalTransportException(org.apache.flink.runtime.io.network.netty.exception.LocalTransportException) RemoteTransportException(org.apache.flink.runtime.io.network.netty.exception.RemoteTransportException)

Aggregations

SocketAddress (java.net.SocketAddress)355 InetSocketAddress (java.net.InetSocketAddress)279 IOException (java.io.IOException)79 Test (org.junit.Test)73 Socket (java.net.Socket)48 InetAddress (java.net.InetAddress)35 Channel (org.jboss.netty.channel.Channel)33 SocketException (java.net.SocketException)27 UnknownHostException (java.net.UnknownHostException)25 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)23 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)23 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)20 ConditionCheck (com.linkedin.databus2.test.ConditionCheck)19 SimpleObjectCaptureHandler (com.linkedin.databus2.test.container.SimpleObjectCaptureHandler)19 Proxy (java.net.Proxy)18 HashMap (java.util.HashMap)17 DatagramPacket (java.net.DatagramPacket)16 ByteBuffer (java.nio.ByteBuffer)16 Logger (org.apache.log4j.Logger)16 Test (org.testng.annotations.Test)16