UNIXProcess(String cmdarray[], String env[], String path) throws java.io.IOException {

    stdin_fd = new FileDescriptor();
    stdout_fd = new FileDescriptor();
    stderr_fd = new FileDescriptor();

    pid = forkAndExec(cmdarray, env, path, stdin_fd, stdout_fd, stderr_fd);

    java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction() {
          public Object run() {
            stdin_stream = new BufferedOutputStream(new FileOutputStream(stdin_fd));
            stdout_inner_stream = new DeferredCloseInputStream(stdout_fd);
            stdout_stream = new BufferedInputStream(stdout_inner_stream);
            stderr_stream = new DeferredCloseInputStream(stderr_fd);
            return null;
          }
        });

    /*
     * For each subprocess forked a corresponding reaper thread
     * is started.  That thread is the only thread which waits
     * for the subprocess to terminate and it doesn't hold any
     * locks while doing so.  This design allows waitFor() and
     * exitStatus() to be safely executed in parallel (and they
     * need no native code).
     */

    java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction() {
          public Object run() {
            Thread t =
                new Thread("process reaper") {
                  public void run() {
                    int res = waitForProcessExit(pid);
                    synchronized (UNIXProcess.this) {
                      hasExited = true;
                      exitcode = res;
                      UNIXProcess.this.notifyAll();
                    }
                  }
                };
            t.setDaemon(true);
            t.start();
            return null;
          }
        });
  }
Example #2
0
    static {
      String altThreshold =
          java.security.AccessController.doPrivileged(
              new sun.security.action.GetPropertyAction("jdk.map.althashing.threshold"));

      int threshold;
      try {
        threshold =
            (null != altThreshold)
                ? Integer.parseInt(altThreshold)
                : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;

        // disable alternative hashing if -1
        if (threshold == -1) {
          threshold = Integer.MAX_VALUE;
        }

        if (threshold < 0) {
          throw new IllegalArgumentException("value must be positive integer.");
        }
      } catch (IllegalArgumentException failed) {
        throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
      }
      ALTERNATIVE_HASHING_THRESHOLD = threshold;

      try {
        UNSAFE = sun.misc.Unsafe.getUnsafe();
        HASHSEED_OFFSET = UNSAFE.objectFieldOffset(HashMap.class.getDeclaredField("hashSeed"));
      } catch (NoSuchFieldException | SecurityException e) {
        throw new Error("Failed to record hashSeed offset", e);
      }
    }
  /*
   * The default for class root is <code>com.sun.cdc.io</code> and can be
   * replaced by setting the system property
   * <code>javax.microedition.io.Connector.protocolpath</code>.
   *
   * @return class root
   */
  protected String getClassRoot() {
    if (classRoot != null) {
      return classRoot;
    }

    String profileTemp = null;

    try {
      /*
       * Check to see if there is a property override for the dynamic
       * building of class root.
       */
      classRoot =
          (String)
              java.security.AccessController.doPrivileged(
                  new GetPropertyAction("javax.microedition.io.Connector.protocolpath"));
    } catch (Throwable t) {
      // do nothing
    }

    if (classRoot == null) {
      classRoot = "com.sun.cdc.io";
    }

    return classRoot;
  }
Example #4
0
 public CharToByteUnicode() {
   String enc =
       (String)
           java.security.AccessController.doPrivileged(
               new sun.security.action.GetPropertyAction("sun.io.unicode.encoding", "UnicodeBig"));
   if (enc.equals("UnicodeBig")) byteOrder = BIG;
   else if (enc.equals("UnicodeLittle")) byteOrder = LITTLE;
   else byteOrder = BIG;
 }
 /**
  * Initialize the maximum allowable clock skew by getting the OCSP clock skew system property. If
  * the property has not been set, or if its value is negative, set the skew to the default.
  */
 private static int initializeClockSkew() {
   Integer tmp =
       java.security.AccessController.doPrivileged(
           new GetIntegerAction("com.sun.security.ocsp.clockSkew"));
   if (tmp == null || tmp < 0) {
     return DEFAULT_MAX_CLOCK_SKEW;
   }
   // Convert to milliseconds, as the system property will be
   // specified in seconds
   return tmp * 1000;
 }
Example #6
0
  /**
   * Compute the hash an IP address. The hash is the first 8 bytes of the SHA digest of the IP
   * address.
   */
  private static byte[] computeAddressHash() {

    /*
     * Get the local host's IP address.
     */
    byte[] addr =
        (byte[])
            java.security.AccessController.doPrivileged(
                new PrivilegedAction() {
                  public Object run() {
                    try {
                      return InetAddress.getLocalHost().getAddress();
                    } catch (Exception e) {
                    }
                    return new byte[] {0, 0, 0, 0};
                  }
                });

    byte[] addrHash;
    final int ADDR_HASH_LENGTH = 8;

    try {
      /*
       * Calculate message digest of IP address using SHA.
       */
      MessageDigest md = MessageDigest.getInstance("SHA");
      ByteArrayOutputStream sink = new ByteArrayOutputStream(64);
      DataOutputStream out = new DataOutputStream(new DigestOutputStream(sink, md));
      out.write(addr, 0, addr.length);
      out.flush();

      byte digest[] = md.digest();
      int hashlength = Math.min(ADDR_HASH_LENGTH, digest.length);
      addrHash = new byte[hashlength];
      System.arraycopy(digest, 0, addrHash, 0, hashlength);

    } catch (IOException ignore) {
      /* can't happen, but be deterministic anyway. */
      addrHash = new byte[0];
    } catch (NoSuchAlgorithmException complain) {
      throw new InternalError(complain.toString());
    }
    return addrHash;
  }
Example #7
0
  public byte[] toByteArray() {

    return (byte[])
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction() {
              public Object run() {

                byte[] b = DebuggingClassWriter.super.toByteArray();
                if (debugLocation != null) {
                  String dirs = className.replace('.', File.separatorChar);
                  try {
                    new File(debugLocation + File.separatorChar + dirs).getParentFile().mkdirs();

                    File file = new File(new File(debugLocation), dirs + ".class");
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
                    try {
                      out.write(b);
                    } finally {
                      out.close();
                    }

                    if (traceEnabled) {
                      file = new File(new File(debugLocation), dirs + ".asm");
                      out = new BufferedOutputStream(new FileOutputStream(file));
                      try {
                        ClassReader cr = new ClassReader(b);
                        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
                        TraceClassVisitor tcv = new TraceClassVisitor(null, pw);
                        cr.accept(tcv, 0);
                        pw.flush();
                      } finally {
                        out.close();
                      }
                    }
                  } catch (IOException e) {
                    throw new CodeGenerationException(e);
                  }
                }
                return b;
              }
            });
  }
Example #8
0
  /**
   * Tries to load a class from: the bootstrap loader, the system loader, the context loader (if one
   * is present) and finally the loader specified.
   *
   * @param className the name of the class to be loaded
   * @param fallback the fallback loader
   * @return the class loaded
   * @exception ClassNotFoundException if class is not found
   */
  protected static final Class<?> tryToLoadClass(String className, ClassLoader fallback)
      throws ClassNotFoundException {
    ClassLoader systemClassLoader =
        (ClassLoader)
            java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction() {
                  public Object run() {
                    ClassLoader cl = Thread.currentThread().getContextClassLoader();
                    return (cl != null) ? cl : ClassLoader.getSystemClassLoader();
                  }
                });

    try {
      return Class.forName(className, true, systemClassLoader);
    } catch (ClassNotFoundException e2) {
      if (fallback != null) {
        return Class.forName(className, true, fallback);
      } else {
        throw new ClassNotFoundException(className);
      }
    }
  }
Example #9
0
  /** Utility routine for setting the context class loader. Returns previous class loader. */
  public static ClassLoader setContextClassLoader(ClassLoader newClassLoader) {

    // Can only reference final local variables from dopriveleged block
    final ClassLoader classLoaderToSet = newClassLoader;

    final Thread currentThread = Thread.currentThread();
    ClassLoader originalClassLoader = currentThread.getContextClassLoader();

    if (classLoaderToSet != originalClassLoader) {
      if (System.getSecurityManager() == null) {
        currentThread.setContextClassLoader(classLoaderToSet);
      } else {
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction() {
              public java.lang.Object run() {
                currentThread.setContextClassLoader(classLoaderToSet);
                return null;
              }
            });
      }
    }
    return originalClassLoader;
  }
Example #10
0
  public BrowserProxyInfo getBrowserProxyInfo() {
    final String IS_RELATIVE = "isrelative=";
    final String PATH_PROFILES = "path=";

    Trace.msgNetPrintln("net.proxy.loading.ns");

    File preferences = null;
    BrowserProxyInfo info = new BrowserProxyInfo();
    info.setType(ProxyType.UNKNOWN);

    try {
      String appDataDir =
          WinRegistry.getString(
              WinRegistry.HKEY_CURRENT_USER,
              "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
              "AppData");

      File profiles = new File(appDataDir + "\\mozilla\\firefox\\profiles.ini");

      if (profiles.exists()) {
        FileInputStream fis = new FileInputStream(profiles);
        InputStreamReader isr = new InputStreamReader(fis, "ISO-8859-1");
        BufferedReader in = new BufferedReader(isr);

        boolean readingProfile0 = false;
        boolean isRelative = true;
        String line;
        while ((line = in.readLine()) != null) {
          // since we can not figure out which profile is really in use, we
          // use the Profile0 data
          if (line.trim().toLowerCase().equals("[profile0]")) {
            readingProfile0 = true;
            continue;
          }

          // we take 0 as false, any other value as true
          if (readingProfile0 && line.toLowerCase().startsWith(IS_RELATIVE)) {
            try {
              int val = Integer.parseInt(line.substring(IS_RELATIVE.length()));
              isRelative = (val != 0) ? true : false;
            } catch (NumberFormatException e) {
              isRelative = true;
            }
            continue;
          }

          if (readingProfile0 && line.toLowerCase().startsWith(PATH_PROFILES)) {
            if (isRelative) {
              preferences =
                  new File(
                      appDataDir
                          + "\\mozilla\\firefox\\"
                          + line.substring(PATH_PROFILES.length())
                          + "\\prefs.js");
            } else {
              preferences = new File(line.substring(PATH_PROFILES.length()) + "\\prefs.js");
            }

            break;
          }
        }

        in.close();

        if ((preferences != null) && preferences.exists()) {
          NSPreferences.parseFile(preferences, info, 6, true);
        }
      }
    } catch (IOException e) {
      info.setType(ProxyType.UNKNOWN);
    } catch (SecurityException e) {
      Trace.netPrintException(e);
      info.setType(ProxyType.UNKNOWN);
    }

    // This is a workaroud for NS6 because of the LiveConnect bug
    //
    if (java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction("javaplugin.version"))
        != null) {
      info.setType(ProxyType.BROWSER);
    }
    Trace.msgNetPrintln("net.proxy.loading.done");

    return info;
  }
  /**
   * Instantiate a JavaBean.
   *
   * @param classLoader the class-loader from which we should create the bean. If this is null, then
   *     the system class-loader is used.
   * @param beanName the name of the bean within the class-loader. For example "sun.beanbox.foobah"
   * @exception java.lang.ClassNotFoundException if the class of a serialized object could not be
   *     found.
   * @exception java.io.IOException if an I/O error occurs.
   */
  public static Object instantiate(ClassLoader cls, String beanName)
      throws java.io.IOException, ClassNotFoundException {
    java.io.InputStream ins;
    java.io.ObjectInputStream oins = null;
    Object result = null;
    boolean serialized = false;
    java.io.IOException serex = null;
    // If the given classloader is null, we check if an
    // system classloader is available and (if so)
    // use that instead.
    // Note that calls on the system class loader will
    // look in the bootstrap class loader first.
    if (cls == null) {
      try {
        cls = ClassLoader.getSystemClassLoader();
      } catch (SecurityException ex) { // We're not allowed to access the system class loader.
        // Drop through.
      }
    }
    // Try to find a serialized object with this name
    final String serName = beanName.replace('.', '/').concat(".ser");
    final ClassLoader loader = cls;
    ins =
        (InputStream)
            java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction() {
                  public Object run() {
                    if (loader == null) return ClassLoader.getSystemResourceAsStream(serName);
                    else return loader.getResourceAsStream(serName);
                  }
                });
    if (ins != null) {
      try {
        if (cls == null) {
          oins = new ObjectInputStream(ins);
        } else {
          oins = new ObjectInputStreamWithLoader(ins, cls);
        }
        result = oins.readObject();
        serialized = true;
        oins.close();
      } catch (java.io.IOException ex) {
        ins.close();
        // Drop through and try opening the class.  But remember
        // the exception in case we can't find the class either.
        serex = ex;
      } catch (ClassNotFoundException ex) {
        ins.close();
        throw ex;
      }
    }
    if (result == null) {
      // No serialized object, try just instantiating the class
      Class cl;
      try {
        if (cls == null) {
          cl = Class.forName(beanName);
        } else {
          cl = cls.loadClass(beanName);
        }
      } catch (ClassNotFoundException ex) {
        // There is no appropriate class.  If we earlier tried to
        // deserialize an object and got an IO exception, throw that,
        // otherwise rethrow the ClassNotFoundException.
        if (serex != null) {
          throw serex;
        }
        throw ex;
      }
      /*
       * Try to instantiate the class.
       */

      try {
        result = cl.newInstance();
      } catch (Exception ex) {
        // We have to remap the exception to one in our signature.
        // But we pass extra information in the detail message.
        throw new ClassNotFoundException("" + cl + " : " + ex);
      }
    }
    if (result != null) { // Ok, if the result is an applet initialize it.
      AppletStub stub = null;

      if (result instanceof Applet) {
        Applet applet = (Applet) result;

        // Figure our the codebase and docbase URLs.  We do this
        // by locating the URL for a known resource, and then
        // massaging the URL.

        // First find the "resource name" corresponding to the bean
        // itself.  So a serialzied bean "a.b.c" would imply a
        // resource name of "a/b/c.ser" and a classname of "x.y"
        // would imply a resource name of "x/y.class".

        final String resourceName;

        if (serialized) {
          // Serialized bean
          resourceName = beanName.replace('.', '/').concat(".ser");
        } else {
          // Regular class
          resourceName = beanName.replace('.', '/').concat(".class");
        }

        URL objectUrl = null;
        URL codeBase = null;
        URL docBase = null;

        // Now get the URL correponding to the resource name.

        final ClassLoader cloader = cls;
        objectUrl =
            (URL)
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction() {
                      public Object run() {
                        if (cloader == null) return ClassLoader.getSystemResource(resourceName);
                        else return cloader.getResource(resourceName);
                      }
                    });

        // If we found a URL, we try to locate the docbase by taking
        // of the final path name component, and the code base by taking
        // of the complete resourceName.
        // So if we had a resourceName of "a/b/c.class" and we got an
        // objectURL of "file://bert/classes/a/b/c.class" then we would
        // want to set the codebase to "file://bert/classes/" and the
        // docbase to "file://bert/classes/a/b/"

        if (objectUrl != null) {
          String s = objectUrl.toExternalForm();

          if (s.endsWith(resourceName)) {
            int ix = s.length() - resourceName.length();
            codeBase = new URL(s.substring(0, ix));
            docBase = codeBase;

            ix = s.lastIndexOf('/');

            if (ix >= 0) {
              docBase = new URL(s.substring(0, ix + 1));
            }
          }
        }

        // Setup a default context and stub.
        BeansAppletContext context = new BeansAppletContext(applet);

        stub = (AppletStub) new BeansAppletStub(applet, context, codeBase, docBase);
        applet.setStub(stub);

        // If it was deserialized then it was already init-ed.
        // Otherwise we need to initialize it.

        if (!serialized) {
          // We need to set a reasonable initial size, as many
          // applets are unhappy if they are started without
          // having been explicitly sized.
          applet.setSize(100, 100);
          applet.init();
        }
        ((BeansAppletStub) stub).active = true;
      }
    }
    return result;
  }
Example #12
0
 public void run() {
   started = true;
   Thread.currentThread().setName("Q2-" + getInstanceId().toString());
   try {
     /*
      * The following code determines whether a MBeanServer exists
      * already. If so then the first one in the list is used.
      * I have not yet find a way to interrogate the server for
      * information other than MBeans so to pick a specific one
      * would be difficult.
      */
     ArrayList mbeanServerList = MBeanServerFactory.findMBeanServer(null);
     if (mbeanServerList.isEmpty()) {
       server = MBeanServerFactory.createMBeanServer(JMX_NAME);
     } else {
       server = (MBeanServer) mbeanServerList.get(0);
     }
     final ObjectName loaderName = new ObjectName(Q2_CLASS_LOADER);
     try {
       loader =
           (QClassLoader)
               java.security.AccessController.doPrivileged(
                   new java.security.PrivilegedAction() {
                     public Object run() {
                       return new QClassLoader(server, libDir, loaderName, mainClassLoader);
                     }
                   });
       server.registerMBean(loader, loaderName);
       loader = loader.scan(false);
     } catch (Throwable t) {
       if (log != null) log.error("initial-scan", t);
       else t.printStackTrace();
     }
     factory = new QFactory(loaderName, this);
     initSystemLogger();
     addShutdownHook();
     q2Thread = Thread.currentThread();
     q2Thread.setContextClassLoader(loader);
     if (cli != null) cli.start();
     initConfigDecorator();
     for (int i = 1; !shutdown; i++) {
       try {
         boolean forceNewClassLoader = scan();
         QClassLoader oldClassLoader = loader;
         loader = loader.scan(forceNewClassLoader);
         if (loader != oldClassLoader) {
           oldClassLoader = null; // We want't this to be null so it gets GCed.
           System.gc(); // force a GC
           log.info(
               "new classloader ["
                   + Integer.toString(loader.hashCode(), 16)
                   + "] has been created");
         }
         deploy();
         checkModified();
         relax(SCAN_INTERVAL);
         if (i % (3600000 / SCAN_INTERVAL) == 0) logVersion();
       } catch (Throwable t) {
         log.error("start", t);
         relax();
       }
     }
     undeploy();
     try {
       server.unregisterMBean(loaderName);
     } catch (InstanceNotFoundException e) {
       log.error(e);
     }
     if (decorator != null) {
       decorator.uninitialize();
     }
     if (exit && !shuttingDown) System.exit(0);
   } catch (Exception e) {
     if (log != null) log.error(e);
     else e.printStackTrace();
     System.exit(1);
   }
 }
  /*
   * Create and open a Connection.
   * <p>
   * There are 2 ways to find a connection implementation.
   * 1. Get the class name from a system property generated in the form of:
   * <pre>
   *    j2me.{connection protocol}.protocol
   * </pre>
   * 2. Use the class root (see getClassRoot) and the connection
   * protocol to dynamically construct a class name in the the form of:
   * <pre>
   *   {class root}.j2me.{connection protocol}.Protocol
   * </pre>
   * The connection protocol is parsed from the <code>name</code> parameter
   * which takes the form of:
   * <pre>
   *   {connection protocol}:{protocol specific part}
   * </pre>
   * In order to avoid problems with illegal
   * class file names, all the '-' characters in the connection protocol
   * are automatically converted into '_' characters.
   * <p>
   * Additionally the protocol specific part is parsed from the name
   * parameter and passed to the connection's factory method.
   *
   * @param name             The URL for the connection
   * @param mode             The access mode
   * @param timeouts         A flag to indicate that the caller
   *                         wants timeout exceptions
   *
   * @return                 A new Connection object
   *
   * @exception IllegalArgumentException If a parameter is invalid.
   * @exception ConnectionNotFoundException If the target of the
   *   name cannot be found, or if the requested protocol type
   *   is not supported.
   * @exception IOException If some other kind of I/O error occurs.
   * @exception IllegalArgumentException If a parameter is invalid.
   */
  public Connection open(String name, int mode, boolean timeouts) throws IOException {
    String oemPrefix = "";
    /* Test for null argument */
    if (name == null) {
      throw new IllegalArgumentException("Null URL");
    }
    try {
      /*
       * Check for OEM specific http and https handler override.
       */
      oemPrefix =
          (String)
              java.security.AccessController.doPrivileged(
                  new GetPropertyAction("oem.http.handler.prefix", ""));
    } catch (Throwable t) {
      // do nothing
    }

    if (name.startsWith("http")) {
      name = oemPrefix + name;
    }

    /* Look for : as in "http:", "file:", or whatever */
    int colon = name.indexOf(':');
    if (colon == -1) {
      throw new IllegalArgumentException("Illegal protocol");
    }
    try {
      String protocol;

      /* Strip off the protocol name */
      protocol = name.substring(0, colon).toLowerCase();
      checkProtocol(protocol);
      /* Strip off the rest of the string */
      name = name.substring(colon + 1);

      /*
       * Convert all the '-' characters in the protocol
       * name to '_' characters (dashes are not allowed
       * in class names).  This operation creates garbage
       * only if the protocol name actually contains dashes
       */
      protocol = protocol.replace('-', '_');

      /*
       * Use the platform and protocol names to look up
       * a class to implement the connection
       */
      String className = getClassRoot() + "." + "j2me" + "." + protocol + ".Protocol";
      Class clazz = Class.forName(className, true, getProtocolClassLoader());

      /* Construct a new instance of the protocol */
      ConnectionBaseInterface uc = (ConnectionBaseInterface) clazz.newInstance();

      /* Open the connection, and return it */
      return uc.openPrim(name, mode, timeouts);
    } catch (InstantiationException x) {
      throw new IOException(x.toString());
    } catch (IllegalAccessException x) {
      throw new IOException(x.toString());
    } catch (ClassCastException x) {
      throw new IOException(x.toString());
    } catch (ClassNotFoundException x) {
      throw new ConnectionNotFoundException("The requested protocol does not exist " + name);
    }
  }
 private static String getLogLevel() {
   return java.security.AccessController.doPrivileged(
       new sun.security.action.GetPropertyAction("sun.rmi.transport.tcp.multiplex.logLevel"));
 }