/**
 * Copyright (c) 2000/2001 Thomas Kopp
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
package org.w3c.jigsaw.https;

import java.net.*;
import java.security.*;

import javax.net.ssl.*;
import javax.security.cert.*;

import org.w3c.util.*;
import org.w3c.jigsaw.daemon.*;
import org.w3c.jigsaw.http.*;

import org.w3c.tools.resources.*;
import org.w3c.tools.resources.ProtocolException;

/**
 * @author Thomas Kopp, Dialogika GmbH
 * @version 1.0.2, 8 April 2001
 * 
 * This class supplies a Jigsaw SSL daemon adapter
 * for enabling Jigsaw https support in accordance with the JSSE API
 * wrapping SSL features in order to solve multiple inheritance problems
 */
public class SSLAdapter {
    
    /**
     * flag for enabling debug output if applicable
     */
    private static boolean debug = false;

    /**
     * version string of the adapter class
     */
    public static final String version = "1.0.2";

    /**
     * property key for enabling TLS support
     */
    public static final String SSL_ENABLED_P = "org.w3c.jigsaw.ssl.enabled";

    /**
     * property key for specifying the TLS protocol handler
     */
    public static final String PROTOCOL_HANDLER_P = "org.w3c.jigsaw.ssl.protocol.handler";
    
    /**
     * property key for specifying the TLS security provider
     */
    public static final String SECURITY_PROVIDER_P = SSLProperties.SECURITY_PROVIDER_P;

    /**
     * property key for specifying the keystore path
     */
    public static final String KEYSTORE_PATH_P = SSLProperties.KEYSTORE_PATH_P;

    /**
     * property key for specifying the keystore password
     */
    public static final String KEYSTORE_PASSWORD_P = SSLProperties.KEYSTORE_PASSWORD_P;

    /**
     * property key for specifying the truststore path (future use for client mode)
     */
    public static final String TRUSTSTORE_PATH_P = SSLProperties.TRUSTSTORE_PATH_P;

    /**
     * property key for specifying the truststore password (future use for client mode)
     */
    public static final String TRUSTSTORE_PASSWORD_P = SSLProperties.TRUSTSTORE_PASSWORD_P;

    /**
     * property key for the system protocol package lookup
     */
    public static final String PROTOCOL_HANDLER_S = "java.protocol.handler.pkgs";

    /**
     * property key for the system keystore path
     */
    public static final String KEYSTORE_PATH_S = "javax.net.ssl.keyStore";

    /**
     * property key for the system keystore password
     */
    public static final String KEYSTORE_PASSWORD_S = "javax.net.ssl.keyStorePassword";

    /**
     * property key for the system truststore path (future usage for client mode)
     */
    public static final String TRUSTSTORE_PATH_S = "javax.net.ssl.trustStore";

    /**
     * property key for the system keystore password (future usage for client mode)
     */
    public static final String TRUSTSTORE_PASSWORD_S = "javax.net.ssl.trustStorePassword";

    /**
     * default security provider for TLS support
     */
    public static final String SECURITY_PROVIDER_D = "com.sun.net.ssl.internal.ssl.Provider";

    /**
     * default TLS protocol handler (should always be set to default)
     */
    public static final String PROTOCOL_HANDLER_D = "com.sun.net.ssl.internal.www.protocol";
    
    /**
     * flag indicating TLS support
     */
    private boolean ssl_enabled = false;
    
    /**
     * reference to the daemon in question
     */
    private httpd daemon = null;
    
    /**
     * uri of the daemon in question
     */
    protected URL url = null;

    /**
     * constructor for a TLS support adapter
     * @param server reference to the daemon in question
     */
    public SSLAdapter(httpd server) {
        if (null != server) {
           ssl_enabled = false;
           daemon = server;
           url = null;
        }
        else throw new NullPointerException("No daemon intance supplied for creating SSL adapter.");
    }
    
    /**
     * method for registering TLS property management
     */
    public void initializePropertySets() {
        if (ssl_enabled) {
  	   daemon.registerPropertySet(new SSLProperties(daemon)); 
        }
    } 
    
    /**
     * method for initializing the properties of a daemon
     * @exception ServerHandlerInitException thrown if initialization fails
     */
    public void initializeProperties() 
        throws ServerHandlerInitException {
        ObservableProperties props = daemon.getProperties();
        ssl_enabled = props.getBoolean(SSL_ENABLED_P, false);
	if (ssl_enabled) {
            
           // enabling the TLS security provider
	   String supplier = props.getString(SECURITY_PROVIDER_P, SECURITY_PROVIDER_D); 
           try {
 	         Class support = Class.forName(supplier);
		 Provider provider = (Provider)support.newInstance();
		 Security.addProvider(provider);
		 if (debug) System.out.println("Provider " + provider.toString() + " added.");

                 // enabling ths TLS stream handler
	         String protocol = props.getString(PROTOCOL_HANDLER_P, PROTOCOL_HANDLER_D); 
                 if (null != protocol) {
                    System.setProperty(PROTOCOL_HANDLER_S, protocol);
		    if (debug) System.out.println("Protocol " + protocol + " added.");
                 }

                 // enabling some TLS custom attributes
	         String keystore = props.getString(KEYSTORE_PATH_P, null); 
                 if (null != keystore) {
                    System.setProperty(KEYSTORE_PATH_S, keystore);
                    
                    String keypass = props.getString(KEYSTORE_PASSWORD_P, null); 
                    if (null != keypass) System.setProperty(KEYSTORE_PASSWORD_S, keypass);
                 }

                 String truststore = props.getString(TRUSTSTORE_PATH_P, null); 
                 if (null != truststore) { 
                    System.setProperty(TRUSTSTORE_PATH_S, truststore);

                    String trustpass = props.getString(TRUSTSTORE_PASSWORD_P, null); 
                    if (null != trustpass) System.setProperty(TRUSTSTORE_PASSWORD_S, trustpass);
                 }
	    }
            catch (Exception ex) {
                  String error = "Unable to set security provider. (" + ex.getMessage() + ")";
                  if (debug) ex.printStackTrace();
                  throw new ServerHandlerInitException(error);
	    }
	}
    }

    /**
     * method for handling a dynamic property modification of a daemon
     * @param name name of the property modified
     * @return true if and only if the modification has been successfully handled
     */
    public boolean propertyChanged(String name) {
        ObservableProperties props = daemon.getProperties();
        if (name.equals(SSL_ENABLED_P)) {
           boolean enabled = props.getBoolean(SSL_ENABLED_P, ssl_enabled);
           if (ssl_enabled&&(!enabled)) {
              String error = "SSL cannot be disabled dynamically.";
              daemon.errlog(error);
              if (debug) System.out.println(error);
              return false;
           }
           else {
                  if (enabled&&(!ssl_enabled)) url = null;
                  ssl_enabled = enabled;
           }
        }
        else {
               if (name.equals(SECURITY_PROVIDER_P)) {
                  String supplier = props.getString(SECURITY_PROVIDER_P, SECURITY_PROVIDER_D); 
                  try {
                        Class support = Class.forName(supplier);
	                Provider provider = (Provider)support.newInstance();
	                Security.addProvider(provider);
		        if (debug) System.out.println("Provider " + provider.toString() + " added.");
                  }
                  catch (Exception ex) {
                        String error = "Unable to add another security provider.";
   	   	        daemon.errlog(error + " (" + ex.getMessage() + ")");
                        if (debug) {
                           System.out.println(error);
                           ex.printStackTrace();
                        }
                        return false;
	          }
               }
               else {
                      if (name.equals(PROTOCOL_HANDLER_P)) {
 	                 String protocol = props.getString(PROTOCOL_HANDLER_P, PROTOCOL_HANDLER_D); 
                         if (null != protocol) {
                            System.setProperty(PROTOCOL_HANDLER_S, protocol);
		            if (debug) System.out.println("Protocol " + protocol + " added.");
                         }
                      }
                      else {
                             if (name.equals(KEYSTORE_PATH_P)) {
 	                        String keystore = props.getString(KEYSTORE_PATH_P, null); 
                                if (null != keystore) System.setProperty(KEYSTORE_PATH_S, keystore);
                             }
                             else {
                                    if (name.equals(KEYSTORE_PASSWORD_P)) {
 	                               String keypass = props.getString(KEYSTORE_PASSWORD_P, null); 
                                       if (null != keypass) System.setProperty(KEYSTORE_PASSWORD_S, keypass);
                                    }
                                    else {
                                           if (name.equals(TRUSTSTORE_PATH_P)) {
 	                                      String truststore = props.getString(TRUSTSTORE_PATH_P, null); 
                                              if (null != truststore) System.setProperty(TRUSTSTORE_PATH_S, truststore);
                                           }
                                           else {
                                                  if (name.equals(TRUSTSTORE_PASSWORD_P)) {
 	                                             String trustpass = props.getString(TRUSTSTORE_PASSWORD_P, null); 
                                                     if (null != trustpass) System.setProperty(TRUSTSTORE_PASSWORD_S, trustpass);
                                                  }
	                                   }
	                            }
	                     }
	              }
               }
        }
        return true;
    }

    /**
     * method for preparing a reply interface for a request
     * @param req the current request to be handled
     * @exception ProtocolException thrown if the request url is malformed
     */
    public void perform(RequestInterface req) 
	throws ProtocolException  {
	Request request = (Request)req;
        if (ssl_enabled) {
        
	   // set request protocol to https
	   URL url = request.getURL();
	   try {
	         request.setURL(new URL("https", url.getHost(), url.getPort(), url.getFile()));
	   } 
           catch (MalformedURLException ex) {
                 String error = "Bad url during switching to https.";
  	         daemon.errlog(error + " (" + ex.getMessage() + ")");
                 if (debug) {
                    System.out.println(error);
                    ex.printStackTrace();
                 }
                 throw new ProtocolException(ex.getMessage());
	   }
	}
    }
    
    /**
     * method for supplying a daemon uri
     * @return uri of the daemon in question
     */
    public URL getURL() {
        if (url == null) {
           if (ssl_enabled) {
	      try {
    		    if (daemon.getPort() != 443) url = new URL("https", daemon.getHost(), daemon.getPort(), "/");
	    	    else url = new URL("https", daemon.getHost(), "/");
	      }
              catch (MalformedURLException ex) {
                    if (debug) ex.printStackTrace();
     		    throw new RuntimeException("Unable to construct server uri. (" + ex.getMessage() + ")");
              }
           }
           else {
	          try {
	    	        if (daemon.getPort() != 80 ) url = new URL("http", daemon.getHost(), daemon.getPort(), "/");
	         	else url = new URL("http", daemon.getHost(), "/");
	          } 
                  catch (MalformedURLException ex) {
     		        throw new RuntimeException("Unable to construct server uri. (" + ex.getMessage() + ")");
	          }
           }
	}		
        return url;
    }

    /**
     * method for supplying a TLS support banner
     * @param banner the original banner of the daemon in question
     * @return composed banner for the daemon in question
     */
    public String getBanner(String banner) {
        if (ssl_enabled) return banner + "/SSL[" + version +"]";
        else return banner;
    }
    
    /**
     * method for indicating TLS support
     * @return flag for indicating TLS support enabled
     */
    public boolean sslEnabled() {
	return ssl_enabled;
    }
}
