/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2011, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.as.remoting;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;

import javax.net.ssl.SSLContext;
import javax.security.auth.callback.CallbackHandler;

import org.jboss.as.domain.management.CallbackHandlerFactory;
import org.jboss.as.domain.management.SecurityRealm;
import org.jboss.as.network.NetworkUtils;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
import org.jboss.remoting3.Connection;
import org.jboss.remoting3.Endpoint;
import org.xnio.IoFuture;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Sequence;

import static org.jboss.as.remoting.RemotingMessages.MESSAGES;
import static org.xnio.Options.SASL_POLICY_NOANONYMOUS;
import static org.xnio.Options.SASL_POLICY_NOPLAINTEXT;

/**
 * A {@link RemoteOutboundConnectionService} manages a remoting connection created out of a remote:// URI scheme.
 *
 * @author Jaikiran Pai
 */
public class RemoteOutboundConnectionService extends AbstractOutboundConnectionService<RemoteOutboundConnectionService> {

    public static final ServiceName REMOTE_OUTBOUND_CONNECTION_BASE_SERVICE_NAME = RemotingServices.SUBSYSTEM_ENDPOINT.append("remote-outbound-connection");

    private static final String JBOSS_LOCAL_USER = "JBOSS-LOCAL-USER";

    private final InjectedValue<OutboundSocketBinding> destinationOutboundSocketBindingInjectedValue = new InjectedValue<OutboundSocketBinding>();
    private final InjectedValue<SecurityRealm> securityRealmInjectedValue = new InjectedValue<SecurityRealm>();

    private final String username;
    private final String protocol;
    private URI connectionURI;

    public RemoteOutboundConnectionService(final String connectionName, final OptionMap connectionCreationOptions, final String username, final String protocol) {
        super(connectionName, connectionCreationOptions);
        this.username = username;
        this.protocol = protocol;
    }

    @Override
    public IoFuture<Connection> connect() throws IOException {
        final URI uri;
        try {
            // we lazily generate the URI on first request to connect() instead of on start() of the service
            // in order to delay resolving the destination address. No point trying to resolve that address
            // if nothing really wants to create a connection out of it.
            uri = this.getConnectionURI();
        } catch (URISyntaxException e) {
            throw MESSAGES.couldNotConnect(e);
        }
        final Endpoint endpoint = this.endpointInjectedValue.getValue();

        final CallbackHandler callbackHandler;
        final CallbackHandlerFactory cbhFactory;
        SSLContext sslContext = null;
        SecurityRealm realm = securityRealmInjectedValue.getOptionalValue();
        if (realm != null && (cbhFactory = realm.getSecretCallbackHandlerFactory()) != null && username != null) {
            callbackHandler = cbhFactory.getCallbackHandler(username);
        } else {
            callbackHandler = getCallbackHandler();
        }

        if (realm != null) {
            sslContext = realm.getSSLContext();
        }

        final OptionMap.Builder builder = OptionMap.builder();
        // first set the defaults
        builder.set(SASL_POLICY_NOANONYMOUS, Boolean.FALSE);
        builder.set(SASL_POLICY_NOPLAINTEXT, Boolean.FALSE);
        builder.set(Options.SASL_DISALLOWED_MECHANISMS, Sequence.of(JBOSS_LOCAL_USER));
        builder.set(Options.SSL_ENABLED, true);
        builder.set(Options.SSL_STARTTLS, true);
        // now override with user specified options
        builder.addAll(this.connectionCreationOptions);


        return endpoint.connect(uri, builder.getMap(), callbackHandler, sslContext);
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    Injector<OutboundSocketBinding> getDestinationOutboundSocketBindingInjector() {
        return this.destinationOutboundSocketBindingInjectedValue;
    }

    Injector<SecurityRealm> getSecurityRealmInjector() {
        return securityRealmInjectedValue;
    }

    /**
     * Generates and returns the URI that corresponds to the remote outbound connection.
     * If the URI has already been generated in a previous request, then it returns that back.
     * Else the URI is constructed out of the outbound socket binding's destination address and destination port.
     *
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    private synchronized URI getConnectionURI() throws IOException, URISyntaxException {
        if (this.connectionURI != null) {
            return this.connectionURI;
        }
        final OutboundSocketBinding destinationOutboundSocket = this.destinationOutboundSocketBindingInjectedValue.getValue();
        final InetAddress destinationAddress = destinationOutboundSocket.getDestinationAddress();
        final int port = destinationOutboundSocket.getDestinationPort();

        this.connectionURI = new URI(protocol +"://" + NetworkUtils.formatPossibleIpv6Address( destinationAddress.getHostAddress()) + ":" + port);
        return this.connectionURI;
    }

    @Override
    public RemoteOutboundConnectionService getValue() throws IllegalStateException, IllegalArgumentException {
        return this;
    }
}

@@ -1860,87 +1860,9 @@
 ons.
-SASL_POLICY_NOANONYMOUS;%0Aimport static org.xnio.Options.SASL_POLICY_NOPLAINTEXT
+*
 ;%0A%0A/
@@ -2360,16 +2360,148 @@
 L-USER%22;
+%0A    private static final String HTTP_REMOTING = %22http-remoting%22;%0A    private static final String HTTPS_REMOTING = %22https-remoting%22;
 %0A%0A    pr
@@ -4643,16 +4643,287 @@
 USER));%0A
+%0A        if (uri.getScheme().equals(HTTP_REMOTING)) %7B%0A            builder.set(SSL_ENABLED, false);%0A        %7D else if (uri.getScheme().equals(HTTPS_REMOTING)) %7B%0A            builder.set(SSL_ENABLED, true);%0A            builder.set(SSL_STARTTLS, false);%0A        %7D else %7B%0A    
         
@@ -4954,32 +4954,36 @@
 ENABLED, true);%0A
+    
         builder.
@@ -5007,32 +5007,43 @@
 TARTTLS, true);%0A
+        %7D%0A%0A
         // now o
@@ -5135,17 +5135,16 @@
 ions);%0A%0A
-%0A
         
@@ -6495,16 +6495,17 @@
 otocol +
+ 
 %22://%22 + 
@@ -6543,17 +6543,16 @@
 Address(
- 
 destinat

Fix some issues with remote outbound connections