socketpermission.java

来自「This is a resource based on j2me embedde」· Java 代码 · 共 1,225 行 · 第 1/3 页

JAVA
1,225
字号
/* * @(#)SocketPermission.java	1.48 06/10/10 * * Copyright  1990-2008 Sun Microsystems, Inc. All Rights Reserved.   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER   *    * This program is free software; you can redistribute it and/or   * modify it under the terms of the GNU General Public License version   * 2 only, as published by the Free Software Foundation.    *    * This program is distributed in the hope that it will be useful, but   * WITHOUT ANY WARRANTY; without even the implied warranty of   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU   * General Public License version 2 for more details (a copy is   * included at /legal/license.txt).    *    * You should have received a copy of the GNU General Public License   * version 2 along with this work; if not, write to the Free Software   * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA   * 02110-1301 USA    *    * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa   * Clara, CA 95054 or visit www.sun.com if you need additional   * information or have any questions.  * */ package java.net;import java.util.Enumeration;import java.util.Vector;import java.util.List;import java.util.ArrayList;import java.util.Collections;import java.util.StringTokenizer;import java.net.InetAddress;import java.security.Permission;import java.security.PermissionCollection;import java.io.Serializable;import java.io.ObjectStreamField;import java.io.ObjectOutputStream;import java.io.ObjectInputStream;import java.io.IOException;import sun.security.util.SecurityConstants;/** * This class represents access to a network via sockets. * A SocketPermission consists of a  * host specification and a set of "actions" specifying ways to * connect to that host. The host is specified as * <pre> *    host = (hostname | IPv4address | iPv6reference) [:portrange] *    portrange = portnumber | -portnumber | portnumber-[portnumber] * </pre> * The host is expressed as a DNS name, as a numerical IP address, * or as "localhost" (for the local machine). * The wildcard "*" may be included once in a DNS name host * specification. If it is included, it must be in the leftmost  * position, as in "*.sun.com". * <p> * The format of the IPv6reference should follow that specified in <a * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format * for Literal IPv6 Addresses in URLs</i></a>: * <pre> *    ipv6reference = "[" IPv6address "]" *</pre> * For example, you can construct a SocketPermission instance * as the following: * <pre> *    String hostAddress = inetaddress.getHostAddress(); *    if (inetaddress instanceof Inet6Address) { *        sp = new SocketPermission("[" + hostAddress + "]:" + port, action); *    } else { *        sp = new SocketPermission(hostAddress + ":" + port, action); *    } * </pre> * or * <pre> *    String host = url.getHost(); *    sp = new SocketPermission(host + ":" + port, action); * </pre> * <p> * The <A HREF="Inet6Address.html#lform">full uncompressed form</A> of * an IPv6 literal address is also valid. * <p> * The port or portrange is optional. A port specification of the  * form "N-", where <i>N</i> is a port number, signifies all ports * numbered <i>N</i> and above, while a specification of the * form "-N" indicates all ports numbered <i>N</i> and below. * <p> * The possible ways to connect to the host are  * <pre> * accept * connect * listen * resolve * </pre> * The "listen" action is only meaningful when used with "localhost".  * The "resolve" action is implied when any of the other actions are present. * The action "resolve" refers to host/ip name service lookups. *  * <p>As an example of the creation and meaning of SocketPermissions,   * note that if the following permission: *  * <pre> *   p1 = new SocketPermission("puffin.eng.sun.com:7777", "connect,accept"); * </pre> *  * is granted to some code, it allows that code to connect to port 7777 on * <code>puffin.eng.sun.com</code>, and to accept connections on that port. *  * <p>Similarly, if the following permission: *  * <pre> *   p1 = new SocketPermission("puffin.eng.sun.com:7777", "connect,accept"); *   p2 = new SocketPermission("localhost:1024-", "accept,connect,listen"); * </pre> *  * is granted to some code, it allows that code to  * accept connections on, connect to, or listen on any port between * 1024 and 65535 on the local host. * * <p>Note: Granting code permission to accept or make connections to remote * hosts may be dangerous because malevolent code can then more easily * transfer and share confidential data among parties who may not * otherwise have access to the data. *  * @see java.security.Permissions * @see SocketPermission * * @version 1.41 10/27/00 * * @author Marianne Mueller * @author Roland Schemers  * * @serial exclude */public final class SocketPermission extends Permission implements java.io.Serializable {    private static final long serialVersionUID = -7204263841984476862L;    /**     * Connect to host:port     */    private final static int CONNECT	= 0x1;    /**     * Listen on host:port     */    private final static int LISTEN	= 0x2;    /**     * Accept a connection from host:port     */    private final static int ACCEPT	= 0x4;    /**     * Resolve DNS queries     */    private final static int RESOLVE	= 0x8;    /**     * No actions     */    private final static int NONE		= 0x0;    /**     * All actions     */     private final static int ALL	= CONNECT|LISTEN|ACCEPT|RESOLVE;    // various port constants    private static final int PORT_MIN = 0;    private static final int PORT_MAX = 65535;    private static final int PRIV_PORT_MAX = 1023;    // the actions mask    private transient int mask;    /**     * the actions string.      *     * @serial     */    private String actions; // Left null as long as possible, then                            // created and re-used in the getAction function.    // hostname part as it is passed    private transient String hostname;        // the canonical name of the host    // in the case of "*.foo.com", cname is ".foo.com".    private transient String cname;    // all the IP addresses of the host     private transient InetAddress[] addresses;    // true if the hostname is a wildcard (e.g. "*.sun.com")    private transient boolean wildcard;    // true if we were initialized with a single numeric IP address    private transient boolean init_with_ip;    // true if this SocketPermission represents an invalid/unknown host    // used for implies when the delayed lookup has already failed    private transient boolean invalid;    // port range on host    private transient int[] portrange;     // true if the trustProxy system property is set    private static boolean trustProxy;    static {	Boolean tmp = (Boolean) java.security.AccessController.doPrivileged(                new sun.security.action.GetBooleanAction("trustProxy"));	trustProxy = tmp.booleanValue();    }    /**     * Creates a new SocketPermission object with the specified actions.     * The host is expressed as a DNS name, or as a numerical IP address.     * Optionally, a port or a portrange may be supplied (separated     * from the DNS name or IP address by a colon).     * <p>     * To specify the local machine, use "localhost" as the <i>host</i>.     * Also note: An empty <i>host</i> String ("") is equivalent to "localhost".     * <p>     * The <i>actions</i> parameter contains a comma-separated list of the     * actions granted for the specified host (and port(s)). Possible actions are     * "connect", "listen", "accept", "resolve", or      * any combination of those. "resolve" is automatically added     * when any of the other three are specified.     * <p>     * Examples of SocketPermission instantiation are the following:      * <pre>     *    nr = new SocketPermission("www.catalog.com", "connect");     *    nr = new SocketPermission("www.sun.com:80", "connect");     *    nr = new SocketPermission("*.sun.com", "connect");     *    nr = new SocketPermission("*.edu", "resolve");     *    nr = new SocketPermission("204.160.241.0", "connect");     *    nr = new SocketPermission("localhost:1024-65535", "listen");     *    nr = new SocketPermission("204.160.241.0:1024-65535", "connect");     * </pre>     *      * @param host the hostname or IPaddress of the computer, optionally     * including a colon followed by a port or port range.      * @param action the action string.     */    public SocketPermission(String host, String action) {	super(getHost(host));	// name initialized to getHost(host); NPE detected in getHost()	init(getName(), getMask(action));    }    SocketPermission(String host, int mask) {	super(getHost(host));	// name initialized to getHost(host); NPE detected in getHost()	init(getName(), mask);    }    private static String getHost(String host)    {	if (host.equals("")) {	    return "localhost";	} else { 	    /* IPv6 literal address used in this context should follow	     * the format specified in RFC 2732;	     * if not, we try to solve the unambiguous case	     */	    int ind;	    if (host.charAt(0) != '[') {		if ((ind = host.indexOf(':')) != host.lastIndexOf(':')) {		    /* More than one ":", meaning IPv6 address is not		     * in RFC 2732 format;		     * We will rectify user errors for all unambiguious cases		     */		    StringTokenizer st = new StringTokenizer(host, ":");		    int tokens = st.countTokens();		    if (tokens == 9) {			// IPv6 address followed by port			ind = host.lastIndexOf(':');			host = "[" + host.substring(0, ind) + "]" +			    host.substring(ind);		    } else if (tokens == 8 && host.indexOf("::") == -1) {			// IPv6 address only, not followed by port			host = "[" + host + "]";		    } else {			// could be ambiguous			throw new IllegalArgumentException("Ambiguous"+							   " hostport part");		    }		}	    }	    return host;	}    }    private int[] parsePort(String port) 	throws Exception    {	if (port == null || port.equals("") || port.equals("*")) {	    return new int[] {PORT_MIN, PORT_MAX};	}	int dash = port.indexOf('-');	if (dash == -1) {	    int p = Integer.parseInt(port);	    return new int[] {p, p};	} else {	    String low = port.substring(0, dash);	    String high = port.substring(dash+1);	    int l,h;	    if (low.equals("")) {		l = PORT_MIN;	    } else {		l = Integer.parseInt(low);	    }	    if (high.equals("")) {		h = PORT_MAX;	    } else {		h = Integer.parseInt(high);	    }	    if (l < 0 || h < 0 || h<l) 		throw new IllegalArgumentException("invalid port range");	    return new int[] {l, h};	}    }    /**     * Initialize the SocketPermission object. We don't do any DNS lookups     * as this point, instead we hold off until the implies method is     * called.     */    private void init(String host, int mask) {	// Set the integer mask that represents the actions	if ((mask & ALL) != mask) 	    throw new IllegalArgumentException("invalid actions mask");	// always OR in RESOLVE if we allow any of the others	this.mask = mask | RESOLVE;	// Parse the host name.  A name has up to three components, the	// hostname, a port number, or two numbers representing a port	// range.   "www.sun.com:8080-9090" is a valid host name.  	// With IPv6 an address can be 2010:836B:4179::836B:4179 	// An IPv6 address needs to be enclose in [] 	// For ex: [2010:836B:4179::836B:4179]:8080-9090 	// Refer to RFC 2732 for more information. 		int rb = 0 ;	int start = 0, end = 0;	int sep = -1;	String hostport = host;	if (host.charAt(0) == '[') {	    start = 1;	    rb = host.indexOf(']');	    if (rb != -1) {		host = host.substring(start, rb);	    } else {		throw new 		    IllegalArgumentException("invalid host/port: "+host);	    }	    sep = hostport.indexOf(':', rb+1);	} else {	    start = 0;	    sep = host.indexOf(':', rb);	    end = sep;	    if (sep != -1) {		host = host.substring(start, end);	    }	}		if (sep != -1) {	    String port = hostport.substring(sep+1);	    try {		portrange = parsePort(port);	    } catch (Exception e) {		throw new 		    IllegalArgumentException("invalid port range: "+port);	    }	} else {	    portrange = new int[] { PORT_MIN, PORT_MAX };	}	    	hostname = host;	// is this a domain wildcard specification	if (host.lastIndexOf('*') > 0) {	    throw new 	       IllegalArgumentException("invalid host wildcard specification");	} else if (host.startsWith("*")) {	    wildcard = true;	    if (host.equals("*")) {		cname = "";	    } else if (host.startsWith("*.")) {

⌨️ 快捷键说明

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