/***************************************
 *                                     *
 *  JBoss: The OpenSource J2EE WebOS   *
 *                                     *
 *  Distributable under LGPL license.  *
 *  See terms of license at gnu.org.   *
 *                                     *
 ***************************************/
 
package org.jboss.iiop.jacorb;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.ServerSocket;
import javax.net.ssl.SSLServerSocket;

import org.jacorb.util.Environment;

import org.jboss.iiop.CorbaORBService;
import org.jboss.logging.Logger;
import org.jboss.security.SecurityDomain;
import org.jboss.security.ssl.DomainServerSocketFactory;
import org.jboss.system.Registry;

/**
 * This implementation of the JacORB-specific interface 
 * <code>org.jacorb.orb.factory.SSLServerSocketFactory</code> uses the JSSE
 * KeyManagerFactory and TrustManagerFactory objects encapsulated by 
 * a JBossSX SecurityDomain. It looks up the 
 * <code>org.jboss.security.SecurityDomain</code> instance bound to the 
 * name <code>CorbaORBService.SSL_DOMAIN</code> in the JBoss registry.
 *
 * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a>
 * @version $Revision: 1.1.2.3 $
 */
public class SSLServerSocketFactory 
    implements org.jacorb.orb.factory.SSLServerSocketFactory
{
   // Static --------------------------------------------------------

   private static Logger log = Logger.getLogger(SSLServerSocketFactory.class);
   private static final Class[] ARG_TYPES_BOOLEAN = new Class[] {Boolean.TYPE};
   private static final Object[] ARGS_TRUE = new Object[] {Boolean.TRUE};

   // Attributes ----------------------------------------------------

   private DomainServerSocketFactory domainFactory = null;
   private boolean require_mutual_auth = false;
   private boolean request_mutual_auth = false;
   private Method setWantClientAuthMethod = null;

   // Constructor ---------------------------------------------------

   public SSLServerSocketFactory(org.jacorb.orb.ORB orb)
      throws IOException
   {
      log.info("Creating");

      SecurityDomain securityDomain = 
         (SecurityDomain)Registry.lookup(CorbaORBService.SSL_DOMAIN);

      try
      {
         domainFactory = new DomainServerSocketFactory(securityDomain);
      }
      catch (IOException e)
      {
         log.warn("Could not create DomainServerSocketFactory: " + e);
         if (log.isDebugEnabled())
            log.debug("Exception creating DomainServerSockedFactory: ", e);
         throw e;
      }
      if ((Environment.getIntProperty("jacorb.security.ssl.server.supported_options", 16) & 0x40) != 0)
      {
         // would prefer to establish trust in client.  If client can support
         // authentication, it will, otherwise we will continue
         request_mutual_auth = true;
      }

      if ((Environment.getIntProperty("jacorb.security.ssl.server.required_options", 16) & 0x40) != 0)
      {
         //required: establish trust in client
         //--> force other side to authenticate
         require_mutual_auth = true;
         request_mutual_auth = false;
      }
      if (request_mutual_auth)
      {
         try
         {
            setWantClientAuthMethod = 
               SSLServerSocket.class.getMethod("setWantClientAuth", 
                                               ARG_TYPES_BOOLEAN);

            log.info("Will create SSL sockets that support client authentication");
         }
         catch (NoSuchMethodException e)
         {
            request_mutual_auth = false;
            log.info("No method setWantClientAuth in class javax.net.ssl.SSLServerSocket");
         }
      }
      else if (require_mutual_auth)
         log.info("Will create SSL sockets that require client authentication");
      
      log.info("Created");
   }
           
   // Private -------------------------------------------------------

   /**
    * Auxiliary method that does s.setWantClientAuth(true) as a reflective
    * call. We need to use reflection here or this class won't compile on 
    * JDK 1.3, as the JSSE library for JDK 1.3 does not have the method 
    * setWantClientAuth(Boolean value) in javax.net.ssl.SSLServerSocket.
    */
   private void setWantClientAuth(SSLServerSocket s)
   {
      try
      {
         setWantClientAuthMethod.invoke(s, ARGS_TRUE);
      }
      catch (IllegalAccessException e)
      {
         log.warn("Unexpected exception: ", e);
      }
      catch (InvocationTargetException e)
      {
         log.warn("Unexpected exception: ", e);
      }
   }

   // JacORB SSLServerSocketFactory implementation ------------------
   // (interface org.jacorb.orb.factory.SSLServerSocketFactory)

   public ServerSocket createServerSocket(int port)
      throws IOException
   {
      SSLServerSocket s = 
         (SSLServerSocket)domainFactory.createServerSocket(port);

      if (request_mutual_auth) 
         setWantClientAuth(s); // s.setWantClientAuth(true);
      else if (require_mutual_auth) 
         s.setNeedClientAuth(true);

      return s;
   }
   
   public ServerSocket createServerSocket(int port, int backlog) 
      throws IOException
   {
      SSLServerSocket s = 
         (SSLServerSocket)domainFactory.createServerSocket(port, backlog);

      if (request_mutual_auth) 
         setWantClientAuth(s); // s.setWantClientAuth(true);
      else if (require_mutual_auth) 
         s.setNeedClientAuth(true);

      return s;
   }

   public ServerSocket createServerSocket(int port,
                                          int backlog,
                                          InetAddress ifAddress)
      throws IOException    
   {
      SSLServerSocket s = 
         (SSLServerSocket)domainFactory.createServerSocket(port, 
                                                           backlog, ifAddress);

      if (request_mutual_auth) 
         setWantClientAuth(s); // s.setWantClientAuth(true);
      else if (require_mutual_auth) 
         s.setNeedClientAuth(true);

      return s;
   }
   
   public boolean isSSL(java.net.ServerSocket s)
   { 
      return (s instanceof SSLServerSocket); 
   }
   
   public void switchToClientMode(java.net.Socket socket)
   {
      // no-op
   }

}
