/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.security;

import java.lang.*;
import java.security.*;
import java.lang.reflect.*;
import java.io.File;
import java.util.Set;
import java.util.HashSet;

import javax.security.auth.Subject;
import javax.security.jacc.*;

import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.SecurityManager;
import com.sun.enterprise.security.application.EJBSecurityManager;
import com.sun.enterprise.server.pluggable.PluggableFeatureFactoryImpl;
import com.sun.enterprise.server.pluggable.SecuritySupport;
import com.sun.ejb.Container; 
import com.sun.ejb.Invocation; 
import com.sun.enterprise.security.util.IASSecurityException;
import com.sun.logging.LogDomains;
import com.sun.enterprise.util.LocalStringManagerImpl;
import com.sun.logging.*;
import java.util.logging.*;
import com.sun.web.security.WebSecurityManagerFactory;
/** 
  * This utility class encloses all the calls to a ejb method
  * in a specified subject
  * @author Harpreet Singh
  * @author Shing Wai Chan
  */
public class SecurityUtil{

    private static LocalStringManagerImpl localStrings =
	new LocalStringManagerImpl(SecurityUtil.class);
    private static Logger _logger =
        LogDomains.getLogger(LogDomains.SECURITY_LOGGER);
    public static String VENDOR_PRESENT = 
	"com.sun.enterprise.security.provider.jaccvendorpresent";
    private static boolean vendorPresent = Boolean.getBoolean(VENDOR_PRESENT);
    // The repository is defined in PolicyFileMgr.
    // It is repeated here since JACC provider is not reference directly.
    public static String repository = System.getProperty("com.sun.enterprise.jaccprovider.property.repository");
    //    private static LocalStringManagerImpl localStrings = 
    //	new LocalStringManagerImpl(SecurityUtil.class);

    /** This method is called from the generated code to execute the
     * method.  This is a translation of method.invoke that the
     * generated code needs to do, to invoke a particular ejb
     * method. The method is invoked under a security Subject. This
     * method is called from the generated code.
     * @param Method beanClassMethod, the bean class method to be invoked
     * @param Invocation inv, the current invocation object
     * @param Object o, the object on which this method needs to be invoked,
     * @param Object[] oa, the parameters to the methods,
     * @param Container c, the container from which the appropriate subject is 
     * queried from.
     */
    public static Object runMethod(Method beanClassMethod, Invocation inv, Object o, Object[] oa, Container c)
    throws Throwable {

	    final Method meth = beanClassMethod;
	    final Object obj = o;
	    final Object[] objArr = oa;
	    Object ret;
	    EJBSecurityManager mgr = (EJBSecurityManager) c.getSecurityManager();
 	    if (mgr == null) {
 		throw new SecurityException("SecurityManager not set");
	    }

            // Optimization.  Skip doAsPrivileged call if this is a local
            // invocation and the target ejb uses caller identity or the
	    // System Security Manager is disabled.
            // Still need to execute it within the target bean's policy context.
            // see CR 6331550
            if((inv.isLocal && mgr.getUsesCallerIdentity()) || 
	       System.getSecurityManager() == null) {
                ret = mgr.runMethod(meth, obj, objArr);
            } else {
                try {
                    PrivilegedExceptionAction pea =
                        new PrivilegedExceptionAction(){
                            public java.lang.Object run() throws Exception {
                                return meth.invoke(obj, objArr);
                            }
                        };

                    ret = mgr.doAsPrivileged(pea);
                } catch(PrivilegedActionException pae) {
                    Throwable cause = pae.getCause();
                    if( cause instanceof InvocationTargetException ) {
                        cause = ((InvocationTargetException) cause).getCause();
                    } 
                    throw cause;
                } 
            }
	    return ret;
    }
    /**
     * This method is similiar to the runMethod, except it keeps the
     * semantics same as the one in reflection. On failure, if the
     * exception is caused due to reflection, it returns the
     * InvocationTargetException.  This method is called from the
     * containers for ejbTimeout, WebService and MDBs.
     * @param Method beanClassMethod, the bean class method to be invoked
     * @param Invocation inv, the current invocation
     * @param Object o, the object on which this method is to be
     * invoked in this case the ejb,
     * @param Object[] oa, the parameters for the method,
     * @param Container c, the container instance, 
     * @param SecurityManager sm, security manager for this container,
     * can be a null value, where in the container will be queried to
     * find its security manager.
     * @return Object, the result of the execution of the method.
     */
    public static Object invoke(Method beanClassMethod, Invocation inv, Object o, Object[] oa, Container c, 
					       SecurityManager mgr) throws Throwable {
	
	final Method meth = beanClassMethod;
	final Object obj = o;
	final Object[] objArr = oa;
	Object ret = null;
        EJBSecurityManager ejbSecMgr = null;

 	if(mgr == null) {
	    if (c != null) {
		ejbSecMgr = (EJBSecurityManager) c.getSecurityManager();
	    }
	    if (ejbSecMgr == null) {
 		throw new SecurityException("SecurityManager not set");
	    }
	} else {
            ejbSecMgr = (EJBSecurityManager) mgr;
        }

        // Optimization.  Skip doAsPrivileged call if this is a local
        // invocation and the target ejb uses caller identity or the
	// System Security Manager is disabled.
        // Still need to execute it within the target bean's policy context.
        // see CR 6331550
        if((inv.isLocal && ejbSecMgr.getUsesCallerIdentity()) ||
	   System.getSecurityManager() == null) {
            ret = ejbSecMgr.runMethod(meth, obj, objArr);
        } else {

            PrivilegedExceptionAction pea =
                new PrivilegedExceptionAction(){
                    public java.lang.Object run() throws Exception {
                        return meth.invoke(obj, objArr);
                    }
                };
 
            try {
                ret = ejbSecMgr.doAsPrivileged(pea);
            } catch(PrivilegedActionException pae) {
                Throwable cause = pae.getCause();
                throw cause;
            } 
        }
	return ret;
    }

     /** This method obtains the policy configuration object
     *  corresponding to the name, and causes the corresponding policy
     *  statements to be put in service. This method also informs the
     *  policy module to refresh its in service policy contexts.
     *  Note that policy statements have already been
     *  added to the pc, this method works to put them in Service.
     *  @param String name - the module id which serves to identify
     *  the corresponding policy context. The name shall not be null.
     *  If the underlying PolicyModule is the RI PolicyModule, 
     *  A SecurityRoleMapper must have been bound to the policy context
     *  before this method is called or the embedded call to pc.commit will
     *  throw an exception.
     */
    public static void generatePolicyFile(String name) throws IASSecurityException {

	assert name != null;

	if (name == null) {
	    throw new IASSecurityException("Invalid Module Name");
	}

	try {

	    boolean inService = 
		PolicyConfigurationFactory.getPolicyConfigurationFactory().
		inService(name);

	    if (!inService) {

		// find the PolicyConfig using remove=false to ensure policy stmts 
		// are retained.

		// Note that it is presumed that the pc exists, and that
		// it is populated with the desired policy statements.
		// If this is not true, the call to commit will not
		// result in the correct policy statements being made
		// available to the policy module.


                PolicyConfigurationFactory pcf = 
                    PolicyConfigurationFactory.getPolicyConfigurationFactory();
                PolicyConfiguration pc =
		    pcf.getPolicyConfiguration(name, false);
                
		pc.commit();

		if (_logger.isLoggable(Level.FINE)){
		    _logger.fine("JACC: committed policy for context: "+name);
		}
	    }
     
	    Policy.getPolicy().refresh();

	} catch(java.lang.ClassNotFoundException cnfe){
	    String msg = localStrings.getLocalString("enterprise.security.securityutil.classnotfound","Could not find PolicyConfigurationFactory class. Check javax.security.jacc.PolicyConfigurationFactory.provider property");
	    throw new IASSecurityException(msg);
	} catch(javax.security.jacc.PolicyContextException pce){
	    throw new IASSecurityException(pce.toString());
	}
    }

    /** 
     * Inform the policy module to take the named policy context out of service.
     * The policy context is transitioned to the deleted state. In our provider
     * implementation, the corresponding policy file is deleted, as the presence
     * of a policy file in the repository is how we persistently remember which
     * policy contexts are in service.
     * @param String name - the module id which serves to identify
     * the corresponding policy context. The name shall not be null.
     */
    public static void removePolicy(String name) throws IASSecurityException {

	assert name != null;

	if (name == null) {
	    throw new IASSecurityException("Invalid Module Name");
	}

	try {

	    boolean wasInService = 
		PolicyConfigurationFactory.getPolicyConfigurationFactory().
		inService(name);
	    
	    // find the PolicyConfig and delete it.

	    PolicyConfiguration pc = 
		PolicyConfigurationFactory.getPolicyConfigurationFactory().
		getPolicyConfiguration(name, false);

	    pc.delete();

	    // Only do refresh policy if the deleted context was in service

	    if (wasInService) {
		Policy.getPolicy().refresh();
	    }

	} catch(java.lang.ClassNotFoundException cnfe){
	    String msg = localStrings.getLocalString("enterprise.security.securityutil.classnotfound","Could not find PolicyConfigurationFactory class. Check javax.security.jacc.PolicyConfigurationFactory.provider property");
	    throw new IASSecurityException(msg);
	} catch(javax.security.jacc.PolicyContextException pce){
	    throw new IASSecurityException(pce.toString());
	}
    }
    /** This method obtains the policy configuration object
    *  corresponding to the name, and links it, for roleMapping purposes
    *  to another. If the pc is already InService when this method is called,
    *  this method does nothing.
    *  @param String name - the module id which serves to identify
    *  the corresponding policy context. The name shall not be null.
    *  @param String linkName - the module id of the module being linked
    *  to this context. This value may be null, in which case, no link is done,
    *  but the inService state of the named PC is returned.
    *  @param boolean lastInService - the inService state returned by the previous
    *  call to this method. The value of this argument is only significant when linkName
    *  is not null.
    *  @return boolean if linkName is null, returns the inService state of the
    *  PC identified in the name argument. Otherwise returns the value
    *  passed to lastInService.
    */
    public static boolean linkPolicyFile(String name, String linkName, boolean lastInService)
    throws IASSecurityException {
        
        boolean rvalue = lastInService;
        
        assert name != null;
        
        if (name == null) {
            throw new IASSecurityException("Invalid Module Name");
        }
        try {
            PolicyConfigurationFactory pcf = PolicyConfigurationFactory.getPolicyConfigurationFactory();
            boolean inService =  pcf.inService(name);
            
            if (linkName == null) {
                rvalue = inService;
            } else if (inService == lastInService) {
                
                // only do the link if the named PC is not inService.
                if (!inService) {
                    
                    // find the PolicyConfigs using remove=false to ensure policy stmts
                    // are retained.
                    
                    PolicyConfiguration pc = 
                        pcf.getPolicyConfiguration(name, false);                    
                    PolicyConfiguration linkPc =
                        pcf.getPolicyConfiguration(linkName, false);                    
                    pc.linkConfiguration(linkPc);
                }
            } else {
                throw new IASSecurityException("Inconsistent Module State");
            }
            
        } catch(java.lang.ClassNotFoundException cnfe){
            String msg = localStrings.getLocalString("enterprise.security.securityutil.classnotfound","Could not find PolicyConfigurationFactory class. Check javax.security.jacc.PolicyConfigurationFactory.provider property");
            throw new IASSecurityException(msg);
        } catch(javax.security.jacc.PolicyContextException pce){
            throw new IASSecurityException(pce.toString());
        }        
        return rvalue;
    }


    /**
     * This method provides a single place to get SecuritySupport for security.
     */
    public static SecuritySupport getSecuritySupport() {
        return PluggableFeatureFactoryImpl.getFactory().getSecuritySupport();
    }
}
