/** * Removes the specified driver from the {@code DriverManager}'s list of registered drivers. * * <p>If a {@code null} value is specified for the driver to be removed, then no action is taken. * * <p>If a security manager exists and its {@code checkPermission} denies permission, then a * {@code SecurityException} will be thrown. * * <p>If the specified driver is not found in the list of registered drivers, then no action is * taken. If the driver was found, it will be removed from the list of registered drivers. * * <p>If a {@code DriverAction} instance was specified when the JDBC driver was registered, its * deregister method will be called prior to the driver being removed from the list of registered * drivers. * * @param driver the JDBC Driver to remove * @exception SQLException if a database access error occurs * @throws SecurityException if a security manager exists and its {@code checkPermission} method * denies permission to deregister a driver. * @see SecurityManager#checkPermission */ @CallerSensitive public static synchronized void deregisterDriver(Driver driver) throws SQLException { if (driver == null) { return; } SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkPermission(DEREGISTER_DRIVER_PERMISSION); } println("DriverManager.deregisterDriver: " + driver); DriverInfo aDriver = new DriverInfo(driver, null); if (registeredDrivers.contains(aDriver)) { if (isDriverAllowed(driver, Reflection.getCallerClass())) { DriverInfo di = registeredDrivers.get(registeredDrivers.indexOf(aDriver)); // If a DriverAction was specified, Call it to notify the // driver that it has been deregistered if (di.action() != null) { di.action().deregister(); } registeredDrivers.remove(aDriver); } else { // If the caller does not have permission to load the driver then // throw a SecurityException. throw new SecurityException(); } } else { println(" couldn't find driver to unload"); } }
/** * Gets the host name of this IP address. If the IP address could not be resolved, the textual * representation in a dotted-quad-notation is returned. * * @return the corresponding string name of this IP address. */ public String getHostName() { try { if (hostName == null) { int address = 0; if (ipaddress.length == 4) { address = bytesToInt(ipaddress, 0); if (address == 0) { return hostName = ipAddressToString(ipaddress); } } hostName = getHostByAddrImpl(ipaddress).hostName; if (hostName.equals("localhost") && ipaddress.length == 4 // $NON-NLS-1$ && address != 0x7f000001) { return hostName = ipAddressToString(ipaddress); } } } catch (UnknownHostException e) { return hostName = ipAddressToString(ipaddress); } SecurityManager security = System.getSecurityManager(); try { // Only check host names, not addresses if (security != null && isHostName(hostName)) { security.checkConnect(hostName, -1); } } catch (SecurityException e) { return ipAddressToString(ipaddress); } return hostName; }
/** * Load a native library using a system-independent "short name" for the library. It will be * transformed to a correct filename in a system-dependent manner (for example, in Windows, * "mylib" will be turned into "mylib.dll"). This is done as follows: if the context that called * load has a ClassLoader cl, then <code>cl.findLibrary(libpath)</code> is used to convert the * name. If that result was null, or there was no class loader, this searches each directory of * the system property <code>java.library.path</code> for a file named <code> * System.mapLibraryName(libname)</code>. There may be a security check, of <code>checkLink</code> * . * * @param libname the library to load * @throws SecurityException if permission is denied * @throws UnsatisfiedLinkError if the library is not found * @see System#mapLibraryName(String) * @see ClassLoader#findLibrary(String) */ public void loadLibrary(String libname) { // This is different from the Classpath implementation, but I // believe it is more correct. SecurityManager sm = SecurityManager.current; // Be thread-safe! if (sm != null) sm.checkLink(libname); _load(libname, true); }
/** * 删除目录(包括:目录里的所有文件) * * @param fileName * @return */ public static boolean deleteDirectory(String fileName) { boolean status; SecurityManager checker = new SecurityManager(); if (!fileName.equals("")) { // File path = Environment.getExternalStorageDirectory(); File newPath = new File(fileName); checker.checkDelete(newPath.toString()); if (newPath.isDirectory()) { String[] listfile = newPath.list(); // delete all files within the specified directory and then // delete the directory try { for (int i = 0; i < listfile.length; i++) { File deletedFile = new File(newPath.toString() + "/" + listfile[i].toString()); deletedFile.delete(); } newPath.delete(); Log.i(TAG, "DirectoryManager deleteDirectory:" + fileName); status = true; } catch (Exception e) { e.printStackTrace(); status = false; } } else status = false; } else status = false; return status; }
/** Check for permission to get a service. */ private <A> void checkAdaptPermission(Class<A> adapterType) { SecurityManager sm = System.getSecurityManager(); if (sm == null) { return; } sm.checkPermission(new AdaptPermission(adapterType.getName(), this, AdaptPermission.ADAPT)); }
public IdentityTrustModuleEntry[] getIdentityTrustModuleEntry() { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(GET_CONFIG_ENTRY_PERM); IdentityTrustModuleEntry[] entries = new IdentityTrustModuleEntry[moduleEntries.size()]; moduleEntries.toArray(entries); return entries; }
public static GSSCredential getDelegCredential() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(GET_DELEGATION_CREDENTIAL); } return DelegationSecurityActions.getDelegationCredential(); }
/** * This method initializes a new instance of <code>URL</code> with the specified protocol, host, * port, and file. Additionally, this method allows the caller to specify a protocol handler to * use instead of the default. If this handler is specified, the caller must have the * "specifyStreamHandler" permission (see <code>NetPermission</code>) or a <code>SecurityException * </code> will be thrown. * * @param protocol The protocol for this URL ("http", "ftp", etc) * @param host The hostname or IP address to connect to * @param port The port number to use, or -1 to use the protocol's default port * @param file The "file" portion of the URL. * @param ph The protocol handler to use with this URL. * @exception MalformedURLException If no protocol handler can be loaded for the specified * protocol. * @exception SecurityException If the <code>SecurityManager</code> exists and does not allow the * caller to specify its own protocol handler. * @since 1.2 */ public URL(String protocol, String host, int port, String file, URLStreamHandler ph) throws MalformedURLException { if (protocol == null) throw new MalformedURLException("null protocol"); protocol = protocol.toLowerCase(); this.protocol = protocol; if (ph != null) { SecurityManager s = System.getSecurityManager(); if (s != null) s.checkPermission(new NetPermission("specifyStreamHandler")); this.ph = ph; } else this.ph = getURLStreamHandler(protocol); if (this.ph == null) throw new MalformedURLException("Protocol handler not found: " + protocol); this.host = host; this.port = port; this.authority = (host != null) ? host : ""; if (port >= 0 && host != null) this.authority += ":" + port; int hashAt = file.indexOf('#'); if (hashAt < 0) { this.file = file; this.ref = null; } else { this.file = file.substring(0, hashAt); this.ref = file.substring(hashAt + 1); } hashCode = hashCode(); // Used for serialization. }
public static List<File> getChild(String root) { SecurityManager checker = new SecurityManager(); File path = new File(root); checker.checkRead(root); if (path.isDirectory()) return Arrays.asList(path.listFiles()); else return null; }
/** * Used to indicate whether of not we are running in an application builder environment. * * <p>Note that this method is security checked and is not available to (for example) untrusted * applets. More specifically, if there is a security manager, its <code>checkPropertiesAccess * </code> method is called. This could result in a SecurityException. * * @param isDesignTime True if we're in an application builder tool. * @exception SecurityException if a security manager exists and its <code>checkPropertiesAccess * </code> method doesn't allow setting of system properties. * @see SecurityManager#checkPropertiesAccess */ public static void setDesignTime(boolean isDesignTime) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } designTime = isDesignTime; }
/** * Used to indicate whether of not we are running in an environment where GUI interaction is * available. * * <p>Note that this method is security checked and is not available to (for example) untrusted * applets. More specifically, if there is a security manager, its <code>checkPropertiesAccess * </code> method is called. This could result in a SecurityException. * * @param isGuiAvailable True if GUI interaction is available. * @exception SecurityException if a security manager exists and its <code>checkPropertiesAccess * </code> method doesn't allow setting of system properties. * @see SecurityManager#checkPropertiesAccess */ public static void setGuiAvailable(boolean isGuiAvailable) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } guiAvailable = isGuiAvailable; }
@Override public DatagramChannel bind(SocketAddress local) throws IOException { synchronized (readLock) { synchronized (writeLock) { synchronized (stateLock) { ensureOpen(); if (localAddress != null) throw new AlreadyBoundException(); InetSocketAddress isa; if (local == null) { // only Inet4Address allowed with IPv4 socket if (family == StandardProtocolFamily.INET) { isa = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0); } else { isa = new InetSocketAddress(0); } } else { isa = Net.checkAddress(local); // only Inet4Address allowed with IPv4 socket if (family == StandardProtocolFamily.INET) { InetAddress addr = isa.getAddress(); if (!(addr instanceof Inet4Address)) throw new UnsupportedAddressTypeException(); } } SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkListen(isa.getPort()); } Net.bind(family, fd, isa.getAddress(), isa.getPort()); localAddress = Net.localAddress(fd); } } } return this; }
/** * Check that the current context is trusted to modify the logging * configuration. This requires LoggingPermission("control"). * <p> * If the check fails we throw a SecurityException, otherwise * we return normally. * * @exception SecurityException if a security manager exists and if * the caller does not have LoggingPermission("control"). */ public void checkAccess() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm == null) { return; } sm.checkPermission(ourPermission); }
private static Void checkPermission() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("localeServiceProvider")); } return null; }
public LinuxInputDevice addDevice(LinuxInputDevice device, String name) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission(new AllPermission()); } return addDeviceInternal(device, name); }
/** @see UserAdminUtil#checkPermission(String, String) */ @Override public void checkPermission(String name, String action) { SecurityManager sm = System.getSecurityManager(); if (null != sm) { sm.checkPermission(new UserAdminPermission(name, action)); } }
/** * Joins a multicast group. Its behavior may be affected by {@code setInterface} or {@code * setNetworkInterface}. * * <p>If there is a security manager, this method first calls its {@code checkMulticast} method * with the {@code mcastaddr} argument as its argument. * * @param mcastaddr is the multicast address to join * @exception IOException if there is an error joining or when the address is not a multicast * address. * @exception SecurityException if a security manager exists and its {@code checkMulticast} method * doesn't allow the join. * @see SecurityManager#checkMulticast(InetAddress) */ public void joinGroup(InetAddress mcastaddr) throws IOException { if (isClosed()) { throw new SocketException("Socket is closed"); } checkAddress(mcastaddr, "joinGroup"); SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkMulticast(mcastaddr); } if (!mcastaddr.isMulticastAddress()) { throw new SocketException("Not a multicast address"); } /** * required for some platforms where it's not possible to join a group without setting the * interface first. */ NetworkInterface defaultInterface = NetworkInterface.getDefault(); if (!interfaceSet && defaultInterface != null) { setNetworkInterface(defaultInterface); } getImpl().join(mcastaddr); }
DefaultThreadFactory(int threadPriority) { this.threadNumber = new AtomicInteger(1); this.threadPriority = threadPriority; SecurityManager s = System.getSecurityManager(); this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); this.namePrefix = "uil-pool-" + poolNumber.getAndIncrement() + "-thread-"; }
/** * Returns an InetAddress object representing the IP address of the given hostname. This name can * be either a hostname such as "www.urbanophile.com" or an IP address in dotted decimal format * such as "127.0.0.1". If the hostname is null or "", the hostname of the local machine is * supplied by default. This method is equivalent to returning the first element in the * InetAddress array returned from GetAllByName. * * @param hostname The name of the desired host, or null for the local loopback address. * @return The address of the host as an InetAddress object. * @exception UnknownHostException If no IP address for the host could be found * @exception SecurityException If a security manager exists and its checkConnect method doesn't * allow the operation */ public static InetAddress getByName(String hostname) throws UnknownHostException { // If null or the empty string is supplied, the loopback address // is returned. Note that this is permitted without a security check. if (hostname == null || hostname.length() == 0) return loopback; SecurityManager s = System.getSecurityManager(); if (s != null) s.checkConnect(hostname, -1); // Assume that the host string is an IP address byte[] address = aton(hostname); if (address != null) { if (address.length == 4) return new Inet4Address(address, null); else if (address.length == 16) { if ((address[10] == 0xFF) && (address[11] == 0xFF)) { byte[] ip4addr = new byte[4]; ip4addr[0] = address[12]; ip4addr[1] = address[13]; ip4addr[2] = address[14]; ip4addr[3] = address[15]; return new Inet4Address(ip4addr, null); } return new Inet6Address(address, null); } else throw new UnknownHostException("Address has invalid length"); } // Try to resolve the host by DNS InetAddress result = new InetAddress(null, null); lookup(hostname, result, false); return result; }
/** * Used to indicate whether of not we are running in an environment where GUI interaction is * available. * * <p>Note that this method is security checked and is not available to (for example) untrusted * applets. More specifically, if there is a security manager, its <code>checkPropertiesAccess * </code> method is called. This could result in a SecurityException. * * @param isGuiAvailable True if GUI interaction is available. * @exception SecurityException if a security manager exists and its <code>checkPropertiesAccess * </code> method doesn't allow setting of system properties. * @see SecurityManager#checkPropertiesAccess */ public static void setGuiAvailable(boolean isGuiAvailable) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } ThreadGroupContext.getContext().setGuiAvailable(isGuiAvailable); }
private static InetAddress[] getAllByName0(String host, InetAddress reqAddr, boolean check) throws UnknownHostException { /* If it gets here it is presumed to be a hostname */ /* Cache.get can return: null, unknownAddress, or InetAddress[] */ Object obj = null; Object objcopy = null; /* make sure the connection to the host is allowed, before we * give out a hostname */ if (check) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkConnect(host, -1); } } obj = getCachedAddress(host); /* If no entry in cache, then do the host lookup */ if (obj == null) { obj = getAddressFromNameService(host, reqAddr); } if (obj == unknown_array) throw new UnknownHostException(host); /* Make a copy of the InetAddress array */ objcopy = ((InetAddress[]) obj).clone(); return (InetAddress[]) objcopy; }
private static void permissionCheck() { SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkPermission(new RuntimePermission("useKeychainStore")); } }
@Override public boolean hasPermission(Object permission) { Generation current = (Generation) module.getCurrentRevision().getRevisionInfo(); ProtectionDomain domain = current.getDomain(); if (domain != null) { if (permission instanceof Permission) { SecurityManager sm = System.getSecurityManager(); if (sm instanceof EquinoxSecurityManager) { /* * If the FrameworkSecurityManager is active, we need to do checks the "right" way. * We can exploit our knowledge that the security context of FrameworkSecurityManager * is an AccessControlContext to invoke it properly with the ProtectionDomain. */ AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] {domain}); try { sm.checkPermission((Permission) permission, acc); return true; } catch (Exception e) { return false; } } return domain.implies((Permission) permission); } return false; } return true; }
/** Loads the class, provided that the calling thread has an access to the class being loaded. */ private static Class safeLoadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { logger.fine("Trying to load " + className); try { // make sure that the current thread has an access to the package of the given name. SecurityManager s = System.getSecurityManager(); if (s != null) { int i = className.lastIndexOf('.'); if (i != -1) { s.checkPackageAccess(className.substring(0, i)); } } if (classLoader == null) { return Class.forName(className); } else { return classLoader.loadClass(className); } } catch (SecurityException se) { // anyone can access the platform default factory class without permission if (PLATFORM_DEFAULT_FACTORY_CLASS.equals(className)) { return Class.forName(className); } throw se; } }
static UserPrincipal lookup(String name) throws IOException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("lookupUserInformation")); } // invoke LookupAccountName to get buffer size needed for SID int size = 0; try { size = LookupAccountName(name, 0L, 0); } catch (WindowsException x) { if (x.lastError() == ERROR_NONE_MAPPED) throw new UserPrincipalNotFoundException(name); throw new IOException(name + ": " + x.errorString()); } assert size > 0; // allocate buffer and re-invoke LookupAccountName get SID NativeBuffer sidBuffer = NativeBuffers.getNativeBuffer(size); try { int newSize = LookupAccountName(name, sidBuffer.address(), size); if (newSize != size) { // can this happen? throw new AssertionError("SID change during lookup"); } // return user principal return fromSid(sidBuffer.address()); } catch (WindowsException x) { throw new IOException(name + ": " + x.errorString()); } finally { sidBuffer.release(); } }
public ConnectionPeerIdentity getConnectionPeerIdentity() throws SecurityException { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(RemotingPermission.GET_CONNECTION_PEER_IDENTITY); } return getPeerIdentityContext().getConnectionIdentity(); }
/** * Gets the fully qualified domain name for the host associated with this IP address. If a * security manager is set, it is checked if the method caller is allowed to get the hostname. * Otherwise, the textual representation in a dotted-quad-notation is returned. * * @return the fully qualified domain name of this IP address. */ public String getCanonicalHostName() { String canonicalName; try { int address = 0; if (ipaddress.length == 4) { address = bytesToInt(ipaddress, 0); if (address == 0) { return ipAddressToString(ipaddress); } } canonicalName = getHostByAddrImpl(ipaddress).hostName; } catch (UnknownHostException e) { return ipAddressToString(ipaddress); } SecurityManager security = System.getSecurityManager(); try { // Only check host names, not addresses if (security != null && isHostName(canonicalName)) { security.checkConnect(canonicalName, -1); } } catch (SecurityException e) { return ipAddressToString(ipaddress); } return canonicalName; }
public void removeDevice(LinuxInputDevice device) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission(new AllPermission()); } devices.remove(device); }
/** * Returns the platform {@link javax.management.MBeanServer MBeanServer}. On the first call to * this method, it first creates the platform <tt>MBeanServer</tt> by calling the {@link * javax.management.MBeanServerFactory#createMBeanServer MBeanServerFactory.createMBeanServer} * method and registers the platform MXBeans in this platform <tt>MBeanServer</tt> using the <a * href="#MXBeanNames">MXBean names</a> defined in the class description. This method, in * subsequent calls, will simply return the initially created platform <tt>MBeanServer</tt>. * * <p>MXBeans that get created and destroyed dynamically, for example, memory {@link * MemoryPoolMXBean pools} and {@link MemoryManagerMXBean managers}, will automatically be * registered and deregistered into the platform <tt>MBeanServer</tt>. * * <p>If the system property <tt>javax.management.builder.initial</tt> is set, the platform * <tt>MBeanServer</tt> creation will be done by the specified {@link * javax.management.MBeanServerBuilder}. * * <p>It is recommended that this platform MBeanServer also be used to register other application * managed beans besides the platform MXBeans. This will allow all MBeans to be published through * the same <tt>MBeanServer</tt> and hence allow for easier network publishing and discovery. Name * conflicts with the platform MXBeans should be avoided. * * @return the platform <tt>MBeanServer</tt>; the platform MXBeans are registered into the * platform <tt>MBeanServer</tt> at the first time this method is called. * @exception SecurityException if there is a security manager and the caller does not have the * permission required by {@link javax.management.MBeanServerFactory#createMBeanServer}. * @see javax.management.MBeanServerFactory * @see javax.management.MBeanServerFactory#createMBeanServer */ public static synchronized MBeanServer getPlatformMBeanServer() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { Permission perm = new MBeanServerPermission("createMBeanServer"); sm.checkPermission(perm); } if (platformMBeanServer == null) { platformMBeanServer = MBeanServerFactory.createMBeanServer(); for (PlatformComponent pc : PlatformComponent.values()) { List<? extends PlatformManagedObject> list = pc.getMXBeans(pc.getMXBeanInterface()); for (PlatformManagedObject o : list) { // Each PlatformComponent represents one management // interface. Some MXBean may extend another one. // The MXBean instances for one platform component // (returned by pc.getMXBeans()) might be also // the MXBean instances for another platform component. // e.g. com.sun.management.GarbageCollectorMXBean // // So need to check if an MXBean instance is registered // before registering into the platform MBeanServer if (!platformMBeanServer.isRegistered(o.getObjectName())) { addMXBean(platformMBeanServer, o); } } } } return platformMBeanServer; }
protected void createMBeanServer() { String hostName; boolean canAccessSystemProps = true; try { // we'll do it this way mostly to determine if we should lookup the hostName SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertiesAccess(); } } catch (SecurityException se) { canAccessSystemProps = false; } if (canAccessSystemProps) { try { hostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { LOG.info("Cannot determine localhost name. Using default: " + DEFAULT_REGISTRY_PORT, uhe); hostName = DEFAULT_HOST; } } else { hostName = DEFAULT_HOST; } server = findOrCreateMBeanServer(); try { // Create the connector if we need if (createConnector) { createJmxConnector(hostName); } } catch (IOException ioe) { LOG.warn("Could not create and start JMX connector.", ioe); } }