/**
 * 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.socket;

import java.net.*;
import java.io.IOException;

import javax.net.ssl.*;
import javax.net.ServerSocketFactory;

import org.w3c.jigsaw.http.httpd;
import org.w3c.jigsaw.http.socket.SocketClientFactory;
import org.w3c.util.ObservableProperties;

/**
 * @author Thomas Kopp, Dialogika GmbH
 * @version 1.0.2, 27 December 2000
 * 
 * This class extends a Jigsaw SocketClientFactory designed for the http protocol
 * in order to supply a SocketClientFactory for the https protocol 
 * in accordance with the JSSE API.
 */
public class SSLSocketClientFactory extends SocketClientFactory {

    /**
     * static flag for enabling debug output if applicable
     */
    private static boolean debug = false;
    
    /**
     * static basic factory for the SocketClientFactory with TLS support
     */
    private static ServerSocketFactory factory = null;
    
    /**
     * the daemon of this factory
     */
    httpd daemon = null;
    
    /**
     * the daemon bind address for this factory
     */
    InetAddress bindAddr = null;
    
    /**
     * the daemon bind address for this factory
     */
    int maxClients = 0;

    /**
     * method for creating a secure server socket
     * @return a new server socket instance
     */
    public ServerSocket createServerSocket() 
	throws IOException {
        int port = daemon.getPort();
        int clients = Math.max(128, maxClients);
        ServerSocket serversocket = null;
        if (bindAddr == null) serversocket = factory.createServerSocket(port, clients);
	else serversocket = factory.createServerSocket(port, clients, bindAddr);
        // Client authentication does not yet work with recent browsers.
        // The following lines would have to be uncommented for implementing client authentication
        // in addition to add client certificate chain verification.
        // tk, 8 April 2001
        // if (serversocket instanceof SSLServerSocket) {
        //    SSLServerSocket sslserversocket = (SSLServerSocket)serversocket;
        //    sslserversocket.setNeedClientAuth(true);
        // }
        return serversocket;
    }

    /**
     * method for intializing this factory
     * @param server the daemon of this factory
     */
    public void initialize(httpd server) {
        super.initialize(server);
	daemon = server;
        ObservableProperties props = daemon.getProperties();
        String bindAddrName = props.getString(BINDADDR_P, null);
	if (bindAddrName != null) {
	   try {
	         bindAddr = InetAddress.getByName(bindAddrName);
	   } 
           catch (Exception ex) {
                 bindAddr = null;
           }
	}
        else bindAddr = null;
        maxClients = props.getInteger(MAXCLIENTS_P, MAXCLIENTS);
    }

    /**
     * method for handling a dynamic property modification
     * @param name the name of the property modified
     * @return true if and only if the modification has been handled successfully
     */
    public boolean propertyChanged(String name) {
        if (super.propertyChanged(name)) {
           ObservableProperties props = daemon.getProperties();
           if (name.equals(MAXCLIENTS_P)) {
	      int newmax = props.getInteger(MAXCLIENTS_P, -1);
	      if (newmax > maxClients) {
	         for (int i = maxClients-newmax; --i >= 0; ) addClient(true);
	      }
              else if (newmax > 0) maxClients = newmax;
   	   } 
           else {
                  if (name.equals(BINDADDR_P)) {
	             try {
		           bindAddr = InetAddress.getByName(props.getString(BINDADDR_P, null));
	             } 
                     catch (Exception ex) {
                           bindAddr = null;
                     }
                  }
	   }
           return true;
        }
        else return false; 
    }

    /**
     * default constructor of this factory
     */
    public SSLSocketClientFactory() {
        super();
        if (null == factory) {
           factory = SSLServerSocketFactory.getDefault();
           
           String[] supported = ((SSLServerSocketFactory)factory).getSupportedCipherSuites();
           if (debug) {
              System.out.println("Supported suites:");
              for (int i = 0; i < supported.length; i++) System.out.println("          " + supported[i]);
           
              String[] enabled = ((SSLServerSocketFactory)factory).getDefaultCipherSuites();
              System.out.println("Enabled suites:");
              for (int i = 0; i < enabled.length; i++) System.out.println("         " + enabled[i]);
           }
           
           if (supported.length < 1) {
              String error = "No cipher suites supported by this SSL socket factory.\n"
                           + "Please check your factory, key store, store password and cerificates.";
              if (debug) System.out.println(error);
              throw new RuntimeException(error);
           }
        }
    }
}
