policyfile.java

来自「kaffe Java 解释器语言,源码,Java的子集系统,开放源代码」· Java 代码 · 共 675 行 · 第 1/2 页

JAVA
675
字号
/* PolicyFile.java -- policy file reader.   Copyright (C) 2003  Casey Marshall <rsdio@metastatic.org>This program is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version.This program is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with this program; see the file COPYING.  If not, write to theFree Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA02111-1307 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library.  Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule.  An independent module is a module which is not derived fromor based on this library.  If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so.  If you do not wish to do so, delete thisexception statement from your version. */package gnu.java.security;import java.io.File;import java.io.FileReader;import java.io.InputStreamReader;import java.io.IOException;import java.io.Reader;import java.io.StreamTokenizer;import java.lang.reflect.Constructor;import java.net.URL;import java.net.MalformedURLException;import java.security.AccessController;import java.security.CodeSource;import java.security.KeyStore;import java.security.KeyStoreException;import java.security.Permission;import java.security.Permissions;import java.security.PermissionCollection;import java.security.Policy;import java.security.Principal;import java.security.PrivilegedActionException;import java.security.PrivilegedExceptionAction;import java.security.Security;import java.security.UnresolvedPermission;import java.security.cert.Certificate;import java.security.cert.X509Certificate;import java.util.Enumeration;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.StringTokenizer;/** * An implementation of a {@link java.security.Policy} object whose * permissions are specified by a <em>policy file</em>. * * <p>The approximate syntax of policy files is:</p> * * <pre> * policyFile ::= keystoreOrGrantEntries ; * * keystoreOrGrantEntries ::= keystoreOrGrantEntry | *                            keystoreOrGrantEntries keystoreOrGrantEntry | *                            EMPTY ; * * keystoreOrGrantEntry ::= keystoreEntry | grantEntry ; * * keystoreEntry ::= "keystore" keystoreUrl ';' | *                   "keystore" keystoreUrl ',' keystoreAlgorithm ';' ; * * keystoreUrl ::= URL ; * keystoreAlgorithm ::= STRING ; * * grantEntry ::= "grant" domainParameters '{' permissions '}' ';' * * domainParameters ::= domainParameter | *                      domainParameter ',' domainParameters ; * * domainParameter ::= "signedBy" signerNames | *                     "codeBase" codeBaseUrl | *                     "principal" principalClassName principalName | *                     "principal" principalName ; * * signerNames ::= quotedString ; * codeBaseUrl ::= URL ; * principalClassName ::= STRING ; * principalName ::= quotedString ; * * quotedString ::= quoteChar STRING quoteChar ; * quoteChar ::= '"' | '\''; * * permissions ::= permission | permissions permission ; * * permission ::= "permission" permissionClassName permissionTarget permissionAction | *                "permission" permissionClassName permissionTarget | *                "permission" permissionClassName; * </pre> * * <p>Comments are either form of Java comments. Keystore entries only * affect subsequent grant entries, so if a grant entry preceeds a * keystore entry, that grant entry is not affected by that keystore * entry. Certian instances of <code>${property-name}</code> will be * replaced with <code>System.getProperty("property-name")</code> in * quoted strings.</p> * * <p>This class will load the following files when created or * refreshed, in order:</p> * * <ol> * <li>The file <code>${java.home}/lib/security/java.policy</code>.</li> * <li>All URLs specified by security properties * <code>"policy.file.<i>n</i>"</code>, for increasing <i>n</i> * starting from 1. The sequence stops at the first undefined * property, so you must set <code>"policy.file.1"</code> if you also * set <code>"policy.file.2"</code>, and so on.</li> * <li>The URL specified by the property * <code>"java.security.policy"</code>.</li> * </ol> * * @author Casey Marshall (rsdio@metastatic.org) * @see java.security.Policy */public final class PolicyFile extends Policy{  // Constants and fields.  // -------------------------------------------------------------------------  private static final boolean DEBUG = true;  private static void debug(String msg)  {    if (DEBUG)      {        System.err.print(">> PolicyFile: ");        System.err.println(msg);      }  }  private static void debug(Throwable t)  {    if (DEBUG)      {        System.err.println(">> PolicyFile");        t.printStackTrace(System.err);      }  }  private static final String DEFAULT_POLICY = System.getProperty("java.home")    + System.getProperty("file.separator") + "lib"    + System.getProperty("file.separator") + "security"    + System.getProperty("file.separator") + "java.policy";  private final Map cs2pc;  // Constructors.  // -------------------------------------------------------------------------  public PolicyFile()  {    cs2pc = new HashMap();    refresh();  }  // Instance methods.  // -------------------------------------------------------------------------  public PermissionCollection getPermissions(CodeSource codeSource)  {    Permissions perms = new Permissions();    for (Iterator it = cs2pc.entrySet().iterator(); it.hasNext(); )      {        Map.Entry e = (Map.Entry) it.next();        CodeSource cs = (CodeSource) e.getKey();        if (cs.implies(codeSource))          {            debug(cs+" -> "+codeSource);            PermissionCollection pc = (PermissionCollection) e.getValue();            for (Enumeration ee = pc.elements(); ee.hasMoreElements(); )              {                perms.add((Permission) ee.nextElement());              }          }        else          debug(cs+" !-> "+codeSource);      }    perms.setReadOnly();    return perms;  }  public void refresh()  {    cs2pc.clear();    List policyFiles = new LinkedList();    try      {        policyFiles.add(new File(DEFAULT_POLICY).toURL());        policyFiles.addAll((List) AccessController.doPrivileged(          new PrivilegedExceptionAction()          {            public Object run() throws Exception            {              LinkedList l = new LinkedList();              for (int i = 1; ; i++)                {                  String s = Security.getProperty("policy.file."+i);                  debug("policy.file."+i+"="+s);                  if (s == null)                    break;                  l.add(new URL(s));                }              String s = System.getProperty("java.security.policy");              debug("java.security.policy="+s);              if (s != null)                l.add(new URL(s));              return l;            }          }));      }    catch (PrivilegedActionException pae)      {        debug(pae);      }    catch (MalformedURLException mue)      {        debug(mue);      }    for (Iterator it = policyFiles.iterator(); it.hasNext(); )      {        try          {            URL url = (URL) it.next();            parse(url);          }        catch (IOException ioe)          {            debug(ioe);          }      }  }  public String toString()  {    return super.toString() + " [ " + cs2pc.toString() + " ]";  }  // Own methods.  // -------------------------------------------------------------------------  private static final int STATE_BEGIN = 0;  private static final int STATE_GRANT = 1;  private static final int STATE_PERMS = 2;  /**   * Parse a policy file, incorporating the permission definitions   * described therein.   *   * @param url The URL of the policy file to read.   * @throws IOException if an I/O error occurs, or if the policy file   * cannot be parsed.   */  private void parse(final URL url) throws IOException  {    final StreamTokenizer in = new StreamTokenizer(new InputStreamReader(url.openStream()));    in.resetSyntax();    in.slashSlashComments(true);    in.slashStarComments(true);    in.wordChars('A', 'Z');    in.wordChars('a', 'z');    in.wordChars('0', '9');    in.wordChars('.', '.');    in.wordChars('_', '_');    in.wordChars('$', '$');    in.whitespaceChars(' ', ' ');    in.whitespaceChars('\t', '\t');    in.whitespaceChars('\f', '\f');    in.whitespaceChars('\n', '\n');    in.whitespaceChars('\r', '\r');    in.quoteChar('\'');    in.quoteChar('"');    int tok;    int state = STATE_BEGIN;    List keystores = new LinkedList();    URL currentBase = null;    List currentCerts = new LinkedList();    Permissions currentPerms = new Permissions();    while ((tok = in.nextToken()) != StreamTokenizer.TT_EOF)      {        switch (tok)          {          case '{':            if (state != STATE_GRANT)              error(url, in, "spurious '{'");            state = STATE_PERMS;            tok = in.nextToken();            break;          case '}':            if (state != STATE_PERMS)              error(url, in, "spurious '}'");            state = STATE_BEGIN;            currentPerms.setReadOnly();            Certificate[] c = null;            if (!currentCerts.isEmpty())              c = (Certificate[]) currentCerts.toArray(new Certificate[currentCerts.size()]);            cs2pc.put(new CodeSource(currentBase, c), currentPerms);            currentCerts.clear();            currentPerms = new Permissions();            currentBase = null;            tok = in.nextToken();            if (tok != ';')              in.pushBack();            continue;          }        if (tok != StreamTokenizer.TT_WORD)          {            error(url, in, "expecting word token");          }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?