All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zeroturnaround.javarebel.integration.google.GaeCustomSecurityManagerCBP Maven / Gradle / Ivy

The newest version!
package org.zeroturnaround.javarebel.integration.google;

import java.security.Permission;
import org.zeroturnaround.bundled.javassist.ClassPool;
import org.zeroturnaround.bundled.javassist.CtClass;
import org.zeroturnaround.javarebel.Logger;
import org.zeroturnaround.javarebel.LoggerFactory;
import org.zeroturnaround.javarebel.integration.support.JavassistClassBytecodeProcessor;

/**
 * Processes com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.
 * 
 * @author Rein Raudjärv
 */
public class GaeCustomSecurityManagerCBP extends JavassistClassBytecodeProcessor {
  
  private static final Logger log = LoggerFactory.getInstance();
  
  public void process(ClassPool cp, ClassLoader cl, CtClass ctClass) throws Exception {
    cp.importPackage("org.zeroturnaround.javarebel.integration.google");
    
    ctClass.getDeclaredMethod("checkPermission").insertBefore(
        "{" +
        "  if (GaeCustomSecurityManagerCBP.checkPermission($1))" +
        "    return;" +
        "}");
  }
  
  /**
   * Check the permission to allow actions performed by JavaRebel.
   * 
   * @param perm permission to check.
   * @return true if it the action is allowed.
   */
  public static boolean checkPermission(Permission perm) {
    try {
      /*
       * Accessing declared class members
       */
      if (perm instanceof RuntimePermission && "accessDeclaredMembers".equals(perm.getName())) {
        if (areDeclaredMembersAccessedByJavaRebel(ThreadUtil.getStackTrace()))
          return true;
      }
    } catch (Throwable t) {
      log.error(t);
    }
    return false;
  }
  
  /**
   * Process stack trace up to this number of elements.
   */
  private static final int STACK_TRACE_DEPTH = 10;
  
  /**
   * Process stack trace and return true if any of the 
   * java.lang.Class.getDeclared* methods is accessed by JavaRebel.
   */
  private static boolean areDeclaredMembersAccessedByJavaRebel(StackTraceElement[] st) {
    if (st == null)
      return false;
    
    int max = st.length - 1;
    if (max > STACK_TRACE_DEPTH)
      max = STACK_TRACE_DEPTH;
    
    for (int i = 0; i < max; i++) {
      final StackTraceElement ste = st[i];
      
      if ("java.lang.Class".equals(ste.getClassName())
          && ste.getMethodName().startsWith("getDeclared")) {
        final StackTraceElement ste2 = st[i+1];
        if (ste2.getClassName().startsWith("com.zeroturnaround.javarebel")) {
          return true;
        }
      }
      
    }
    return false;
  }
  
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy