package org.jboss.test.remoting.transport.multiplex.ssl.serversocketrefresh;

import org.jboss.jrunit.extensions.ServerTestCase;
import org.jboss.logging.Logger;
import org.jboss.remoting.InvocationRequest;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.ServerInvocationHandler;
import org.jboss.remoting.ServerInvoker;
import org.jboss.remoting.callback.InvokerCallbackHandler;
import org.jboss.remoting.security.SSLSocketBuilder;
import org.jboss.remoting.transport.Connector;
import org.jboss.remoting.transport.sslmultiplex.SSLMultiplexServerInvoker;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Michael Voss
 *
 */
public class TestServer extends ServerTestCase{
	
   private static Logger log = Logger.getLogger("TestServer.class");
	private String localHost="127.0.0.1";
	private String keyStorePath="src/tests/org/jboss/test/remoting/transport/multiplex/ssl/serversocketrefresh/certificate/serverKeyStore";
	private String trustStorePath="src/tests/org/jboss/test/remoting/transport/multiplex/ssl/serversocketrefresh/certificate/serverTrustStore";
	private String keyStorePassword="testpw";
	private String trustStorePassword="testpw";
	private String port="2001";
	private Connector connector;
	private MBeanServer server;
	private static boolean invocationDone=false;
	
	public void setUp(){	
		
		// starting connector
		try{
			//make it SSL-ready for sending callbacks (server acts as a client)
			Map configuration = new HashMap();
			/*configuration.put(RemotingSSLSocketFactory.REMOTING_KEY_STORE_TYPE, "JKS");
			configuration.put(RemotingSSLSocketFactory.REMOTING_KEY_STORE_FILE_PATH, keyStorePath);
			configuration.put(RemotingSSLSocketFactory.REMOTING_KEY_STORE_PASSWORD, keyStorePassword);
			configuration.put(RemotingSSLSocketFactory.REMOTING_ALGORITHM, "SunX509");
			
			configuration.put(RemotingSSLSocketFactory.REMOTING_TRUST_STORE_TYPE, "JKS");			
			configuration.put(RemotingSSLSocketFactory.REMOTING_TRUST_STORE_FILE_PATH, trustStorePath);
			configuration.put(RemotingSSLSocketFactory.REMOTING_TRUST_STORE_PASSWORD, trustStorePassword);
			configuration.put(RemotingSSLSocketFactory.REMOTING_TRUST_ALGORITHM, "SunX509");
						
		    configuration.put(RemotingSSLSocketFactory.REMOTING_USE_CLIENT_MODE, "false");
*/

         keyStorePath = this.getClass().getResource("certificate/serverKeyStore").getFile();
         trustStorePath = this.getClass().getResource("certificate/serverTrustStore").getFile();

         configuration.put(SSLSocketBuilder.REMOTING_KEY_STORE_TYPE, "JKS");
			configuration.put(SSLSocketBuilder.REMOTING_KEY_STORE_FILE_PATH, keyStorePath);
			configuration.put(SSLSocketBuilder.REMOTING_KEY_STORE_PASSWORD, keyStorePassword);
			configuration.put(SSLSocketBuilder.REMOTING_KEY_STORE_ALGORITHM, "SunX509");
			
			configuration.put(SSLSocketBuilder.REMOTING_TRUST_STORE_TYPE, "JKS");
			configuration.put(SSLSocketBuilder.REMOTING_TRUST_STORE_FILE_PATH, trustStorePath);
			configuration.put(SSLSocketBuilder.REMOTING_TRUST_STORE_PASSWORD, trustStorePassword);
			configuration.put(SSLSocketBuilder.REMOTING_TRUST_STORE_ALGORITHM, "SunX509");
		    connector = new Connector(configuration);
			
		    InvokerLocator locator = new InvokerLocator("sslmultiplex://"+localHost+":"+port);
			connector.setInvokerLocator(locator.getLocatorURI());
			connector.create();
			
			//make it SSL-ready for clients that want to build up connection:			
			try{
				// create server socket factory
				ServerSocketFactory svrSocketFactory = createServerSocketFactory(keyStorePassword,trustStorePassword,keyStorePath,trustStorePath);
				
				// notice that the invoker has to be explicitly cast to the
				// SSLMultiplexServerInvoker type								
				SSLMultiplexServerInvoker socketSvrInvoker = (SSLMultiplexServerInvoker) connector.getServerInvoker();
				socketSvrInvoker.setServerSocketFactory(svrSocketFactory);
			}
			catch(Exception e){
				e.printStackTrace();
			}			
			
			connector.start();
			server=MBeanServerFactory.createMBeanServer();
			server.registerMBean(connector,  new ObjectName("jboss.remoting:type=Connector"));
			connector.addInvocationHandler("Sample",new Sample());
			
		}
		catch(Exception e){			
			e.printStackTrace();
		}		
								    		    
	}
	public void tearDown() throws Exception
	   {
       log.info("tearDown() entered");
		Thread.sleep(10000);
		server.unregisterMBean( new ObjectName("jboss.remoting:type=Connector"));
		connector.removeInvocationHandler("Sample");
		connector.stop();
        log.info("tearDown() done");
	   }
	
	/**
	 * @throws Exception
	 */
	public void test() throws Exception{
		while(!invocationDone){
			Thread.sleep(1000);
		}
        log.info("invocationDone: " + invocationDone);
      String keyStorePath2 = this.getClass().getResource("certificate/serverTrustStore2").getFile();

      ((SSLMultiplexServerInvoker) connector.getServerInvoker()).setNewServerSocketFactory(createServerSocketFactory(keyStorePassword,
                                                                                                                     trustStorePassword,
                                                                                                                     keyStorePath,
                                                                                                                     keyStorePath2));
      log.info("reset ServerSocketFactory");
		Thread.sleep(10000);//let client build up connection a second time	
        log.info("test() done");
	}

   public static void main(String[] args)
   {
      try
      {
         TestServer server = new TestServer();
         server.setUp();
         server.test();
         Thread.currentThread().sleep(360000);
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
   }


   /**
	 * @author Michael Voss
	 *
	 */
	public static class Sample implements ServerInvocationHandler
	   {
	    
	      /**
	       * called by the remoting server to handle the invocation from client.
	       *
	       * @param invocation
	       * @return Object
	       * @throws Throwable
	       */
	      public Object invoke(InvocationRequest invocation) throws Throwable
	      {
	    	  invocationDone=true;
	    	  System.err.println("client invoked: "+invocation.getParameter());
	    	  System.err.println("answering: succeess");
	    	  return "success";
	      }

	      /**
	       * Adds a callback handler that will listen for callbacks from
	       * the server invoker handler.
	       *
	       * @param callbackHandler
	       */
	      public void addListener(InvokerCallbackHandler callbackHandler)
	      {
	         
	      }

	      /**
	       * Removes the callback handler that was listening for callbacks
	       * from the server invoker handler.
	       *
	       * @param callbackHandler
	       */
	      public void removeListener(InvokerCallbackHandler callbackHandler)
	      {
	         
	      }


	      /**
	       * set the mbean server that the handler can reference
	       *
	       * @param server
	       */
	      public void setMBeanServer(MBeanServer server)
	      {
	         // NO OP as do not need reference to MBeanServer for this handler
	      }

	      /**
	       * set the invoker that owns this handler
	       *
	       * @param invoker
	       */
	      public void setInvoker(ServerInvoker invoker)
	      {
	         // NO OP as do not need reference back to the server invoker
	      }
	   }
	
	/**
	 * returns a SSLServerSocketFactory that requires a client certificate to build up SSL connection
	 * @param keyStorePassword
	 * @param trustStorePassword
	 * @param keyStorePath
	 * @param trustStorePath
	 * @return SSLServerSocketFactory
	 * @throws Exception
	 */
	public static SSLServerSocketFactory createServerSocketFactory(String keyStorePassword, String trustStorePassword, String keyStorePath, String trustStorePath) throws Exception
	{				 
		return new ClientAuthSocketFactory(createNoAuthServerSocketFactory(keyStorePassword,trustStorePassword,keyStorePath,trustStorePath));
	}
	
	/**
	 * returns a SSLServerSocketFactory
	 * @param keyStorePassword
	 * @param trustStorePassword
	 * @param keyStorePath
	 * @param trustStorePath
	 * @return SSLServerSocketFactory
	 * @throws Exception
	 */
	public static SSLServerSocketFactory createNoAuthServerSocketFactory(String keyStorePassword, String trustStorePassword, String keyStorePath, String trustStorePath) throws Exception
	{		
		FileInputStream stream=null;
		try {
			// create an SSLContext
			SSLContext context = null;

			context = SSLContext.getInstance("TLS");

			// define password
			char[] keyPassphrase = keyStorePassword.toCharArray();
			char[] trustPassphrase = trustStorePassword.toCharArray();
			
			// load the server key store
			KeyStore server_keystore = KeyStore.getInstance("JKS");
			stream = new FileInputStream(keyStorePath);
			server_keystore.load(stream, keyPassphrase);
			stream.close();
			
			// load the server trust store
			KeyStore server_truststore = KeyStore.getInstance("JKS");
			stream = new FileInputStream(trustStorePath);
			server_truststore.load(stream, trustPassphrase);
			stream.close();
			
			// initialize a KeyManagerFactory with the KeyStore
			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			kmf.init(server_keystore, keyPassphrase);			
			// KeyManagers from the KeyManagerFactory
			KeyManager[] keyManagers = kmf.getKeyManagers();

			// initialize a TrustManagerFactory with the TrustStore
			TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
			tmf.init(server_truststore);
			// TrustManagers from the TrustManagerFactory
			TrustManager[] trustManagers = tmf.getTrustManagers();

			// initialize context with Keystore and Truststore information
			context.init(keyManagers, trustManagers, null);

			// get ServerSocketFactory from context
			return context.getServerSocketFactory();
			
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				stream.close();
			} catch (Exception ioe) {
			}
		}
	}
	
	/**
	 * overrides createServerSocket methods from class SSLServerSocketFactory<br>
	 * sets NeedClientAuth true, so server asks for a client certificate in the SSL handshake
	 * @author <a href="mailto:michael.voss@hp.com">Michael Voß</a>
	 *
	 */
	public static class ClientAuthSocketFactory extends SSLServerSocketFactory{
		SSLServerSocketFactory serverSocketFactory;

	    /**
	     * @param serverSocketFactory
	     */
	    public ClientAuthSocketFactory(SSLServerSocketFactory serverSocketFactory)
	    {
	       this.serverSocketFactory = serverSocketFactory;
	    }

	    public ServerSocket createServerSocket() throws IOException
	    {
	       SSLServerSocket ss = (SSLServerSocket) serverSocketFactory.createServerSocket();
	       ss.setNeedClientAuth(true);
	       return ss;
	    }

	    public ServerSocket createServerSocket(int arg0) throws IOException
	    {
	       SSLServerSocket ss = (SSLServerSocket) serverSocketFactory.createServerSocket(arg0);
	       ss.setNeedClientAuth(true);
	       return ss;
	    }

	    public ServerSocket createServerSocket(int arg0, int arg1) throws IOException
	    {
	       SSLServerSocket ss = (SSLServerSocket) serverSocketFactory.createServerSocket(arg0, arg1);
	       ss.setNeedClientAuth(true);
	       return ss;
	    }

	    public ServerSocket createServerSocket(int arg0, int arg1, InetAddress arg2) throws IOException
	    {
	       SSLServerSocket ss = (SSLServerSocket) serverSocketFactory.createServerSocket(arg0, arg1, arg2);
	       ss.setNeedClientAuth(true);
	       return ss;
	      
	    }

	    public boolean equals(Object obj)
	    {
	       return serverSocketFactory.equals(obj);
	    }

	    public String[] getDefaultCipherSuites()
	    {
	       return serverSocketFactory.getDefaultCipherSuites();
	    }

	    public String[] getSupportedCipherSuites()
	    {
	       return serverSocketFactory.getSupportedCipherSuites();
	    }

	    public int hashCode()
	    {
	       return serverSocketFactory.hashCode();
	    }

	    public String toString()
	    {
	       return serverSocketFactory.toString();
	    }
	}
}
